• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app.admin;
18 
19 import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
20 
21 import android.Manifest.permission;
22 import android.annotation.CallbackExecutor;
23 import android.annotation.ColorInt;
24 import android.annotation.IntDef;
25 import android.annotation.NonNull;
26 import android.annotation.Nullable;
27 import android.annotation.RequiresFeature;
28 import android.annotation.RequiresPermission;
29 import android.annotation.SdkConstant;
30 import android.annotation.SdkConstant.SdkConstantType;
31 import android.annotation.StringDef;
32 import android.annotation.SuppressLint;
33 import android.annotation.SystemApi;
34 import android.annotation.SystemService;
35 import android.annotation.TestApi;
36 import android.annotation.UnsupportedAppUsage;
37 import android.annotation.UserIdInt;
38 import android.annotation.WorkerThread;
39 import android.app.Activity;
40 import android.app.IServiceConnection;
41 import android.app.KeyguardManager;
42 import android.app.admin.SecurityLog.SecurityEvent;
43 import android.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”> Note: This is a protected intent that can only be sent by the system.</p>
1555      */
1556     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1557     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1558             "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1559 
1560     /**
1561      * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1562      * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1563      */
1564     public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1565 
1566     /**
1567      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1568      * the parent profile to access intents sent from the managed profile.
1569      * That is, when an app in the managed profile calls
1570      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1571      * matching activity in the parent profile.
1572      */
1573     public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1574 
1575     /**
1576      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1577      * the managed profile to access intents sent from the parent profile.
1578      * That is, when an app in the parent profile calls
1579      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1580      * matching activity in the managed profile.
1581      */
1582     public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1583 
1584     /**
1585      * Broadcast action: notify that a new local system update policy has been set by the device
1586      * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1587      */
1588     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1589     public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1590             = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1591 
1592     /**
1593      * Broadcast action to notify ManagedProvisioning that
1594      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has changed.
1595      * @hide
1596      */
1597     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1598     public static final String ACTION_DATA_SHARING_RESTRICTION_CHANGED =
1599             "android.app.action.DATA_SHARING_RESTRICTION_CHANGED";
1600 
1601     /**
1602      * Broadcast action from ManagedProvisioning to notify that the latest change to
1603      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
1604      * applied (cross profile intent filters updated). Only usesd for CTS tests.
1605      * @hide
1606      */
1607     @TestApi
1608     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1609     public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
1610             "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
1611 
1612     /**
1613      * Permission policy to prompt user for new permission requests for runtime permissions.
1614      * Already granted or denied permissions are not affected by this.
1615      */
1616     public static final int PERMISSION_POLICY_PROMPT = 0;
1617 
1618     /**
1619      * Permission policy to always grant new permission requests for runtime permissions.
1620      * Already granted or denied permissions are not affected by this.
1621      */
1622     public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1623 
1624     /**
1625      * Permission policy to always deny new permission requests for runtime permissions.
1626      * Already granted or denied permissions are not affected by this.
1627      */
1628     public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1629 
1630     /**
1631      * Possible policy values for permissions.
1632      *
1633      * @hide
1634      */
1635     @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = {
1636             PERMISSION_GRANT_STATE_DEFAULT,
1637             PERMISSION_GRANT_STATE_GRANTED,
1638             PERMISSION_GRANT_STATE_DENIED
1639     })
1640     @Retention(RetentionPolicy.SOURCE)
1641     public @interface PermissionGrantState {}
1642 
1643     /**
1644      * Runtime permission state: The user can manage the permission
1645      * through the UI.
1646      */
1647     public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1648 
1649     /**
1650      * Runtime permission state: The permission is granted to the app
1651      * and the user cannot manage the permission through the UI.
1652      */
1653     public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1654 
1655     /**
1656      * Runtime permission state: The permission is denied to the app
1657      * and the user cannot manage the permission through the UI.
1658      */
1659     public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1660 
1661     /**
1662      * Delegation of certificate installation and management. This scope grants access to the
1663      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1664      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1665      */
1666     public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1667 
1668     /**
1669      * Delegation of application restrictions management. This scope grants access to the
1670      * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1671      */
1672     public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1673 
1674     /**
1675      * Delegation of application uninstall block. This scope grants access to the
1676      * {@link #setUninstallBlocked} API.
1677      */
1678     public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1679 
1680     /**
1681      * Delegation of permission policy and permission grant state. This scope grants access to the
1682      * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1683      * and {@link #setPermissionGrantState} APIs.
1684      */
1685     public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1686 
1687     /**
1688      * Delegation of package access state. This scope grants access to the
1689      * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1690      * {@link #setPackagesSuspended} APIs.
1691      */
1692     public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1693 
1694     /**
1695      * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1696      * API.
1697      */
1698     public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1699 
1700     /**
1701      * Delegation for installing existing packages. This scope grants access to the
1702      * {@link #installExistingPackage} API.
1703      */
1704     public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
1705             "delegation-install-existing-package";
1706 
1707     /**
1708      * Delegation of management of uninstalled packages. This scope grants access to the
1709      * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs.
1710      */
1711     public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1712             "delegation-keep-uninstalled-packages";
1713 
1714     /**
1715      * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and
1716      * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving
1717      * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner will no longer
1718      * receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback.
1719      * There can be at most one app that has this delegation.
1720      * If another app already had delegated network logging access,
1721      * it will lose the delegation when a new app is delegated.
1722      *
1723      * <p> Can only be granted by Device Owner.
1724      */
1725     public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
1726 
1727     /**
1728      * Grants access to selection of KeyChain certificates on behalf of requesting apps.
1729      * Once granted the app will start receiving
1730      * DelegatedAdminReceiver.onChoosePrivateKeyAlias. The caller (PO/DO) will
1731      * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}.
1732      * There can be at most one app that has this delegation.
1733      * If another app already had delegated certificate selection access,
1734      * it will lose the delegation when a new app is delegated.
1735      *
1736      * <p> Can be granted by Device Owner or Profile Owner.
1737      */
1738     public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
1739 
1740     /**
1741      * No management for current user in-effect. This is the default.
1742      * @hide
1743      */
1744     @SystemApi
1745     public static final int STATE_USER_UNMANAGED = 0;
1746 
1747     /**
1748      * Management partially setup, user setup needs to be completed.
1749      * @hide
1750      */
1751     @SystemApi
1752     public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1753 
1754     /**
1755      * Management partially setup, user setup completed.
1756      * @hide
1757      */
1758     @SystemApi
1759     public static final int STATE_USER_SETUP_COMPLETE = 2;
1760 
1761     /**
1762      * Management setup and active on current user.
1763      * @hide
1764      */
1765     @SystemApi
1766     public static final int STATE_USER_SETUP_FINALIZED = 3;
1767 
1768     /**
1769      * Management partially setup on a managed profile.
1770      * @hide
1771      */
1772     @SystemApi
1773     public static final int STATE_USER_PROFILE_COMPLETE = 4;
1774 
1775     /**
1776      * @hide
1777      */
1778     @IntDef(prefix = { "STATE_USER_" }, value = {
1779             STATE_USER_UNMANAGED,
1780             STATE_USER_SETUP_INCOMPLETE,
1781             STATE_USER_SETUP_COMPLETE,
1782             STATE_USER_SETUP_FINALIZED,
1783             STATE_USER_PROFILE_COMPLETE
1784     })
1785     @Retention(RetentionPolicy.SOURCE)
1786     public @interface UserProvisioningState {}
1787 
1788     /**
1789      * Result code for {@link #checkProvisioningPreCondition}.
1790      *
1791      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1792      * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1793      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when provisioning is allowed.
1794      *
1795      * @hide
1796      */
1797     public static final int CODE_OK = 0;
1798 
1799     /**
1800      * Result code for {@link #checkProvisioningPreCondition}.
1801      *
1802      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1803      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the device already has a device
1804      * owner.
1805      *
1806      * @hide
1807      */
1808     public static final int CODE_HAS_DEVICE_OWNER = 1;
1809 
1810     /**
1811      * Result code for {@link #checkProvisioningPreCondition}.
1812      *
1813      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1814      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user has a profile owner and for
1815      * {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
1816      *
1817      * @hide
1818      */
1819     public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
1820 
1821     /**
1822      * Result code for {@link #checkProvisioningPreCondition}.
1823      *
1824      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1825      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user isn't running.
1826      *
1827      * @hide
1828      */
1829     public static final int CODE_USER_NOT_RUNNING = 3;
1830 
1831     /**
1832      * Result code for {@link #checkProvisioningPreCondition}.
1833      *
1834      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1835      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the device has already been setup and
1836      * for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
1837      *
1838      * @hide
1839      */
1840     public static final int CODE_USER_SETUP_COMPLETED = 4;
1841 
1842     /**
1843      * Code used to indicate that the device also has a user other than the system user.
1844      *
1845      * @hide
1846      */
1847     public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
1848 
1849     /**
1850      * Code used to indicate that device has an account that prevents provisioning.
1851      *
1852      * @hide
1853      */
1854     public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
1855 
1856     /**
1857      * Result code for {@link #checkProvisioningPreCondition}.
1858      *
1859      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1860      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the user is not a system user.
1861      *
1862      * @hide
1863      */
1864     public static final int CODE_NOT_SYSTEM_USER = 7;
1865 
1866     /**
1867      * Result code for {@link #checkProvisioningPreCondition}.
1868      *
1869      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1870      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} and {@link #ACTION_PROVISION_MANAGED_USER}
1871      * when the device is a watch and is already paired.
1872      *
1873      * @hide
1874      */
1875     public static final int CODE_HAS_PAIRED = 8;
1876 
1877     /**
1878      * Result code for {@link #checkProvisioningPreCondition}.
1879      *
1880      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
1881      * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
1882      *
1883      * @see {@link PackageManager#FEATURE_MANAGED_USERS}
1884      * @hide
1885      */
1886     public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
1887 
1888     /**
1889      * Result code for {@link #checkProvisioningPreCondition}.
1890      *
1891      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user.
1892      *
1893      * @hide
1894      */
1895     public static final int CODE_SYSTEM_USER = 10;
1896 
1897     /**
1898      * Result code for {@link #checkProvisioningPreCondition}.
1899      *
1900      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
1901      * managed profiles.
1902      *
1903      * @hide
1904      */
1905     public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
1906 
1907     /**
1908      * Result code for {@link #checkProvisioningPreCondition}.
1909      *
1910      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} and
1911      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices not running with split system
1912      * user.
1913      *
1914      * @hide
1915      */
1916     public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
1917 
1918     /**
1919      * Result code for {@link #checkProvisioningPreCondition}.
1920      *
1921      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1922      * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1923      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices which do no support device
1924      * admins.
1925      *
1926      * @hide
1927      */
1928     public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
1929 
1930     /**
1931      * Result code for {@link #checkProvisioningPreCondition}.
1932      *
1933      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the device the user is a
1934      * system user on a split system user device.
1935      *
1936      * @hide
1937      */
1938     public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
1939 
1940     /**
1941      * Result code for {@link #checkProvisioningPreCondition}.
1942      *
1943      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when adding a managed profile is
1944      * disallowed by {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
1945      *
1946      * @hide
1947      */
1948     public static final int CODE_ADD_MANAGED_PROFILE_DISALLOWED = 15;
1949 
1950     /**
1951      * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
1952      * conditions.
1953      *
1954      * @hide
1955      */
1956     @Retention(RetentionPolicy.SOURCE)
1957     @IntDef(prefix = { "CODE_" }, value = {
1958             CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
1959             CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
1960             CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
1961             CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
1962             CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER, CODE_ADD_MANAGED_PROFILE_DISALLOWED
1963     })
1964     public @interface ProvisioningPreCondition {}
1965 
1966     /**
1967      * Disable all configurable SystemUI features during LockTask mode. This includes,
1968      * <ul>
1969      *     <li>system info area in the status bar (connectivity icons, clock, etc.)
1970      *     <li>notifications (including alerts, icons, and the notification shade)
1971      *     <li>Home button
1972      *     <li>Recents button and UI
1973      *     <li>global actions menu (i.e. power button menu)
1974      *     <li>keyguard
1975      * </ul>
1976      *
1977      * @see #setLockTaskFeatures(ComponentName, int)
1978      */
1979     public static final int LOCK_TASK_FEATURE_NONE = 0;
1980 
1981     /**
1982      * Enable the system info area in the status bar during LockTask mode. The system info area
1983      * usually occupies the right side of the status bar (although this can differ across OEMs). It
1984      * includes all system information indicators, such as date and time, connectivity, battery,
1985      * vibration mode, etc.
1986      *
1987      * @see #setLockTaskFeatures(ComponentName, int)
1988      */
1989     public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
1990 
1991     /**
1992      * Enable notifications during LockTask mode. This includes notification icons on the status
1993      * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
1994      * Settings panel remains disabled. This feature flag can only be used in combination with
1995      * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
1996      * throws an {@link IllegalArgumentException} if this feature flag is defined without
1997      * {@link #LOCK_TASK_FEATURE_HOME}.
1998      *
1999      * @see #setLockTaskFeatures(ComponentName, int)
2000      */
2001     public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
2002 
2003     /**
2004      * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
2005      * to be registered as the default launcher with
2006      * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
2007      * package needs to be whitelisted for LockTask with
2008      * {@link #setLockTaskPackages(ComponentName, String[])}.
2009      *
2010      * @see #setLockTaskFeatures(ComponentName, int)
2011      */
2012     public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
2013 
2014     /**
2015      * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
2016      * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
2017      * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
2018      * {@link IllegalArgumentException} if this feature flag is defined without
2019      * {@link #LOCK_TASK_FEATURE_HOME}.
2020      *
2021      * @see #setLockTaskFeatures(ComponentName, int)
2022      */
2023     public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
2024 
2025     /**
2026      * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
2027      * the user long-presses the power button, for example. Note that the user may not be able to
2028      * power off the device if this flag is not set.
2029      *
2030      * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
2031      * called for the first time.
2032      *
2033      * @see #setLockTaskFeatures(ComponentName, int)
2034      */
2035     public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
2036 
2037     /**
2038      * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
2039      * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
2040      * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
2041      * credential.
2042      *
2043      * @see #setLockTaskFeatures(ComponentName, int)
2044      */
2045     public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
2046 
2047     /**
2048      * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
2049      *
2050      * @hide
2051      */
2052     @Retention(RetentionPolicy.SOURCE)
2053     @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
2054             LOCK_TASK_FEATURE_NONE,
2055             LOCK_TASK_FEATURE_SYSTEM_INFO,
2056             LOCK_TASK_FEATURE_NOTIFICATIONS,
2057             LOCK_TASK_FEATURE_HOME,
2058             LOCK_TASK_FEATURE_OVERVIEW,
2059             LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
2060             LOCK_TASK_FEATURE_KEYGUARD
2061     })
2062     public @interface LockTaskFeature {}
2063 
2064     /**
2065      * Service action: Action for a service that device owner and profile owner can optionally
2066      * own.  If a device owner or a profile owner has such a service, the system tries to keep
2067      * a bound connection to it, in order to keep their process always running.
2068      * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
2069      * permission.
2070      */
2071     @SdkConstant(SdkConstantType.SERVICE_ACTION)
2072     public static final String ACTION_DEVICE_ADMIN_SERVICE
2073             = "android.app.action.DEVICE_ADMIN_SERVICE";
2074 
2075     /** @hide */
2076     @Retention(RetentionPolicy.SOURCE)
2077     @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
2078         ID_TYPE_BASE_INFO,
2079         ID_TYPE_SERIAL,
2080         ID_TYPE_IMEI,
2081         ID_TYPE_MEID
2082     })
2083     public @interface AttestationIdType {}
2084 
2085     /**
2086      * Specifies that the device should attest its manufacturer details. For use with
2087      * {@link #generateKeyPair}.
2088      *
2089      * @see #generateKeyPair
2090      */
2091     public static final int ID_TYPE_BASE_INFO = 1;
2092 
2093     /**
2094      * Specifies that the device should attest its serial number. For use with
2095      * {@link #generateKeyPair}.
2096      *
2097      * @see #generateKeyPair
2098      */
2099     public static final int ID_TYPE_SERIAL = 2;
2100 
2101     /**
2102      * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
2103      *
2104      * @see #generateKeyPair
2105      */
2106     public static final int ID_TYPE_IMEI = 4;
2107 
2108     /**
2109      * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
2110      *
2111      * @see #generateKeyPair
2112      */
2113     public static final int ID_TYPE_MEID = 8;
2114 
2115     /**
2116      * Service-specific error code for {@link #generateKeyPair}:
2117      * Indicates the call has failed due to StrongBox unavailability.
2118      * @hide
2119      */
2120     public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1;
2121 
2122     /**
2123      * Specifies that the calling app should be granted access to the installed credentials
2124      * immediately. Otherwise, access to the credentials will be gated by user approval.
2125      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2126      *
2127      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2128      */
2129     public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
2130 
2131     /**
2132      * Specifies that a user can select the key via the Certificate Selection prompt.
2133      * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
2134      * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2135      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2136      *
2137      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2138      */
2139     public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
2140 
2141     /**
2142      * Broadcast action: sent when the profile owner is set, changed or cleared.
2143      *
2144      * This broadcast is sent only to the user managed by the new profile owner.
2145      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
2146      */
2147     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2148     public static final String ACTION_PROFILE_OWNER_CHANGED =
2149             "android.app.action.PROFILE_OWNER_CHANGED";
2150 
2151     /** @hide */
2152     @Retention(RetentionPolicy.SOURCE)
2153     @IntDef(flag = true, prefix = {"PRIVATE_DNS_MODE_"}, value = {
2154             PRIVATE_DNS_MODE_UNKNOWN,
2155             PRIVATE_DNS_MODE_OFF,
2156             PRIVATE_DNS_MODE_OPPORTUNISTIC,
2157             PRIVATE_DNS_MODE_PROVIDER_HOSTNAME
2158     })
2159     public @interface PrivateDnsMode {}
2160 
2161     /**
2162      * Specifies that the Private DNS setting is in an unknown state.
2163      */
2164     public static final int PRIVATE_DNS_MODE_UNKNOWN = 0;
2165 
2166     /**
2167      * Specifies that Private DNS was turned off completely.
2168      */
2169     public static final int PRIVATE_DNS_MODE_OFF = 1;
2170 
2171     /**
2172      * Specifies that the device owner requested opportunistic DNS over TLS
2173      */
2174     public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2;
2175 
2176     /**
2177      * Specifies that the device owner configured a specific host to use for Private DNS.
2178      */
2179     public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3;
2180 
2181     /**
2182      * Callback used in {@link #installSystemUpdate} to indicate that there was an error while
2183      * trying to install an update.
2184      */
2185     public abstract static class InstallSystemUpdateCallback {
2186         /** Represents an unknown error while trying to install an update. */
2187         public static final int UPDATE_ERROR_UNKNOWN = 1;
2188 
2189         /** Represents the update file being intended for different OS version. */
2190         public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
2191 
2192         /**
2193          * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
2194          * compression method is used.
2195          */
2196         public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
2197 
2198         /** Represents that the file could not be found. */
2199         public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4;
2200 
2201         /** Represents the battery being too low to apply an update. */
2202         public static final int UPDATE_ERROR_BATTERY_LOW = 5;
2203 
2204         /**
2205          * Method invoked when there was an error while installing an update.
2206          *
2207          * <p>The given error message is not intended to be user-facing. It is intended to be
2208          * reported back to the IT admin to be read.
2209          */
onInstallUpdateError( @nstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage)2210         public void onInstallUpdateError(
2211                 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) {
2212         }
2213     }
2214 
2215     /**
2216      * @hide
2217      */
2218     @IntDef(prefix = { "UPDATE_ERROR_" }, value = {
2219             InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
2220             InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
2221             InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
2222             InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
2223             InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
2224     })
2225     @Retention(RetentionPolicy.SOURCE)
2226     public @interface InstallUpdateCallbackErrorConstants {}
2227 
2228     /**
2229      * The selected mode has been set successfully. If the mode is
2230      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid
2231      * and reachable.
2232      */
2233     public static final int PRIVATE_DNS_SET_NO_ERROR = 0;
2234 
2235     /**
2236      * If the {@code privateDnsHost} provided was of a valid hostname but that host was found
2237      * to not support DNS-over-TLS.
2238      */
2239     public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1;
2240 
2241     /**
2242      * General failure to set the Private DNS mode, not due to one of the reasons listed above.
2243      */
2244     public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2;
2245 
2246     /**
2247      * @hide
2248      */
2249     @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = {
2250             PRIVATE_DNS_SET_NO_ERROR,
2251             PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING,
2252             PRIVATE_DNS_SET_ERROR_FAILURE_SETTING
2253     })
2254     @Retention(RetentionPolicy.SOURCE)
2255     public @interface PrivateDnsModeErrorCodes {}
2256 
2257     /**
2258      * Activity action: Starts the administrator to get the mode for the provisioning.
2259      * This intent may contain the following extras:
2260      * <ul>
2261      *     <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li>
2262      *     <li>{@link #EXTRA_PROVISIONING_IMEI}</li>
2263      *     <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li>
2264      * </ul>
2265      *
2266      * <p>The target activity should return one of the following values in
2267      * {@link #EXTRA_PROVISIONING_MODE} as result:
2268      * <ul>
2269      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
2270      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
2271      * </ul>
2272      *
2273      * <p>If performing fully-managed device provisioning and the admin app desires to show its
2274      * own education screens, the target activity can additionally return
2275      * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>.
2276      *
2277      * <p>The target activity may also return the account that needs to be migrated from primary
2278      * user to managed profile in case of a profile owner provisioning in
2279      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result.
2280      */
2281     public static final String ACTION_GET_PROVISIONING_MODE =
2282             "android.app.action.GET_PROVISIONING_MODE";
2283 
2284     /**
2285      * A string extra holding the IMEI (International Mobile Equipment Identity) of the device.
2286      */
2287     public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI";
2288 
2289     /**
2290      * A string extra holding the serial number of the device.
2291      */
2292     public static final String EXTRA_PROVISIONING_SERIAL_NUMBER =
2293             "android.app.extra.PROVISIONING_SERIAL_NUMBER";
2294 
2295     /**
2296      * An intent extra holding the provisioning mode returned by the administrator.
2297      * The value for this extra should be one of the following:
2298      * <ul>
2299      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
2300      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
2301      * </ul>
2302      */
2303     public static final String EXTRA_PROVISIONING_MODE =
2304             "android.app.extra.PROVISIONING_MODE";
2305 
2306     /**
2307      * The provisioning mode for fully managed device.
2308      */
2309     public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1;
2310 
2311     /**
2312      * The provisioning mode for managed profile.
2313      */
2314     public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2;
2315 
2316     /**
2317      * Activity action: Starts the administrator to show policy compliance for the provisioning.
2318      */
2319     public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
2320             "android.app.action.ADMIN_POLICY_COMPLIANCE";
2321 
2322     /**
2323      * Return true if the given administrator component is currently active (enabled) in the system.
2324      *
2325      * @param admin The administrator component to check for.
2326      * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
2327      *         otherwise
2328      */
isAdminActive(@onNull ComponentName admin)2329     public boolean isAdminActive(@NonNull ComponentName admin) {
2330         throwIfParentInstance("isAdminActive");
2331         return isAdminActiveAsUser(admin, myUserId());
2332     }
2333 
2334     /**
2335      * @see #isAdminActive(ComponentName)
2336      * @hide
2337      */
isAdminActiveAsUser(@onNull ComponentName admin, int userId)2338     public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
2339         if (mService != null) {
2340             try {
2341                 return mService.isAdminActive(admin, userId);
2342             } catch (RemoteException e) {
2343                 throw e.rethrowFromSystemServer();
2344             }
2345         }
2346         return false;
2347     }
2348 
2349     /**
2350      * Return true if the given administrator component is currently being removed
2351      * for the user.
2352      * @hide
2353      */
isRemovingAdmin(@onNull ComponentName admin, int userId)2354     public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
2355         if (mService != null) {
2356             try {
2357                 return mService.isRemovingAdmin(admin, userId);
2358             } catch (RemoteException e) {
2359                 throw e.rethrowFromSystemServer();
2360             }
2361         }
2362         return false;
2363     }
2364 
2365     /**
2366      * Return a list of all currently active device administrators' component
2367      * names.  If there are no administrators {@code null} may be
2368      * returned.
2369      */
getActiveAdmins()2370     public @Nullable List<ComponentName> getActiveAdmins() {
2371         throwIfParentInstance("getActiveAdmins");
2372         return getActiveAdminsAsUser(myUserId());
2373     }
2374 
2375     /**
2376      * @see #getActiveAdmins()
2377      * @hide
2378      */
2379     @UnsupportedAppUsage
getActiveAdminsAsUser(int userId)2380     public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
2381         if (mService != null) {
2382             try {
2383                 return mService.getActiveAdmins(userId);
2384             } catch (RemoteException e) {
2385                 throw e.rethrowFromSystemServer();
2386             }
2387         }
2388         return null;
2389     }
2390 
2391     /**
2392      * Used by package administration code to determine if a package can be stopped
2393      * or uninstalled.
2394      * @hide
2395      */
2396     @SystemApi
2397     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
packageHasActiveAdmins(String packageName)2398     public boolean packageHasActiveAdmins(String packageName) {
2399         return packageHasActiveAdmins(packageName, myUserId());
2400     }
2401 
2402     /**
2403      * Used by package administration code to determine if a package can be stopped
2404      * or uninstalled.
2405      * @hide
2406      */
2407     @UnsupportedAppUsage
packageHasActiveAdmins(String packageName, int userId)2408     public boolean packageHasActiveAdmins(String packageName, int userId) {
2409         if (mService != null) {
2410             try {
2411                 return mService.packageHasActiveAdmins(packageName, userId);
2412             } catch (RemoteException e) {
2413                 throw e.rethrowFromSystemServer();
2414             }
2415         }
2416         return false;
2417     }
2418 
2419     /**
2420      * Remove a current administration component.  This can only be called
2421      * by the application that owns the administration component; if you
2422      * try to remove someone else's component, a security exception will be
2423      * thrown.
2424      *
2425      * <p>Note that the operation is not synchronous and the admin might still be active (as
2426      * indicated by {@link #getActiveAdmins()}) by the time this method returns.
2427      *
2428      * @param admin The administration compononent to remove.
2429      * @throws SecurityException if the caller is not in the owner application of {@code admin}.
2430      */
removeActiveAdmin(@onNull ComponentName admin)2431     public void removeActiveAdmin(@NonNull ComponentName admin) {
2432         throwIfParentInstance("removeActiveAdmin");
2433         if (mService != null) {
2434             try {
2435                 mService.removeActiveAdmin(admin, myUserId());
2436             } catch (RemoteException e) {
2437                 throw e.rethrowFromSystemServer();
2438             }
2439         }
2440     }
2441 
2442     /**
2443      * Returns true if an administrator has been granted a particular device policy. This can be
2444      * used to check whether the administrator was activated under an earlier set of policies, but
2445      * requires additional policies after an upgrade.
2446      *
2447      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
2448      *            active administrator, or an exception will be thrown.
2449      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
2450      * @throws SecurityException if {@code admin} is not an active administrator.
2451      */
hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)2452     public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
2453         throwIfParentInstance("hasGrantedPolicy");
2454         if (mService != null) {
2455             try {
2456                 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
2457             } catch (RemoteException e) {
2458                 throw e.rethrowFromSystemServer();
2459             }
2460         }
2461         return false;
2462     }
2463 
2464     /**
2465      * Returns true if the Profile Challenge is available to use for the given profile user.
2466      *
2467      * @hide
2468      */
isSeparateProfileChallengeAllowed(int userHandle)2469     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
2470         if (mService != null) {
2471             try {
2472                 return mService.isSeparateProfileChallengeAllowed(userHandle);
2473             } catch (RemoteException e) {
2474                 throw e.rethrowFromSystemServer();
2475             }
2476         }
2477         return false;
2478     }
2479 
2480     /**
2481      * Constant for {@link #setPasswordQuality}: the policy has no requirements
2482      * for the password.  Note that quality constants are ordered so that higher
2483      * values are more restrictive.
2484      */
2485     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
2486 
2487     /**
2488      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
2489      * recognition technology.  This implies technologies that can recognize the identity of
2490      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
2491      * Note that quality constants are ordered so that higher values are more restrictive.
2492      */
2493     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
2494 
2495     /**
2496      * Constant for {@link #setPasswordQuality}: the policy requires some kind
2497      * of password or pattern, but doesn't care what it is. Note that quality constants
2498      * are ordered so that higher values are more restrictive.
2499      */
2500     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
2501 
2502     /**
2503      * Constant for {@link #setPasswordQuality}: the user must have entered a
2504      * password containing at least numeric characters.  Note that quality
2505      * constants are ordered so that higher values are more restrictive.
2506      */
2507     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
2508 
2509     /**
2510      * Constant for {@link #setPasswordQuality}: the user must have entered a
2511      * password containing at least numeric characters with no repeating (4444)
2512      * or ordered (1234, 4321, 2468) sequences.  Note that quality
2513      * constants are ordered so that higher values are more restrictive.
2514      */
2515     public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
2516 
2517     /**
2518      * Constant for {@link #setPasswordQuality}: the user must have entered a
2519      * password containing at least alphabetic (or other symbol) characters.
2520      * Note that quality constants are ordered so that higher values are more
2521      * restrictive.
2522      */
2523     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
2524 
2525     /**
2526      * Constant for {@link #setPasswordQuality}: the user must have entered a
2527      * password containing at least <em>both></em> numeric <em>and</em>
2528      * alphabetic (or other symbol) characters.  Note that quality constants are
2529      * ordered so that higher values are more restrictive.
2530      */
2531     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
2532 
2533     /**
2534      * Constant for {@link #setPasswordQuality}: the user must have entered a
2535      * password containing at least a letter, a numerical digit and a special
2536      * symbol, by default. With this password quality, passwords can be
2537      * restricted to contain various sets of characters, like at least an
2538      * uppercase letter, etc. These are specified using various methods,
2539      * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
2540      * that quality constants are ordered so that higher values are more
2541      * restrictive.
2542      */
2543     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
2544 
2545     /**
2546      * Constant for {@link #setPasswordQuality}: the user is not allowed to
2547      * modify password. In case this password quality is set, the password is
2548      * managed by a profile owner. The profile owner can set any password,
2549      * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
2550      * that quality constants are ordered so that higher values are more
2551      * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
2552      * the highest.
2553      * @hide
2554      */
2555     public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
2556 
2557     /**
2558      * @hide
2559      *
2560      * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
2561      * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
2562      * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
2563      * used by authenticator to exempt their accounts from this:
2564      *
2565      * <ul>
2566      *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
2567      *     <p>In order to make an apk test-only, add android:testOnly="true" to the
2568      *     &lt;application&gt; tag in the manifest.
2569      *
2570      *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
2571      *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
2572      *     Some authenticators claim to have any features, so to detect it, we also check
2573      *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
2574      *     if any of the accounts have it.
2575      * </ul>
2576      */
2577     @SystemApi
2578     @TestApi
2579     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
2580             "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
2581 
2582     /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
2583     @SystemApi
2584     @TestApi
2585     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
2586             "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
2587 
2588     /**
2589      * Called by an application that is administering the device to set the password restrictions it
2590      * is imposing. After setting this, the user will not be able to enter a new password that is
2591      * not at least as restrictive as what has been set. Note that the current password will remain
2592      * until the user has set a new one, so the change does not take place immediately. To prompt
2593      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2594      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
2595      * <p>
2596      * Quality constants are ordered so that higher values are more restrictive; thus the highest
2597      * requested quality constant (between the policy set here, the user's preference, and any other
2598      * considerations) is the one that is in effect.
2599      * <p>
2600      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2601      * password is always treated as empty.
2602      * <p>
2603      * The calling device admin must have requested
2604      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2605      * not, a security exception will be thrown.
2606      * <p>
2607      * This method can be called on the {@link DevicePolicyManager} instance returned by
2608      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2609      * profile.
2610      *
2611      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2612      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
2613      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
2614      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2615      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
2616      * @throws SecurityException if {@code admin} is not an active administrator or if {@code admin}
2617      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2618      */
setPasswordQuality(@onNull ComponentName admin, int quality)2619     public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
2620         if (mService != null) {
2621             try {
2622                 mService.setPasswordQuality(admin, quality, mParentInstance);
2623             } catch (RemoteException e) {
2624                 throw e.rethrowFromSystemServer();
2625             }
2626         }
2627     }
2628 
2629     /**
2630      * Retrieve the current minimum password quality for a particular admin or all admins that set
2631      * restrictions on this user and its participating profiles. Restrictions on profiles that have
2632      * a separate challenge are not taken into account.
2633      *
2634      * <p>This method can be called on the {@link DevicePolicyManager} instance
2635      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2636      * restrictions on the parent profile.
2637      *
2638      * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
2639      * the password is always treated as empty.
2640      *
2641      * @param admin The name of the admin component to check, or {@code null} to aggregate
2642      * all admins.
2643      */
getPasswordQuality(@ullable ComponentName admin)2644     public int getPasswordQuality(@Nullable ComponentName admin) {
2645         return getPasswordQuality(admin, myUserId());
2646     }
2647 
2648     /** @hide per-user version */
2649     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordQuality(@ullable ComponentName admin, int userHandle)2650     public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
2651         if (mService != null) {
2652             try {
2653                 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
2654             } catch (RemoteException e) {
2655                 throw e.rethrowFromSystemServer();
2656             }
2657         }
2658         return PASSWORD_QUALITY_UNSPECIFIED;
2659     }
2660 
2661     /**
2662      * Called by an application that is administering the device to set the minimum allowed password
2663      * length. After setting this, the user will not be able to enter a new password that is not at
2664      * least as restrictive as what has been set. Note that the current password will remain until
2665      * the user has set a new one, so the change does not take place immediately. To prompt the user
2666      * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2667      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2668      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2669      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2670      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
2671      * {@link #setPasswordQuality}.
2672      * <p>
2673      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2674      * password is always treated as empty.
2675      * <p>
2676      * The calling device admin must have requested
2677      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2678      * not, a security exception will be thrown.
2679      * <p>
2680      * This method can be called on the {@link DevicePolicyManager} instance returned by
2681      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2682      * profile.
2683      *
2684      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2685      * @param length The new desired minimum password length. A value of 0 means there is no
2686      *            restriction.
2687      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2688      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2689      */
setPasswordMinimumLength(@onNull ComponentName admin, int length)2690     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
2691         if (mService != null) {
2692             try {
2693                 mService.setPasswordMinimumLength(admin, length, mParentInstance);
2694             } catch (RemoteException e) {
2695                 throw e.rethrowFromSystemServer();
2696             }
2697         }
2698     }
2699 
2700     /**
2701      * Retrieve the current minimum password length for a particular admin or all admins that set
2702      * restrictions on this user and its participating profiles. Restrictions on profiles that have
2703      * a separate challenge are not taken into account.
2704      *
2705      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2706      * password is always treated as empty.
2707      *
2708      * <p>This method can be called on the {@link DevicePolicyManager} instance
2709      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2710      * restrictions on the parent profile.
2711      *
2712      * @param admin The name of the admin component to check, or {@code null} to aggregate
2713      * all admins.
2714      */
getPasswordMinimumLength(@ullable ComponentName admin)2715     public int getPasswordMinimumLength(@Nullable ComponentName admin) {
2716         return getPasswordMinimumLength(admin, myUserId());
2717     }
2718 
2719     /** @hide per-user version */
2720     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)2721     public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
2722         if (mService != null) {
2723             try {
2724                 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
2725             } catch (RemoteException e) {
2726                 throw e.rethrowFromSystemServer();
2727             }
2728         }
2729         return 0;
2730     }
2731 
2732     /**
2733      * Called by an application that is administering the device to set the minimum number of upper
2734      * case letters required in the password. After setting this, the user will not be able to enter
2735      * a new password that is not at least as restrictive as what has been set. Note that the
2736      * current password will remain until the user has set a new one, so the change does not take
2737      * place immediately. To prompt the user for a new password, use
2738      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2739      * setting this value. This constraint is only imposed if the administrator has also requested
2740      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2741      * <p>
2742      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2743      * password is always treated as empty.
2744      * <p>
2745      * The calling device admin must have requested
2746      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2747      * not, a security exception will be thrown.
2748      * <p>
2749      * This method can be called on the {@link DevicePolicyManager} instance returned by
2750      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2751      * profile.
2752      *
2753      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2754      * @param length The new desired minimum number of upper case letters required in the password.
2755      *            A value of 0 means there is no restriction.
2756      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2757      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2758      */
setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)2759     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
2760         if (mService != null) {
2761             try {
2762                 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
2763             } catch (RemoteException e) {
2764                 throw e.rethrowFromSystemServer();
2765             }
2766         }
2767     }
2768 
2769     /**
2770      * Retrieve the current number of upper case letters required in the password
2771      * for a particular admin or all admins that set restrictions on this user and
2772      * its participating profiles. Restrictions on profiles that have a separate challenge
2773      * are not taken into account.
2774      * This is the same value as set by
2775      * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
2776      * and only applies when the password quality is
2777      * {@link #PASSWORD_QUALITY_COMPLEX}.
2778      *
2779      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2780      * password is always treated as empty.
2781      *
2782      * <p>This method can be called on the {@link DevicePolicyManager} instance
2783      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2784      * restrictions on the parent profile.
2785      *
2786      * @param admin The name of the admin component to check, or {@code null} to
2787      *            aggregate all admins.
2788      * @return The minimum number of upper case letters required in the
2789      *         password.
2790      */
getPasswordMinimumUpperCase(@ullable ComponentName admin)2791     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
2792         return getPasswordMinimumUpperCase(admin, myUserId());
2793     }
2794 
2795     /** @hide per-user version */
2796     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)2797     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
2798         if (mService != null) {
2799             try {
2800                 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
2801             } catch (RemoteException e) {
2802                 throw e.rethrowFromSystemServer();
2803             }
2804         }
2805         return 0;
2806     }
2807 
2808     /**
2809      * Called by an application that is administering the device to set the minimum number of lower
2810      * case letters required in the password. After setting this, the user will not be able to enter
2811      * a new password that is not at least as restrictive as what has been set. Note that the
2812      * current password will remain until the user has set a new one, so the change does not take
2813      * place immediately. To prompt the user for a new password, use
2814      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2815      * setting this value. This constraint is only imposed if the administrator has also requested
2816      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2817      * <p>
2818      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2819      * password is always treated as empty.
2820      * <p>
2821      * The calling device admin must have requested
2822      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2823      * not, a security exception will be thrown.
2824      * <p>
2825      * This method can be called on the {@link DevicePolicyManager} instance returned by
2826      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2827      * profile.
2828      *
2829      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2830      * @param length The new desired minimum number of lower case letters required in the password.
2831      *            A value of 0 means there is no restriction.
2832      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2833      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2834      */
setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)2835     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
2836         if (mService != null) {
2837             try {
2838                 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
2839             } catch (RemoteException e) {
2840                 throw e.rethrowFromSystemServer();
2841             }
2842         }
2843     }
2844 
2845     /**
2846      * Retrieve the current number of lower case letters required in the password
2847      * for a particular admin or all admins that set restrictions on this user
2848      * and its participating profiles. Restrictions on profiles that have
2849      * a separate challenge are not taken into account.
2850      * This is the same value as set by
2851      * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
2852      * and only applies when the password quality is
2853      * {@link #PASSWORD_QUALITY_COMPLEX}.
2854      *
2855      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2856      * password is always treated as empty.
2857      *
2858      * <p>This method can be called on the {@link DevicePolicyManager} instance
2859      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2860      * restrictions on the parent profile.
2861      *
2862      * @param admin The name of the admin component to check, or {@code null} to
2863      *            aggregate all admins.
2864      * @return The minimum number of lower case letters required in the
2865      *         password.
2866      */
getPasswordMinimumLowerCase(@ullable ComponentName admin)2867     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
2868         return getPasswordMinimumLowerCase(admin, myUserId());
2869     }
2870 
2871     /** @hide per-user version */
2872     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)2873     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
2874         if (mService != null) {
2875             try {
2876                 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
2877             } catch (RemoteException e) {
2878                 throw e.rethrowFromSystemServer();
2879             }
2880         }
2881         return 0;
2882     }
2883 
2884     /**
2885      * Called by an application that is administering the device to set the minimum number of
2886      * letters required in the password. After setting this, the user will not be able to enter a
2887      * new password that is not at least as restrictive as what has been set. Note that the current
2888      * password will remain until the user has set a new one, so the change does not take place
2889      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2890      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2891      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2892      * {@link #setPasswordQuality}. The default value is 1.
2893      * <p>
2894      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2895      * password is always treated as empty.
2896      * <p>
2897      * The calling device admin must have requested
2898      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2899      * not, a security exception will be thrown.
2900      * <p>
2901      * This method can be called on the {@link DevicePolicyManager} instance returned by
2902      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2903      * profile.
2904      *
2905      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2906      * @param length The new desired minimum number of letters required in the password. A value of
2907      *            0 means there is no restriction.
2908      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2909      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2910      */
setPasswordMinimumLetters(@onNull ComponentName admin, int length)2911     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
2912         if (mService != null) {
2913             try {
2914                 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
2915             } catch (RemoteException e) {
2916                 throw e.rethrowFromSystemServer();
2917             }
2918         }
2919     }
2920 
2921     /**
2922      * Retrieve the current number of letters required in the password
2923      * for a particular admin or all admins that set restrictions on this user
2924      * and its participating profiles. Restrictions on profiles that have
2925      * a separate challenge are not taken into account.
2926      * This is the same value as set by
2927      * {@link #setPasswordMinimumLetters(ComponentName, int)}
2928      * and only applies when the password quality is
2929      * {@link #PASSWORD_QUALITY_COMPLEX}.
2930      *
2931      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2932      * password is always treated as empty.
2933      *
2934      * <p>This method can be called on the {@link DevicePolicyManager} instance
2935      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2936      * restrictions on the parent profile.
2937      *
2938      * @param admin The name of the admin component to check, or {@code null} to
2939      *            aggregate all admins.
2940      * @return The minimum number of letters required in the password.
2941      */
getPasswordMinimumLetters(@ullable ComponentName admin)2942     public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
2943         return getPasswordMinimumLetters(admin, myUserId());
2944     }
2945 
2946     /** @hide per-user version */
2947     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)2948     public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
2949         if (mService != null) {
2950             try {
2951                 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
2952             } catch (RemoteException e) {
2953                 throw e.rethrowFromSystemServer();
2954             }
2955         }
2956         return 0;
2957     }
2958 
2959     /**
2960      * Called by an application that is administering the device to set the minimum number of
2961      * numerical digits required in the password. After setting this, the user will not be able to
2962      * enter a new password that is not at least as restrictive as what has been set. Note that the
2963      * current password will remain until the user has set a new one, so the change does not take
2964      * place immediately. To prompt the user for a new password, use
2965      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2966      * setting this value. This constraint is only imposed if the administrator has also requested
2967      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 1.
2968      * <p>
2969      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2970      * password is always treated as empty.
2971      * <p>
2972      * The calling device admin must have requested
2973      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2974      * not, a security exception will be thrown.
2975      * <p>
2976      * This method can be called on the {@link DevicePolicyManager} instance returned by
2977      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2978      * profile.
2979      *
2980      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2981      * @param length The new desired minimum number of numerical digits required in the password. A
2982      *            value of 0 means there is no restriction.
2983      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2984      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2985      */
setPasswordMinimumNumeric(@onNull ComponentName admin, int length)2986     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
2987         if (mService != null) {
2988             try {
2989                 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
2990             } catch (RemoteException e) {
2991                 throw e.rethrowFromSystemServer();
2992             }
2993         }
2994     }
2995 
2996     /**
2997      * Retrieve the current number of numerical digits required in the password
2998      * for a particular admin or all admins that set restrictions on this user
2999      * and its participating profiles. Restrictions on profiles that have
3000      * a separate challenge are not taken into account.
3001      * This is the same value as set by
3002      * {@link #setPasswordMinimumNumeric(ComponentName, int)}
3003      * and only applies when the password quality is
3004      * {@link #PASSWORD_QUALITY_COMPLEX}.
3005      *
3006      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3007      * password is always treated as empty.
3008      *
3009      * <p>This method can be called on the {@link DevicePolicyManager} instance
3010      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3011      * restrictions on the parent profile.
3012      *
3013      * @param admin The name of the admin component to check, or {@code null} to
3014      *            aggregate all admins.
3015      * @return The minimum number of numerical digits required in the password.
3016      */
getPasswordMinimumNumeric(@ullable ComponentName admin)3017     public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
3018         return getPasswordMinimumNumeric(admin, myUserId());
3019     }
3020 
3021     /** @hide per-user version */
3022     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)3023     public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
3024         if (mService != null) {
3025             try {
3026                 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
3027             } catch (RemoteException e) {
3028                 throw e.rethrowFromSystemServer();
3029             }
3030         }
3031         return 0;
3032     }
3033 
3034     /**
3035      * Called by an application that is administering the device to set the minimum number of
3036      * symbols required in the password. After setting this, the user will not be able to enter a
3037      * new password that is not at least as restrictive as what has been set. Note that the current
3038      * password will remain until the user has set a new one, so the change does not take place
3039      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3040      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3041      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
3042      * {@link #setPasswordQuality}. The default value is 1.
3043      * <p>
3044      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3045      * password is always treated as empty.
3046      * <p>
3047      * The calling device admin must have requested
3048      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3049      * not, a security exception will be thrown.
3050      * <p>
3051      * This method can be called on the {@link DevicePolicyManager} instance returned by
3052      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3053      * profile.
3054      *
3055      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3056      * @param length The new desired minimum number of symbols required in the password. A value of
3057      *            0 means there is no restriction.
3058      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3059      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3060      */
setPasswordMinimumSymbols(@onNull ComponentName admin, int length)3061     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
3062         if (mService != null) {
3063             try {
3064                 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
3065             } catch (RemoteException e) {
3066                 throw e.rethrowFromSystemServer();
3067             }
3068         }
3069     }
3070 
3071     /**
3072      * Retrieve the current number of symbols required in the password
3073      * for a particular admin or all admins that set restrictions on this user
3074      * and its participating profiles. Restrictions on profiles that have
3075      * a separate challenge are not taken into account. This is the same value as
3076      * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
3077      * and only applies when the password quality is
3078      * {@link #PASSWORD_QUALITY_COMPLEX}.
3079      *
3080      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3081      * password is always treated as empty.
3082      *
3083      * <p>This method can be called on the {@link DevicePolicyManager} instance
3084      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3085      * restrictions on the parent profile.
3086      *
3087      * @param admin The name of the admin component to check, or {@code null} to
3088      *            aggregate all admins.
3089      * @return The minimum number of symbols required in the password.
3090      */
getPasswordMinimumSymbols(@ullable ComponentName admin)3091     public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
3092         return getPasswordMinimumSymbols(admin, myUserId());
3093     }
3094 
3095     /** @hide per-user version */
3096     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)3097     public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
3098         if (mService != null) {
3099             try {
3100                 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
3101             } catch (RemoteException e) {
3102                 throw e.rethrowFromSystemServer();
3103             }
3104         }
3105         return 0;
3106     }
3107 
3108     /**
3109      * Called by an application that is administering the device to set the minimum number of
3110      * non-letter characters (numerical digits or symbols) required in the password. After setting
3111      * this, the user will not be able to enter a new password that is not at least as restrictive
3112      * as what has been set. Note that the current password will remain until the user has set a new
3113      * one, so the change does not take place immediately. To prompt the user for a new password,
3114      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3115      * setting this value. This constraint is only imposed if the administrator has also requested
3116      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
3117      * <p>
3118      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3119      * password is always treated as empty.
3120      * <p>
3121      * The calling device admin must have requested
3122      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3123      * not, a security exception will be thrown.
3124      * <p>
3125      * This method can be called on the {@link DevicePolicyManager} instance returned by
3126      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3127      * profile.
3128      *
3129      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3130      * @param length The new desired minimum number of letters required in the password. A value of
3131      *            0 means there is no restriction.
3132      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3133      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3134      */
setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)3135     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
3136         if (mService != null) {
3137             try {
3138                 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
3139             } catch (RemoteException e) {
3140                 throw e.rethrowFromSystemServer();
3141             }
3142         }
3143     }
3144 
3145     /**
3146      * Retrieve the current number of non-letter characters required in the password
3147      * for a particular admin or all admins that set restrictions on this user
3148      * and its participating profiles. Restrictions on profiles that have
3149      * a separate challenge are not taken into account.
3150      * This is the same value as set by
3151      * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
3152      * and only applies when the password quality is
3153      * {@link #PASSWORD_QUALITY_COMPLEX}.
3154      *
3155      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3156      * password is always treated as empty.
3157      *
3158      * <p>This method can be called on the {@link DevicePolicyManager} instance
3159      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3160      * restrictions on the parent profile.
3161      *
3162      * @param admin The name of the admin component to check, or {@code null} to
3163      *            aggregate all admins.
3164      * @return The minimum number of letters required in the password.
3165      */
getPasswordMinimumNonLetter(@ullable ComponentName admin)3166     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
3167         return getPasswordMinimumNonLetter(admin, myUserId());
3168     }
3169 
3170     /** @hide per-user version */
3171     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)3172     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
3173         if (mService != null) {
3174             try {
3175                 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
3176             } catch (RemoteException e) {
3177                 throw e.rethrowFromSystemServer();
3178             }
3179         }
3180         return 0;
3181     }
3182 
3183     /**
3184      * Called by an application that is administering the device to set the length of the password
3185      * history. After setting this, the user will not be able to enter a new password that is the
3186      * same as any password in the history. Note that the current password will remain until the
3187      * user has set a new one, so the change does not take place immediately. To prompt the user for
3188      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3189      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3190      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
3191      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX} {@link #PASSWORD_QUALITY_ALPHABETIC}, or
3192      * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
3193      * <p>
3194      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3195      * password history length is always 0.
3196      * <p>
3197      * The calling device admin must have requested
3198      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3199      * not, a security exception will be thrown.
3200      * <p>
3201      * This method can be called on the {@link DevicePolicyManager} instance returned by
3202      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3203      * profile.
3204      *
3205      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3206      * @param length The new desired length of password history. A value of 0 means there is no
3207      *            restriction.
3208      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3209      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3210      */
3211     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordHistoryLength(@onNull ComponentName admin, int length)3212     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
3213         if (mService != null) {
3214             try {
3215                 mService.setPasswordHistoryLength(admin, length, mParentInstance);
3216             } catch (RemoteException e) {
3217                 throw e.rethrowFromSystemServer();
3218             }
3219         }
3220     }
3221 
3222     /**
3223      * Called by a device admin to set the password expiration timeout. Calling this method will
3224      * restart the countdown for password expiration for the given admin, as will changing the
3225      * device password (for all admins).
3226      * <p>
3227      * The provided timeout is the time delta in ms and will be added to the current time. For
3228      * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
3229      * 432000000 ms for timeout.
3230      * <p>
3231      * To disable password expiration, a value of 0 may be used for timeout.
3232      * <p>
3233      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3234      * password expiration is always disabled.
3235      * <p>
3236      * The calling device admin must have requested
3237      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
3238      * not, a security exception will be thrown.
3239      * <p>
3240      * Note that setting the password will automatically reset the expiration time for all active
3241      * admins. Active admins do not need to explicitly call this method in that case.
3242      * <p>
3243      * This method can be called on the {@link DevicePolicyManager} instance returned by
3244      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3245      * profile.
3246      *
3247      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3248      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
3249      *            there is no restriction (unlimited).
3250      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3251      *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
3252      */
3253     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordExpirationTimeout(@onNull ComponentName admin, long timeout)3254     public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
3255         if (mService != null) {
3256             try {
3257                 mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
3258             } catch (RemoteException e) {
3259                 throw e.rethrowFromSystemServer();
3260             }
3261         }
3262     }
3263 
3264     /**
3265      * Get the password expiration timeout for the given admin. The expiration timeout is the
3266      * recurring expiration timeout provided in the call to
3267      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
3268      * aggregate of all participating policy administrators if {@code admin} is null. Admins that
3269      * have set restrictions on profiles that have a separate challenge are not taken into account.
3270      *
3271      * <p>This method can be called on the {@link DevicePolicyManager} instance
3272      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3273      * restrictions on the parent profile.
3274      *
3275      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3276      * password expiration is always disabled and this method always returns 0.
3277      *
3278      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
3279      * @return The timeout for the given admin or the minimum of all timeouts
3280      */
3281     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpirationTimeout(@ullable ComponentName admin)3282     public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
3283         if (mService != null) {
3284             try {
3285                 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
3286             } catch (RemoteException e) {
3287                 throw e.rethrowFromSystemServer();
3288             }
3289         }
3290         return 0;
3291     }
3292 
3293     /**
3294      * Get the current password expiration time for a particular admin or all admins that set
3295      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3296      * a separate challenge are not taken into account. If admin is {@code null}, then a composite
3297      * of all expiration times is returned - which will be the minimum of all of them.
3298      *
3299      * <p>This method can be called on the {@link DevicePolicyManager} instance
3300      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3301      * the password expiration for the parent profile.
3302      *
3303      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3304      * password expiration is always disabled and this method always returns 0.
3305      *
3306      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
3307      * @return The password expiration time, in milliseconds since epoch.
3308      */
3309     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpiration(@ullable ComponentName admin)3310     public long getPasswordExpiration(@Nullable ComponentName admin) {
3311         if (mService != null) {
3312             try {
3313                 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
3314             } catch (RemoteException e) {
3315                 throw e.rethrowFromSystemServer();
3316             }
3317         }
3318         return 0;
3319     }
3320 
3321     /**
3322      * Retrieve the current password history length for a particular admin or all admins that
3323      * set restrictions on this user and its participating profiles. Restrictions on profiles that
3324      * have a separate challenge are not taken into account.
3325      *
3326      * <p>This method can be called on the {@link DevicePolicyManager} instance
3327      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3328      * restrictions on the parent profile.
3329      *
3330      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3331      * password history length is always 0.
3332      *
3333      * @param admin The name of the admin component to check, or {@code null} to aggregate
3334      * all admins.
3335      * @return The length of the password history
3336      */
3337     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin)3338     public int getPasswordHistoryLength(@Nullable ComponentName admin) {
3339         return getPasswordHistoryLength(admin, myUserId());
3340     }
3341 
3342     /** @hide per-user version */
3343     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
3344     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)3345     public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
3346         if (mService != null) {
3347             try {
3348                 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
3349             } catch (RemoteException e) {
3350                 throw e.rethrowFromSystemServer();
3351             }
3352         }
3353         return 0;
3354     }
3355 
3356     /**
3357      * Return the maximum password length that the device supports for a
3358      * particular password quality.
3359      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3360      * password is always empty and this method always returns 0.
3361      * @param quality The quality being interrogated.
3362      * @return Returns the maximum length that the user can enter.
3363      */
getPasswordMaximumLength(int quality)3364     public int getPasswordMaximumLength(int quality) {
3365         PackageManager pm = mContext.getPackageManager();
3366         if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) {
3367             return 0;
3368         }
3369         // Kind-of arbitrary.
3370         return 16;
3371     }
3372 
3373     /**
3374      * Determines whether the calling user's current password meets policy requirements
3375      * (e.g. quality, minimum length). The user must be unlocked to perform this check.
3376      *
3377      * <p>Policy requirements which affect this check can be set by admins of the user, but also
3378      * by the admin of a managed profile associated with the calling user (when the managed profile
3379      * doesn't have a separate work challenge). When a managed profile has a separate work
3380      * challenge, its policy requirements only affect the managed profile.
3381      *
3382      * <p>Depending on the user, this method checks the policy requirement against one of the
3383      * following passwords:
3384      * <ul>
3385      * <li>For the primary user or secondary users: the personal keyguard password.
3386      * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal
3387      *     keyguard password.
3388      * <ul/>
3389      * In other words, it's always checking the requirement against the password that is protecting
3390      * the calling user.
3391      *
3392      * <p>Note that this method considers all policy requirements targeting the password in
3393      * question. For example a profile owner might set a requirement on the parent profile i.e.
3394      * personal keyguard but not on the profile itself. When the device has a weak personal keyguard
3395      * password and no separate work challenge, calling this method will return {@code false}
3396      * despite the profile owner not setting a policy on the profile itself. This is because the
3397      * profile's current password is the personal keyguard password, and it does not meet all policy
3398      * requirements.
3399      *
3400      * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before
3401      * calling this method. Note, this policy type is deprecated for device admins in Android 9.0
3402      * (API level 28) or higher.
3403      *
3404      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
3405      * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
3406      * the parent profile is sufficient.
3407      *
3408      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3409      * password is always treated as empty - i.e. this method will always return false on such
3410      * devices, provided any password requirements were set.
3411      *
3412      * @return {@code true} if the password meets the policy requirements, {@code false} otherwise
3413      * @throws SecurityException if the calling application isn't an active admin that uses
3414      *     {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3415      * @throws IllegalStateException if the user isn't unlocked
3416      */
isActivePasswordSufficient()3417     public boolean isActivePasswordSufficient() {
3418         if (mService != null) {
3419             try {
3420                 return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
3421             } catch (RemoteException e) {
3422                 throw e.rethrowFromSystemServer();
3423             }
3424         }
3425         return false;
3426     }
3427 
3428     /**
3429      * Returns how complex the current user's screen lock is.
3430      *
3431      * <p>Note that when called from a profile which uses an unified challenge with its parent, the
3432      * screen lock complexity of the parent will be returned. However, this API does not support
3433      * explicitly querying the parent profile screen lock complexity via {@link
3434      * #getParentProfileInstance}.
3435      *
3436      * @throws IllegalStateException if the user is not unlocked.
3437      * @throws SecurityException if the calling application does not have the permission
3438      *                           {@link permission#REQUEST_PASSWORD_COMPLEXITY}
3439      */
3440     @PasswordComplexity
3441     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
getPasswordComplexity()3442     public int getPasswordComplexity() {
3443         throwIfParentInstance("getPasswordComplexity");
3444         if (mService == null) {
3445             return PASSWORD_COMPLEXITY_NONE;
3446         }
3447 
3448         try {
3449             return mService.getPasswordComplexity();
3450         } catch (RemoteException e) {
3451             throw e.rethrowFromSystemServer();
3452         }
3453     }
3454 
3455     /**
3456      * When called by a profile owner of a managed profile returns true if the profile uses unified
3457      * challenge with its parent user.
3458      *
3459      * <strong>Note</strong>: This method is not concerned with password quality and will return
3460      * false if the profile has empty password as a separate challenge.
3461      *
3462      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3463      * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
3464      * @see UserManager#DISALLOW_UNIFIED_PASSWORD
3465      */
isUsingUnifiedPassword(@onNull ComponentName admin)3466     public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
3467         throwIfParentInstance("isUsingUnifiedPassword");
3468         if (mService != null) {
3469             try {
3470                 return mService.isUsingUnifiedPassword(admin);
3471             } catch (RemoteException e) {
3472                 throw e.rethrowFromSystemServer();
3473             }
3474         }
3475         return true;
3476     }
3477 
3478     /**
3479      * Determine whether the current profile password the user has set is sufficient
3480      * to meet the policy requirements (e.g. quality, minimum length) that have been
3481      * requested by the admins of the parent user and its profiles.
3482      *
3483      * @param userHandle the userId of the profile to check the password for.
3484      * @return Returns true if the password would meet the current requirements, else false.
3485      * @throws SecurityException if {@code userHandle} is not a managed profile.
3486      * @hide
3487      */
isProfileActivePasswordSufficientForParent(int userHandle)3488     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3489         if (mService != null) {
3490             try {
3491                 return mService.isProfileActivePasswordSufficientForParent(userHandle);
3492             } catch (RemoteException e) {
3493                 throw e.rethrowFromSystemServer();
3494             }
3495         }
3496         return false;
3497     }
3498 
3499     /**
3500      * Retrieve the number of times the user has failed at entering a password since that last
3501      * successful password entry.
3502      * <p>
3503      * This method can be called on the {@link DevicePolicyManager} instance returned by
3504      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
3505      * password attemts for the parent user.
3506      * <p>
3507      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
3508      * to be able to call this method; if it has not, a security exception will be thrown.
3509      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3510      * password is always empty and this method always returns 0.
3511      *
3512      * @return The number of times user has entered an incorrect password since the last correct
3513      *         password entry.
3514      * @throws SecurityException if the calling application does not own an active administrator
3515      *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
3516      */
3517     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getCurrentFailedPasswordAttempts()3518     public int getCurrentFailedPasswordAttempts() {
3519         return getCurrentFailedPasswordAttempts(myUserId());
3520     }
3521 
3522     /**
3523      * Retrieve the number of times the given user has failed at entering a
3524      * password since that last successful password entry.
3525      *
3526      * <p>The calling device admin must have requested
3527      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
3528      * not and it is not the system uid, a security exception will be thrown.
3529      *
3530      * @hide
3531      */
3532     @UnsupportedAppUsage
getCurrentFailedPasswordAttempts(int userHandle)3533     public int getCurrentFailedPasswordAttempts(int userHandle) {
3534         if (mService != null) {
3535             try {
3536                 return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
3537             } catch (RemoteException e) {
3538                 throw e.rethrowFromSystemServer();
3539             }
3540         }
3541         return -1;
3542     }
3543 
3544     /**
3545      * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
3546      *
3547      * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
3548      * @hide
3549      */
getDoNotAskCredentialsOnBoot()3550     public boolean getDoNotAskCredentialsOnBoot() {
3551         if (mService != null) {
3552             try {
3553                 return mService.getDoNotAskCredentialsOnBoot();
3554             } catch (RemoteException e) {
3555                 throw e.rethrowFromSystemServer();
3556             }
3557         }
3558         return false;
3559     }
3560 
3561     /**
3562      * Setting this to a value greater than zero enables a built-in policy that will perform a
3563      * device or profile wipe after too many incorrect device-unlock passwords have been entered.
3564      * This built-in policy combines watching for failed passwords and wiping the device, and
3565      * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
3566      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
3567      * <p>
3568      * To implement any other policy (e.g. wiping data for a particular application only, erasing or
3569      * revoking credentials, or reporting the failure to a server), you should implement
3570      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
3571      * use this API, because if the maximum count is reached, the device or profile will be wiped
3572      * immediately, and your callback will not be invoked.
3573      * <p>
3574      * This method can be called on the {@link DevicePolicyManager} instance returned by
3575      * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
3576      * profile.
3577      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3578      * password is always empty and this method has no effect - i.e. the policy is not set.
3579      *
3580      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3581      * @param num The number of failed password attempts at which point the device or profile will
3582      *            be wiped.
3583      * @throws SecurityException if {@code admin} is not an active administrator or does not use
3584      *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
3585      *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
3586      */
3587     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setMaximumFailedPasswordsForWipe(@onNull ComponentName admin, int num)3588     public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
3589         if (mService != null) {
3590             try {
3591                 mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
3592             } catch (RemoteException e) {
3593                 throw e.rethrowFromSystemServer();
3594             }
3595         }
3596     }
3597 
3598     /**
3599      * Retrieve the current maximum number of login attempts that are allowed before the device
3600      * or profile is wiped, for a particular admin or all admins that set restrictions on this user
3601      * and its participating profiles. Restrictions on profiles that have a separate challenge are
3602      * not taken into account.
3603      *
3604      * <p>This method can be called on the {@link DevicePolicyManager} instance
3605      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3606      * the value for the parent profile.
3607      *
3608      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3609      * password is always empty and this method returns a default value (0) indicating that the
3610      * policy is not set.
3611      *
3612      * @param admin The name of the admin component to check, or {@code null} to aggregate
3613      * all admins.
3614      */
3615     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)3616     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
3617         return getMaximumFailedPasswordsForWipe(admin, myUserId());
3618     }
3619 
3620     /** @hide per-user version */
3621     @UnsupportedAppUsage
3622     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)3623     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
3624         if (mService != null) {
3625             try {
3626                 return mService.getMaximumFailedPasswordsForWipe(
3627                         admin, userHandle, mParentInstance);
3628             } catch (RemoteException e) {
3629                 throw e.rethrowFromSystemServer();
3630             }
3631         }
3632         return 0;
3633     }
3634 
3635     /**
3636      * Returns the profile with the smallest maximum failed passwords for wipe,
3637      * for the given user. So for primary user, it might return the primary or
3638      * a managed profile. For a secondary user, it would be the same as the
3639      * user passed in.
3640      * @hide Used only by Keyguard
3641      */
3642     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getProfileWithMinimumFailedPasswordsForWipe(int userHandle)3643     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
3644         if (mService != null) {
3645             try {
3646                 return mService.getProfileWithMinimumFailedPasswordsForWipe(
3647                         userHandle, mParentInstance);
3648             } catch (RemoteException e) {
3649                 throw e.rethrowFromSystemServer();
3650             }
3651         }
3652         return UserHandle.USER_NULL;
3653     }
3654 
3655     /**
3656      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
3657      * to change the password again until the user has entered it.
3658      */
3659     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
3660 
3661     /**
3662      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
3663      * credentials on device boot.
3664      * If the flag is set, the device can be booted without asking for user password.
3665      * The absence of this flag does not change the current boot requirements. This flag
3666      * can be set by the device owner only. If the app is not the device owner, the flag
3667      * is ignored. Once the flag is set, it cannot be reverted back without resetting the
3668      * device to factory defaults.
3669      */
3670     public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
3671 
3672     /**
3673      * Force a new password for device unlock (the password needed to access the entire device) or
3674      * the work profile challenge on the current user. This takes effect immediately.
3675      * <p>
3676      * <em>For device owner and profile owners targeting SDK level
3677      * {@link android.os.Build.VERSION_CODES#O} or above, this API is no longer available and will
3678      * throw {@link SecurityException}. Please use the new API {@link #resetPasswordWithToken}
3679      * instead. </em>
3680      * <p>
3681      * <em>Note: This API has been limited as of {@link android.os.Build.VERSION_CODES#N} for
3682      * device admins that are not device owner and not profile owner.
3683      * The password can now only be changed if there is currently no password set.  Device owner
3684      * and profile owner can still do this when user is unlocked and does not have a managed
3685      * profile.</em>
3686      * <p>
3687      * The given password must be sufficient for the current password quality and length constraints
3688      * as returned by {@link #getPasswordQuality(ComponentName)} and
3689      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3690      * it will be rejected and false returned. Note that the password may be a stronger quality
3691      * (containing alphanumeric characters when the requested quality is only numeric), in which
3692      * case the currently active quality will be increased to match.
3693      * <p>
3694      * Calling with a null or empty password will clear any existing PIN, pattern or password if the
3695      * current password constraints allow it. <em>Note: This will not work in
3696      * {@link android.os.Build.VERSION_CODES#N} and later for managed profiles, or for device admins
3697      * that are not device owner or profile owner.  Once set, the password cannot be changed to null
3698      * or empty except by these admins.</em>
3699      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
3700      * methods does nothing.
3701      * <p>
3702      * The calling device admin must have requested
3703      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
3704      * not, a security exception will be thrown.
3705      *
3706      * @param password The new password for the user. Null or empty clears the password.
3707      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3708      *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3709      * @return Returns true if the password was applied, or false if it is not acceptable for the
3710      *         current constraints or if the user has not been decrypted yet.
3711      * @throws SecurityException if the calling application does not own an active administrator
3712      *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
3713      * @throws IllegalStateException if the calling user is locked or has a managed profile.
3714      */
3715     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPassword(String password, int flags)3716     public boolean resetPassword(String password, int flags) {
3717         throwIfParentInstance("resetPassword");
3718         if (mService != null) {
3719             try {
3720                 return mService.resetPassword(password, flags);
3721             } catch (RemoteException e) {
3722                 throw e.rethrowFromSystemServer();
3723             }
3724         }
3725         return false;
3726     }
3727 
3728     /**
3729      * Called by a profile or device owner to provision a token which can later be used to reset the
3730      * device lockscreen password (if called by device owner), or managed profile challenge (if
3731      * called by profile owner), via {@link #resetPasswordWithToken}.
3732      * <p>
3733      * If the user currently has a lockscreen password, the provisioned token will not be
3734      * immediately usable; it only becomes active after the user performs a confirm credential
3735      * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
3736      * If the user has no lockscreen password, the token is activated immediately. In all cases,
3737      * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
3738      * For security reasons, un-activated tokens are only stored in memory and will be lost once
3739      * the device reboots. In this case a new token needs to be provisioned again.
3740      * <p>
3741      * Once provisioned and activated, the token will remain effective even if the user changes
3742      * or clears the lockscreen password.
3743      * <p>
3744      * <em>This token is highly sensitive and should be treated at the same level as user
3745      * credentials. In particular, NEVER store this token on device in plaintext. Do not store
3746      * the plaintext token in device-encrypted storage if it will be needed to reset password on
3747      * file-based encryption devices before user unlocks. Consider carefully how any password token
3748      * will be stored on your server and who will need access to them. Tokens may be the subject of
3749      * legal access requests.
3750      * </em>
3751      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3752      * reset token is not set and this method returns false.
3753      *
3754      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3755      * @param token a secure token a least 32-byte long, which must be generated by a
3756      *        cryptographically strong random number generator.
3757      * @return true if the operation is successful, false otherwise.
3758      * @throws SecurityException if admin is not a device or profile owner.
3759      * @throws IllegalArgumentException if the supplied token is invalid.
3760      */
3761     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setResetPasswordToken(ComponentName admin, byte[] token)3762     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
3763         throwIfParentInstance("setResetPasswordToken");
3764         if (mService != null) {
3765             try {
3766                 return mService.setResetPasswordToken(admin, token);
3767             } catch (RemoteException e) {
3768                 throw e.rethrowFromSystemServer();
3769             }
3770         }
3771         return false;
3772     }
3773 
3774     /**
3775      * Called by a profile or device owner to revoke the current password reset token.
3776      *
3777      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
3778      * method has no effect - the reset token should not have been set in the first place - and
3779      * false is returned.
3780      *
3781      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3782      * @return true if the operation is successful, false otherwise.
3783      * @throws SecurityException if admin is not a device or profile owner.
3784      */
3785     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
clearResetPasswordToken(ComponentName admin)3786     public boolean clearResetPasswordToken(ComponentName admin) {
3787         throwIfParentInstance("clearResetPasswordToken");
3788         if (mService != null) {
3789             try {
3790                 return mService.clearResetPasswordToken(admin);
3791             } catch (RemoteException e) {
3792                 throw e.rethrowFromSystemServer();
3793             }
3794         }
3795         return false;
3796     }
3797 
3798     /**
3799      * Called by a profile or device owner to check if the current reset password token is active.
3800      *
3801      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3802      * false is always returned.
3803      *
3804      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3805      * @return true if the token is active, false otherwise.
3806      * @throws SecurityException if admin is not a device or profile owner.
3807      * @throws IllegalStateException if no token has been set.
3808      */
3809     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
isResetPasswordTokenActive(ComponentName admin)3810     public boolean isResetPasswordTokenActive(ComponentName admin) {
3811         throwIfParentInstance("isResetPasswordTokenActive");
3812         if (mService != null) {
3813             try {
3814                 return mService.isResetPasswordTokenActive(admin);
3815             } catch (RemoteException e) {
3816                 throw e.rethrowFromSystemServer();
3817             }
3818         }
3819         return false;
3820     }
3821 
3822     /**
3823      * Called by device or profile owner to force set a new device unlock password or a managed
3824      * profile challenge on current user. This takes effect immediately.
3825      * <p>
3826      * Unlike {@link #resetPassword}, this API can change the password even before the user or
3827      * device is unlocked or decrypted. The supplied token must have been previously provisioned via
3828      * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
3829      * <p>
3830      * The given password must be sufficient for the current password quality and length constraints
3831      * as returned by {@link #getPasswordQuality(ComponentName)} and
3832      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3833      * it will be rejected and false returned. Note that the password may be a stronger quality, for
3834      * example, a password containing alphanumeric characters when the requested quality is only
3835      * numeric.
3836      * <p>
3837      * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
3838      * password if the current password constraints allow it.
3839      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3840      * calling this methods has no effect - the password is always empty - and false is returned.
3841      *
3842      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3843      * @param password The new password for the user. {@code null} or empty clears the password.
3844      * @param token the password reset token previously provisioned by
3845      *        {@link #setResetPasswordToken}.
3846      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3847      *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3848      * @return Returns true if the password was applied, or false if it is not acceptable for the
3849      *         current constraints.
3850      * @throws SecurityException if admin is not a device or profile owner.
3851      * @throws IllegalStateException if the provided token is not valid.
3852      */
3853     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPasswordWithToken(@onNull ComponentName admin, String password, byte[] token, int flags)3854     public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
3855             byte[] token, int flags) {
3856         throwIfParentInstance("resetPassword");
3857         if (mService != null) {
3858             try {
3859                 return mService.resetPasswordWithToken(admin, password, token, flags);
3860             } catch (RemoteException e) {
3861                 throw e.rethrowFromSystemServer();
3862             }
3863         }
3864         return false;
3865     }
3866 
3867     /**
3868      * Called by an application that is administering the device to set the maximum time for user
3869      * activity until the device will lock. This limits the length that the user can set. It takes
3870      * effect immediately.
3871      * <p>
3872      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3873      * to be able to call this method; if it has not, a security exception will be thrown.
3874      * <p>
3875      * This method can be called on the {@link DevicePolicyManager} instance returned by
3876      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3877      * profile.
3878      *
3879      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3880      * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
3881      *            is no restriction.
3882      * @throws SecurityException if {@code admin} is not an active administrator or it does not use
3883      *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3884      */
setMaximumTimeToLock(@onNull ComponentName admin, long timeMs)3885     public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
3886         if (mService != null) {
3887             try {
3888                 mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
3889             } catch (RemoteException e) {
3890                 throw e.rethrowFromSystemServer();
3891             }
3892         }
3893     }
3894 
3895     /**
3896      * Retrieve the current maximum time to unlock for a particular admin or all admins that set
3897      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3898      * a separate challenge are not taken into account.
3899      *
3900      * <p>This method can be called on the {@link DevicePolicyManager} instance
3901      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3902      * restrictions on the parent profile.
3903      *
3904      * @param admin The name of the admin component to check, or {@code null} to aggregate
3905      * all admins.
3906      * @return time in milliseconds for the given admin or the minimum value (strictest) of
3907      * all admins if admin is null. Returns 0 if there are no restrictions.
3908      */
getMaximumTimeToLock(@ullable ComponentName admin)3909     public long getMaximumTimeToLock(@Nullable ComponentName admin) {
3910         return getMaximumTimeToLock(admin, myUserId());
3911     }
3912 
3913     /** @hide per-user version */
3914     @UnsupportedAppUsage
getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)3915     public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
3916         if (mService != null) {
3917             try {
3918                 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
3919             } catch (RemoteException e) {
3920                 throw e.rethrowFromSystemServer();
3921             }
3922         }
3923         return 0;
3924     }
3925 
3926     /**
3927      * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
3928      * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a
3929      * strong authentication method like password, pin or pattern.
3930      *
3931      * <p>This timeout is used internally to reset the timer to require strong auth again after
3932      * specified timeout each time it has been successfully used.
3933      *
3934      * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
3935      *
3936      * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3937      *
3938      * <p>The calling device admin must be a device or profile owner. If it is not,
3939      * a {@link SecurityException} will be thrown.
3940      *
3941      * <p>The calling device admin can verify the value it has set by calling
3942      * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
3943      *
3944      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
3945      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3946      * profile.
3947      *
3948      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3949      * calling this methods has no effect - i.e. the timeout is not set.
3950      *
3951      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3952      * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
3953      *         with strong authentication method. A value of 0 means the admin is not participating
3954      *         in controlling the timeout.
3955      *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
3956      *         72 hours, respectively. Though discouraged, the admin may choose to require strong
3957      *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
3958      *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3959      *
3960      * @throws SecurityException if {@code admin} is not a device or profile owner.
3961      */
3962     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setRequiredStrongAuthTimeout(@onNull ComponentName admin, long timeoutMs)3963     public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
3964             long timeoutMs) {
3965         if (mService != null) {
3966             try {
3967                 mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
3968             } catch (RemoteException e) {
3969                 throw e.rethrowFromSystemServer();
3970             }
3971         }
3972     }
3973 
3974     /**
3975      * Determine for how long the user will be able to use secondary, non strong auth for
3976      * authentication, since last strong method authentication (password, pin or pattern) was used.
3977      * After the returned timeout the user is required to use strong authentication method.
3978      *
3979      * <p>This method can be called on the {@link DevicePolicyManager} instance
3980      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3981      * restrictions on the parent profile.
3982      *
3983      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3984      * 0 is returned to indicate that no timeout is configured.
3985      *
3986      * @param admin The name of the admin component to check, or {@code null} to aggregate
3987      *         across all participating admins.
3988      * @return The timeout in milliseconds or 0 if not configured for the provided admin.
3989      */
3990     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin)3991     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
3992         return getRequiredStrongAuthTimeout(admin, myUserId());
3993     }
3994 
3995     /** @hide per-user version */
3996     @UnsupportedAppUsage
3997     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)3998     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
3999         if (mService != null) {
4000             try {
4001                 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
4002             } catch (RemoteException e) {
4003                 throw e.rethrowFromSystemServer();
4004             }
4005         }
4006         return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4007     }
4008 
4009     /**
4010      * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
4011      * keyring. The user's credential will need to be entered again in order to derive the
4012      * credential encryption key that will be stored back in the keyring for future use.
4013      * <p>
4014      * This flag can only be used by a profile owner when locking a managed profile when
4015      * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4016      * <p>
4017      * In order to secure user data, the user will be stopped and restarted so apps should wait
4018      * until they are next run to perform further actions.
4019      */
4020     public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
4021 
4022     /** @hide */
4023     @Retention(RetentionPolicy.SOURCE)
4024     @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
4025             FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
4026     })
4027     public @interface LockNowFlag {}
4028 
4029     /**
4030      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
4031      * this call.
4032      * <p>
4033      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4034      * to be able to call this method; if it has not, a security exception will be thrown.
4035      * <p>
4036      * This method can be called on the {@link DevicePolicyManager} instance returned by
4037      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
4038      * <p>
4039      * Equivalent to calling {@link #lockNow(int)} with no flags.
4040      *
4041      * @throws SecurityException if the calling application does not own an active administrator
4042      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4043      */
lockNow()4044     public void lockNow() {
4045         lockNow(0);
4046     }
4047 
4048     /**
4049      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
4050      * this call.
4051      * <p>
4052      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4053      * to be able to call this method; if it has not, a security exception will be thrown.
4054      * <p>
4055      * This method can be called on the {@link DevicePolicyManager} instance returned by
4056      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
4057      *
4058      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
4059      * @throws SecurityException if the calling application does not own an active administrator
4060      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
4061      *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
4062      *             that is not a profile
4063      *             owner of a managed profile.
4064      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
4065      *             passed when locking the parent profile.
4066      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
4067      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
4068      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4069      */
lockNow(@ockNowFlag int flags)4070     public void lockNow(@LockNowFlag int flags) {
4071         if (mService != null) {
4072             try {
4073                 mService.lockNow(flags, mParentInstance);
4074             } catch (RemoteException e) {
4075                 throw e.rethrowFromSystemServer();
4076             }
4077         }
4078     }
4079 
4080     /**
4081      * Flag for {@link #wipeData(int)}: also erase the device's external
4082      * storage (such as SD cards).
4083      */
4084     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
4085 
4086     /**
4087      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
4088      * data.
4089      *
4090      * <p>This flag may only be set by device owner admins; if it is set by
4091      * other admins a {@link SecurityException} will be thrown.
4092      */
4093     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
4094 
4095     /**
4096      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
4097      */
4098     public static final int WIPE_EUICC = 0x0004;
4099 
4100     /**
4101      * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
4102      */
4103     public static final int WIPE_SILENTLY = 0x0008;
4104 
4105     /**
4106      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
4107      * other users will remain unaffected. Calling from the primary user will cause the device to
4108      * reboot, erasing all device data - including all the secondary users and their data - while
4109      * booting up.
4110      * <p>
4111      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
4112      * be able to call this method; if it has not, a security exception will be thrown.
4113      *
4114      * @param flags Bit mask of additional options: currently supported flags are
4115      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
4116      *            {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
4117      * @throws SecurityException if the calling application does not own an active administrator
4118      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
4119      */
wipeData(int flags)4120     public void wipeData(int flags) {
4121         throwIfParentInstance("wipeData");
4122         final String wipeReasonForUser = mContext.getString(
4123                 R.string.work_profile_deleted_description_dpm_wipe);
4124         wipeDataInternal(flags, wipeReasonForUser);
4125     }
4126 
4127     /**
4128      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
4129      * other users will remain unaffected, the provided reason for wiping data can be shown to
4130      * user. Calling from the primary user will cause the device to reboot, erasing all device data
4131      * - including all the secondary users and their data - while booting up. In this case, we don't
4132      * show the reason to the user since the device would be factory reset.
4133      * <p>
4134      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
4135      * be able to call this method; if it has not, a security exception will be thrown.
4136      *
4137      * @param flags Bit mask of additional options: currently supported flags are
4138      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
4139      *            {@link #WIPE_EUICC}.
4140      * @param reason a string that contains the reason for wiping data, which can be
4141      *            presented to the user.
4142      * @throws SecurityException if the calling application does not own an active administrator
4143      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
4144      * @throws IllegalArgumentException if the input reason string is null or empty, or if
4145      *            {@link #WIPE_SILENTLY} is set.
4146      */
wipeData(int flags, @NonNull CharSequence reason)4147     public void wipeData(int flags, @NonNull CharSequence reason) {
4148         throwIfParentInstance("wipeData");
4149         Preconditions.checkNotNull(reason, "reason string is null");
4150         Preconditions.checkStringNotEmpty(reason, "reason string is empty");
4151         Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
4152         wipeDataInternal(flags, reason.toString());
4153     }
4154 
4155     /**
4156      * Internal function for both {@link #wipeData(int)} and
4157      * {@link #wipeData(int, CharSequence)} to call.
4158      *
4159      * @see #wipeData(int)
4160      * @see #wipeData(int, CharSequence)
4161      * @hide
4162      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser)4163     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
4164         if (mService != null) {
4165             try {
4166                 mService.wipeDataWithReason(flags, wipeReasonForUser);
4167             } catch (RemoteException e) {
4168                 throw e.rethrowFromSystemServer();
4169             }
4170         }
4171     }
4172 
4173     /**
4174      * Called by an application that is administering the device to set the
4175      * global proxy and exclusion list.
4176      * <p>
4177      * The calling device admin must have requested
4178      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
4179      * this method; if it has not, a security exception will be thrown.
4180      * Only the first device admin can set the proxy. If a second admin attempts
4181      * to set the proxy, the {@link ComponentName} of the admin originally setting the
4182      * proxy will be returned. If successful in setting the proxy, {@code null} will
4183      * be returned.
4184      * The method can be called repeatedly by the device admin alrady setting the
4185      * proxy to update the proxy and exclusion list.
4186      *
4187      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4188      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
4189      *            Pass Proxy.NO_PROXY to reset the proxy.
4190      * @param exclusionList a list of domains to be excluded from the global proxy.
4191      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
4192      *            of the device admin that sets the proxy.
4193      * @hide
4194      */
4195     @UnsupportedAppUsage
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )4196     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
4197             List<String> exclusionList ) {
4198         throwIfParentInstance("setGlobalProxy");
4199         if (proxySpec == null) {
4200             throw new NullPointerException();
4201         }
4202         if (mService != null) {
4203             try {
4204                 String hostSpec;
4205                 String exclSpec;
4206                 if (proxySpec.equals(Proxy.NO_PROXY)) {
4207                     hostSpec = null;
4208                     exclSpec = null;
4209                 } else {
4210                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
4211                         throw new IllegalArgumentException();
4212                     }
4213                     InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
4214                     String hostName = sa.getHostName();
4215                     int port = sa.getPort();
4216                     StringBuilder hostBuilder = new StringBuilder();
4217                     hostSpec = hostBuilder.append(hostName)
4218                         .append(":").append(Integer.toString(port)).toString();
4219                     if (exclusionList == null) {
4220                         exclSpec = "";
4221                     } else {
4222                         StringBuilder listBuilder = new StringBuilder();
4223                         boolean firstDomain = true;
4224                         for (String exclDomain : exclusionList) {
4225                             if (!firstDomain) {
4226                                 listBuilder = listBuilder.append(",");
4227                             } else {
4228                                 firstDomain = false;
4229                             }
4230                             listBuilder = listBuilder.append(exclDomain.trim());
4231                         }
4232                         exclSpec = listBuilder.toString();
4233                     }
4234                     if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
4235                             != android.net.Proxy.PROXY_VALID)
4236                         throw new IllegalArgumentException();
4237                 }
4238                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
4239             } catch (RemoteException e) {
4240                 throw e.rethrowFromSystemServer();
4241             }
4242         }
4243         return null;
4244     }
4245 
4246     /**
4247      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
4248      * HTTP proxies - they are generally network dependent. However if you're doing something
4249      * unusual like general internal filtering this may be useful. On a private network where the
4250      * proxy is not accessible, you may break HTTP using this.
4251      * <p>
4252      * This method requires the caller to be the device owner.
4253      * <p>
4254      * This proxy is only a recommendation and it is possible that some apps will ignore it.
4255      *
4256      * @see ProxyInfo
4257      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4258      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
4259      *            {@code null} value will clear the global HTTP proxy.
4260      * @throws SecurityException if {@code admin} is not the device owner.
4261      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)4262     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
4263             proxyInfo) {
4264         throwIfParentInstance("setRecommendedGlobalProxy");
4265         if (mService != null) {
4266             try {
4267                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
4268             } catch (RemoteException e) {
4269                 throw e.rethrowFromSystemServer();
4270             }
4271         }
4272     }
4273 
4274     /**
4275      * Returns the component name setting the global proxy.
4276      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
4277      *         if no admin has set the proxy.
4278      * @hide
4279      */
getGlobalProxyAdmin()4280     public @Nullable ComponentName getGlobalProxyAdmin() {
4281         if (mService != null) {
4282             try {
4283                 return mService.getGlobalProxyAdmin(myUserId());
4284             } catch (RemoteException e) {
4285                 throw e.rethrowFromSystemServer();
4286             }
4287         }
4288         return null;
4289     }
4290 
4291     /**
4292      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4293      * indicating that encryption is not supported.
4294      */
4295     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
4296 
4297     /**
4298      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4299      * indicating that encryption is supported, but is not currently active.
4300      */
4301     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
4302 
4303     /**
4304      * Result code for {@link #getStorageEncryptionStatus}:
4305      * indicating that encryption is not currently active, but is currently
4306      * being activated.  This is only reported by devices that support
4307      * encryption of data and only when the storage is currently
4308      * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
4309      * to become encrypted will never return this value.
4310      */
4311     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
4312 
4313     /**
4314      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4315      * indicating that encryption is active.
4316      * <p>
4317      * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4318      */
4319     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
4320 
4321     /**
4322      * Result code for {@link #getStorageEncryptionStatus}:
4323      * indicating that encryption is active, but an encryption key has not
4324      * been set by the user.
4325      */
4326     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
4327 
4328     /**
4329      * Result code for {@link #getStorageEncryptionStatus}:
4330      * indicating that encryption is active and the encryption key is tied to the user or profile.
4331      * <p>
4332      * This value is only returned to apps targeting API level 24 and above. For apps targeting
4333      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
4334      * encryption key is specific to the user or profile.
4335      */
4336     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
4337 
4338     /**
4339      * Activity action: begin the process of encrypting data on the device.  This activity should
4340      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
4341      * After resuming from this activity, use {@link #getStorageEncryption}
4342      * to check encryption status.  However, on some devices this activity may never return, as
4343      * it may trigger a reboot and in some cases a complete data wipe of the device.
4344      */
4345     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
4346     public static final String ACTION_START_ENCRYPTION
4347             = "android.app.action.START_ENCRYPTION";
4348 
4349     /**
4350      * Broadcast action: notify managed provisioning that new managed user is created.
4351      *
4352      * @hide
4353      */
4354     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4355     public static final String ACTION_MANAGED_USER_CREATED =
4356             "android.app.action.MANAGED_USER_CREATED";
4357 
4358     /**
4359      * Widgets are enabled in keyguard
4360      */
4361     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
4362 
4363     /**
4364      * Disable all keyguard widgets. Has no effect starting from
4365      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
4366      * on Android versions lower than 5.0.
4367      */
4368     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
4369 
4370     /**
4371      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
4372      */
4373     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
4374 
4375     /**
4376      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
4377      */
4378     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
4379 
4380     /**
4381      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
4382      */
4383     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
4384 
4385     /**
4386      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
4387      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
4388      * whitelist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
4389      * used in conjuction to set trust-agent-specific configurations.
4390      */
4391     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
4392 
4393     /**
4394      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4395      */
4396     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
4397 
4398     /**
4399      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
4400      * This flag has no effect starting from version {@link android.os.Build.VERSION_CODES#N}
4401      */
4402     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
4403 
4404     /**
4405      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4406      */
4407     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
4408 
4409     /**
4410      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4411      */
4412     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
4413 
4414     /**
4415      * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
4416      * CTS test when adding to the list above.
4417      */
4418 
4419     /**
4420      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4421      */
4422     public static final int KEYGUARD_DISABLE_BIOMETRICS =
4423             DevicePolicyManager.KEYGUARD_DISABLE_FACE
4424             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
4425             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
4426 
4427     /**
4428      * Disable all current and future keyguard customizations.
4429      */
4430     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
4431 
4432     /**
4433      * Keyguard features that when set on a managed profile that doesn't have its own challenge will
4434      * affect the profile's parent user. These can also be set on the managed profile's parent
4435      * {@link DevicePolicyManager} instance.
4436      *
4437      * @hide
4438      */
4439     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
4440             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
4441             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
4442 
4443     /**
4444      * Called by an application that is administering the device to request that the storage system
4445      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
4446      * <p>
4447      * When multiple device administrators attempt to control device encryption, the most secure,
4448      * supported setting will always be used. If any device administrator requests device
4449      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
4450      * device encryption while another device administrator has enabled it, the call to disable will
4451      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
4452      * <p>
4453      * This policy controls encryption of the secure (application data) storage area. Data written
4454      * to other storage areas may or may not be encrypted, and this policy does not require or
4455      * control the encryption of any other storage areas. There is one exception: If
4456      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
4457      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
4458      * written to disk within the encrypted storage area.
4459      * <p>
4460      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
4461      * to create a device PIN or Password. In this case, the storage is encrypted, but the
4462      * encryption key may not be fully secured. For maximum security, the administrator should also
4463      * require (and check for) a pattern, PIN, or password.
4464      *
4465      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4466      * @param encrypt true to request encryption, false to release any previous request
4467      * @return the new total request status (for all active admins), or {@link
4468      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
4469      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
4470      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
4471      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
4472      *         state.
4473      *
4474      * @throws SecurityException if {@code admin} is not an active administrator or does not use
4475      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
4476      */
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)4477     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
4478         throwIfParentInstance("setStorageEncryption");
4479         if (mService != null) {
4480             try {
4481                 return mService.setStorageEncryption(admin, encrypt);
4482             } catch (RemoteException e) {
4483                 throw e.rethrowFromSystemServer();
4484             }
4485         }
4486         return ENCRYPTION_STATUS_UNSUPPORTED;
4487     }
4488 
4489     /**
4490      * Called by an application that is administering the device to
4491      * determine the requested setting for secure storage.
4492      *
4493      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
4494      * this will return the requested encryption setting as an aggregate of all active
4495      * administrators.
4496      * @return true if the admin(s) are requesting encryption, false if not.
4497      */
getStorageEncryption(@ullable ComponentName admin)4498     public boolean getStorageEncryption(@Nullable ComponentName admin) {
4499         throwIfParentInstance("getStorageEncryption");
4500         if (mService != null) {
4501             try {
4502                 return mService.getStorageEncryption(admin, myUserId());
4503             } catch (RemoteException e) {
4504                 throw e.rethrowFromSystemServer();
4505             }
4506         }
4507         return false;
4508     }
4509 
4510     /**
4511      * Called by an application that is administering the device to
4512      * determine the current encryption status of the device.
4513      * <p>
4514      * Depending on the returned status code, the caller may proceed in different
4515      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
4516      * storage system does not support encryption.  If the
4517      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
4518      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
4519      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
4520      * storage system has enabled encryption but no password is set so further action
4521      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
4522      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
4523      * no further action is required.
4524      *
4525      * @return current status of encryption. The value will be one of
4526      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
4527      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
4528      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4529      */
getStorageEncryptionStatus()4530     public int getStorageEncryptionStatus() {
4531         throwIfParentInstance("getStorageEncryptionStatus");
4532         return getStorageEncryptionStatus(myUserId());
4533     }
4534 
4535     /** @hide per-user version */
4536     @UnsupportedAppUsage
getStorageEncryptionStatus(int userHandle)4537     public int getStorageEncryptionStatus(int userHandle) {
4538         if (mService != null) {
4539             try {
4540                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
4541             } catch (RemoteException e) {
4542                 throw e.rethrowFromSystemServer();
4543             }
4544         }
4545         return ENCRYPTION_STATUS_UNSUPPORTED;
4546     }
4547 
4548     /**
4549      * Mark a CA certificate as approved by the device user. This means that they have been notified
4550      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
4551      * keep the certificate on the device.
4552      *
4553      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
4554      * this certificate.
4555      *
4556      * @hide
4557      */
approveCaCert(String alias, int userHandle, boolean approval)4558     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
4559         if (mService != null) {
4560             try {
4561                 return mService.approveCaCert(alias, userHandle, approval);
4562             } catch (RemoteException e) {
4563                 throw e.rethrowFromSystemServer();
4564             }
4565         }
4566         return false;
4567     }
4568 
4569     /**
4570      * Check whether a CA certificate has been approved by the device user.
4571      *
4572      * @hide
4573      */
isCaCertApproved(String alias, int userHandle)4574     public boolean isCaCertApproved(String alias, int userHandle) {
4575         if (mService != null) {
4576             try {
4577                 return mService.isCaCertApproved(alias, userHandle);
4578             } catch (RemoteException e) {
4579                 throw e.rethrowFromSystemServer();
4580             }
4581         }
4582         return false;
4583     }
4584 
4585     /**
4586      * Installs the given certificate as a user CA.
4587      * <p>
4588      * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
4589      * higher. App developers can change the default behavior for an app by adding a
4590      * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
4591      * File</a> to the app manifest file.
4592      *
4593      * The caller must be a profile or device owner on that user, or a delegate package given the
4594      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
4595      * security exception will be thrown.
4596      *
4597      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4598      *              {@code null} if calling from a delegated certificate installer.
4599      * @param certBuffer encoded form of the certificate to install.
4600      *
4601      * @return false if the certBuffer cannot be parsed or installation is
4602      *         interrupted, true otherwise.
4603      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4604      *         owner.
4605      * @see #setDelegatedScopes
4606      * @see #DELEGATION_CERT_INSTALL
4607      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)4608     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
4609         throwIfParentInstance("installCaCert");
4610         if (mService != null) {
4611             try {
4612                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
4613             } catch (RemoteException e) {
4614                 throw e.rethrowFromSystemServer();
4615             }
4616         }
4617         return false;
4618     }
4619 
4620     /**
4621      * Uninstalls the given certificate from trusted user CAs, if present.
4622      *
4623      * The caller must be a profile or device owner on that user, or a delegate package given the
4624      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
4625      * security exception will be thrown.
4626      *
4627      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4628      *              {@code null} if calling from a delegated certificate installer.
4629      * @param certBuffer encoded form of the certificate to remove.
4630      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4631      *         owner.
4632      * @see #setDelegatedScopes
4633      * @see #DELEGATION_CERT_INSTALL
4634      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)4635     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
4636         throwIfParentInstance("uninstallCaCert");
4637         if (mService != null) {
4638             try {
4639                 final String alias = getCaCertAlias(certBuffer);
4640                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
4641             } catch (CertificateException e) {
4642                 Log.w(TAG, "Unable to parse certificate", e);
4643             } catch (RemoteException e) {
4644                 throw e.rethrowFromSystemServer();
4645             }
4646         }
4647     }
4648 
4649     /**
4650      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
4651      * If a user has installed any certificates by other means than device policy these will be
4652      * included too.
4653      *
4654      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4655      *              {@code null} if calling from a delegated certificate installer.
4656      * @return a List of byte[] arrays, each encoding one user CA certificate.
4657      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4658      *         owner.
4659      */
getInstalledCaCerts(@ullable ComponentName admin)4660     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
4661         final List<byte[]> certs = new ArrayList<byte[]>();
4662         throwIfParentInstance("getInstalledCaCerts");
4663         if (mService != null) {
4664             try {
4665                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
4666                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
4667                 for (String alias : certStore.userAliases()) {
4668                     try {
4669                         certs.add(certStore.getCertificate(alias).getEncoded());
4670                     } catch (CertificateException ce) {
4671                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
4672                     }
4673                 }
4674             } catch (RemoteException re) {
4675                 throw re.rethrowFromSystemServer();
4676             }
4677         }
4678         return certs;
4679     }
4680 
4681     /**
4682      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
4683      * means other than device policy will also be removed, except for system CA certificates.
4684      *
4685      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4686      *              {@code null} if calling from a delegated certificate installer.
4687      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4688      *         owner.
4689      */
uninstallAllUserCaCerts(@ullable ComponentName admin)4690     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
4691         throwIfParentInstance("uninstallAllUserCaCerts");
4692         if (mService != null) {
4693             try {
4694                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
4695                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
4696             } catch (RemoteException re) {
4697                 throw re.rethrowFromSystemServer();
4698             }
4699         }
4700     }
4701 
4702     /**
4703      * Returns whether this certificate is installed as a trusted CA.
4704      *
4705      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4706      *              {@code null} if calling from a delegated certificate installer.
4707      * @param certBuffer encoded form of the certificate to look up.
4708      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4709      *         owner.
4710      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)4711     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
4712         throwIfParentInstance("hasCaCertInstalled");
4713         if (mService != null) {
4714             try {
4715                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
4716                 return getCaCertAlias(certBuffer) != null;
4717             } catch (RemoteException re) {
4718                 throw re.rethrowFromSystemServer();
4719             } catch (CertificateException ce) {
4720                 Log.w(TAG, "Could not parse certificate", ce);
4721             }
4722         }
4723         return false;
4724     }
4725 
4726     /**
4727      * Called by a device or profile owner, or delegated certificate installer, to install a
4728      * certificate and corresponding private key. All apps within the profile will be able to access
4729      * the certificate and use the private key, given direct user approval.
4730      *
4731      * <p>Access to the installed credentials will not be granted to the caller of this API without
4732      * direct user approval. This is for security - should a certificate installer become
4733      * compromised, certificates it had already installed will be protected.
4734      *
4735      * <p>If the installer must have access to the credentials, call
4736      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
4737      *
4738      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
4739      * have been given to access the key and certificates associated with this alias will be
4740      * revoked.
4741      *
4742      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4743      *            {@code null} if calling from a delegated certificate installer.
4744      * @param privKey The private key to install.
4745      * @param cert The certificate to install.
4746      * @param alias The private key alias under which to install the certificate. If a certificate
4747      * with that alias already exists, it will be overwritten.
4748      * @return {@code true} if the keys were installed, {@code false} otherwise.
4749      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4750      *         owner.
4751      * @see #setDelegatedScopes
4752      * @see #DELEGATION_CERT_INSTALL
4753      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)4754     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4755             @NonNull Certificate cert, @NonNull String alias) {
4756         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
4757     }
4758 
4759     /**
4760      * Called by a device or profile owner, or delegated certificate installer, to install a
4761      * certificate chain and corresponding private key for the leaf certificate. All apps within the
4762      * profile will be able to access the certificate chain and use the private key, given direct
4763      * user approval.
4764      *
4765      * <p>The caller of this API may grant itself access to the certificate and private key
4766      * immediately, without user approval. It is a best practice not to request this unless strictly
4767      * necessary since it opens up additional security vulnerabilities.
4768      *
4769      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
4770      * have been given to access the key and certificates associated with this alias will be
4771      * revoked.
4772      *
4773      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4774      *        {@code null} if calling from a delegated certificate installer.
4775      * @param privKey The private key to install.
4776      * @param certs The certificate chain to install. The chain should start with the leaf
4777      *        certificate and include the chain of trust in order. This will be returned by
4778      *        {@link android.security.KeyChain#getCertificateChain}.
4779      * @param alias The private key alias under which to install the certificate. If a certificate
4780      *        with that alias already exists, it will be overwritten.
4781      * @param requestAccess {@code true} to request that the calling app be granted access to the
4782      *        credentials immediately. Otherwise, access to the credentials will be gated by user
4783      *        approval.
4784      * @return {@code true} if the keys were installed, {@code false} otherwise.
4785      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4786      *         owner.
4787      * @see android.security.KeyChain#getCertificateChain
4788      * @see #setDelegatedScopes
4789      * @see #DELEGATION_CERT_INSTALL
4790      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)4791     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4792             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
4793         int flags = INSTALLKEY_SET_USER_SELECTABLE;
4794         if (requestAccess) {
4795             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
4796         }
4797         return installKeyPair(admin, privKey, certs, alias, flags);
4798     }
4799 
4800     /**
4801      * Called by a device or profile owner, or delegated certificate installer, to install a
4802      * certificate chain and corresponding private key for the leaf certificate. All apps within the
4803      * profile will be able to access the certificate chain and use the private key, given direct
4804      * user approval (if the user is allowed to select the private key).
4805      *
4806      * <p>The caller of this API may grant itself access to the certificate and private key
4807      * immediately, without user approval. It is a best practice not to request this unless strictly
4808      * necessary since it opens up additional security vulnerabilities.
4809      *
4810      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
4811      * the user to select the key from a dialog.
4812      *
4813      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
4814      * have been given to access the key and certificates associated with this alias will be
4815      * revoked.
4816      *
4817      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4818      *        {@code null} if calling from a delegated certificate installer.
4819      * @param privKey The private key to install.
4820      * @param certs The certificate chain to install. The chain should start with the leaf
4821      *        certificate and include the chain of trust in order. This will be returned by
4822      *        {@link android.security.KeyChain#getCertificateChain}.
4823      * @param alias The private key alias under which to install the certificate. If a certificate
4824      *        with that alias already exists, it will be overwritten.
4825      * @param flags Flags to request that the calling app be granted access to the credentials
4826      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
4827      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
4828      * @return {@code true} if the keys were installed, {@code false} otherwise.
4829      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4830      *         owner.
4831      * @see android.security.KeyChain#getCertificateChain
4832      * @see #setDelegatedScopes
4833      * @see #DELEGATION_CERT_INSTALL
4834      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)4835     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4836             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
4837         throwIfParentInstance("installKeyPair");
4838         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
4839                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
4840         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
4841                 == INSTALLKEY_SET_USER_SELECTABLE;
4842         try {
4843             final byte[] pemCert = Credentials.convertToPem(certs[0]);
4844             byte[] pemChain = null;
4845             if (certs.length > 1) {
4846                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
4847             }
4848             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
4849                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
4850             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
4851                     pemChain, alias, requestAccess, isUserSelectable);
4852         } catch (RemoteException e) {
4853             throw e.rethrowFromSystemServer();
4854         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
4855             Log.w(TAG, "Failed to obtain private key material", e);
4856         } catch (CertificateException | IOException e) {
4857             Log.w(TAG, "Could not pem-encode certificate", e);
4858         }
4859         return false;
4860     }
4861 
4862     /**
4863      * Called by a device or profile owner, or delegated certificate installer, to remove a
4864      * certificate and private key pair installed under a given alias.
4865      *
4866      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4867      *        {@code null} if calling from a delegated certificate installer.
4868      * @param alias The private key alias under which the certificate is installed.
4869      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
4870      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4871      *         owner.
4872      * @see #setDelegatedScopes
4873      * @see #DELEGATION_CERT_INSTALL
4874      */
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)4875     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
4876         throwIfParentInstance("removeKeyPair");
4877         try {
4878             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4879         } catch (RemoteException e) {
4880             throw e.rethrowFromSystemServer();
4881         }
4882     }
4883 
4884     /**
4885      * Called by a device or profile owner, or delegated certificate installer, to generate a
4886      * new private/public key pair. If the device supports key generation via secure hardware,
4887      * this method is useful for creating a key in KeyChain that never left the secure hardware.
4888      * Access to the key is controlled the same way as in {@link #installKeyPair}.
4889      *
4890      * <p>Because this method might take several seconds to complete, it should only be called from
4891      * a worker thread. This method returns {@code null} when called from the main thread.
4892      *
4893      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
4894      * have been given to access the key and certificates associated with this alias will be
4895      * revoked.
4896      *
4897      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4898      *            {@code null} if calling from a delegated certificate installer.
4899      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
4900      * @param keySpec Specification of the key to generate, see
4901      * {@link java.security.KeyPairGenerator}.
4902      * @param idAttestationFlags A bitmask of all the identifiers that should be included in the
4903      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
4904      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), or {@code 0} if no device
4905      *        identification is required in the attestation record.
4906      *        Device owner, profile owner and their delegated certificate installer can use
4907      *        {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device information
4908      *        including manufacturer, model, brand, device and product in the attestation record.
4909      *        Only device owner and their delegated certificate installer can use
4910      *        {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID} to request
4911      *        unique device identifiers to be attested.
4912      *        <p>
4913      *        If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
4914      *        is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
4915      *        <p>
4916      *        If any flag is specified, then an attestation challenge must be included in the
4917      *        {@code keySpec}.
4918      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
4919      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4920      *         owner. If Device ID attestation is requested (using {@link #ID_TYPE_SERIAL},
4921      *         {@link #ID_TYPE_IMEI} or {@link #ID_TYPE_MEID}), the caller must be the Device Owner
4922      *         or the Certificate Installer delegate.
4923      * @throws IllegalArgumentException if the alias in {@code keySpec} is empty, if the
4924      *         algorithm specification in {@code keySpec} is not {@code RSAKeyGenParameterSpec}
4925      *         or {@code ECGenParameterSpec}, or if Device ID attestation was requested but the
4926      *         {@code keySpec} does not contain an attestation challenge.
4927      * @throws UnsupportedOperationException if Device ID attestation was requested but the
4928      *         underlying hardware does not support it.
4929      * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
4930      *         specified in {@code keySpec} but the device does not have one.
4931      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
4932      */
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)4933     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
4934             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
4935             @AttestationIdType int idAttestationFlags) {
4936         throwIfParentInstance("generateKeyPair");
4937         try {
4938             final ParcelableKeyGenParameterSpec parcelableSpec =
4939                     new ParcelableKeyGenParameterSpec(keySpec);
4940             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
4941 
4942             // Translate ID attestation flags to values used by AttestationUtils
4943             final boolean success = mService.generateKeyPair(
4944                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
4945                     idAttestationFlags, attestationChain);
4946             if (!success) {
4947                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
4948                 return null;
4949             }
4950 
4951             final String alias = keySpec.getKeystoreAlias();
4952             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
4953             Certificate[] outputChain = null;
4954             try {
4955                 if (AttestationUtils.isChainValid(attestationChain)) {
4956                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
4957                 }
4958             } catch (KeyAttestationException e) {
4959                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
4960                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4961                 return null;
4962             }
4963             return new AttestedKeyPair(keyPair, outputChain);
4964         } catch (RemoteException e) {
4965             throw e.rethrowFromSystemServer();
4966         } catch (KeyChainException e) {
4967             Log.w(TAG, "Failed to generate key", e);
4968         } catch (InterruptedException e) {
4969             Log.w(TAG, "Interrupted while generating key", e);
4970             Thread.currentThread().interrupt();
4971         } catch (ServiceSpecificException e) {
4972             Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
4973             switch (e.errorCode) {
4974                 case KEY_GEN_STRONGBOX_UNAVAILABLE:
4975                     throw new StrongBoxUnavailableException("No StrongBox for key generation.");
4976                 default:
4977                     throw new RuntimeException(
4978                             String.format("Unknown error while generating key: %d", e.errorCode));
4979             }
4980         }
4981         return null;
4982     }
4983 
4984     /**
4985      * Returns {@code true} if the device supports attestation of device identifiers in addition
4986      * to key attestation.
4987      * @return {@code true} if Device ID attestation is supported.
4988      */
isDeviceIdAttestationSupported()4989     public boolean isDeviceIdAttestationSupported() {
4990         PackageManager pm = mContext.getPackageManager();
4991         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
4992     }
4993 
4994     /**
4995      * Called by a device or profile owner, or delegated certificate installer, to associate
4996      * certificates with a key pair that was generated using {@link #generateKeyPair}, and
4997      * set whether the key is available for the user to choose in the certificate selection
4998      * prompt.
4999      *
5000      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5001      *            {@code null} if calling from a delegated certificate installer.
5002      * @param alias The private key alias under which to install the certificate. The {@code alias}
5003      *        should denote an existing private key. If a certificate with that alias already
5004      *        exists, it will be overwritten.
5005      * @param certs The certificate chain to install. The chain should start with the leaf
5006      *        certificate and include the chain of trust in order. This will be returned by
5007      *        {@link android.security.KeyChain#getCertificateChain}.
5008      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
5009      *        certificate selection prompt, {@code false} to indicate that this key can only be
5010      *        granted access by implementing
5011      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
5012      * @return {@code true} if the provided {@code alias} exists and the certificates has been
5013      *        successfully associated with it, {@code false} otherwise.
5014      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5015      *         owner, or {@code admin} is null but the calling application is not a delegated
5016      *         certificate installer.
5017      */
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)5018     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
5019             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
5020         throwIfParentInstance("setKeyPairCertificate");
5021         try {
5022             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
5023             byte[] pemChain = null;
5024             if (certs.size() > 1) {
5025                 pemChain = Credentials.convertToPem(
5026                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
5027             }
5028             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
5029                     pemChain, isUserSelectable);
5030         } catch (RemoteException e) {
5031             throw e.rethrowFromSystemServer();
5032         } catch (CertificateException | IOException e) {
5033             Log.w(TAG, "Could not pem-encode certificate", e);
5034         }
5035         return false;
5036     }
5037 
5038 
5039     /**
5040      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
5041      * doesn't exist.
5042      */
getCaCertAlias(byte[] certBuffer)5043     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
5044         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
5045         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
5046                               new ByteArrayInputStream(certBuffer));
5047         return new TrustedCertificateStore().getCertificateAlias(cert);
5048     }
5049 
5050     /**
5051      * Called by a profile owner or device owner to grant access to privileged certificate
5052      * manipulation APIs to a third-party certificate installer app. Granted APIs include
5053      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
5054      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
5055      * <p>
5056      * Delegated certificate installer is a per-user state. The delegated access is persistent until
5057      * it is later cleared by calling this method with a null value or uninstallling the certificate
5058      * installer.
5059      * <p>
5060      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
5061      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
5062      * supplied certificate installer package must be installed when calling this API, otherwise an
5063      * {@link IllegalArgumentException} will be thrown.
5064      *
5065      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5066      * @param installerPackage The package name of the certificate installer which will be given
5067      *            access. If {@code null} is given the current package will be cleared.
5068      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5069      *
5070      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5071      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
5072      */
5073     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)5074     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
5075             installerPackage) throws SecurityException {
5076         throwIfParentInstance("setCertInstallerPackage");
5077         if (mService != null) {
5078             try {
5079                 mService.setCertInstallerPackage(admin, installerPackage);
5080             } catch (RemoteException e) {
5081                 throw e.rethrowFromSystemServer();
5082             }
5083         }
5084     }
5085 
5086     /**
5087      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
5088      * or {@code null} if none is set. If there are multiple delegates this function will return one
5089      * of them.
5090      *
5091      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5092      * @return The package name of the current delegated certificate installer, or {@code null} if
5093      *         none is set.
5094      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5095      *
5096      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5097      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
5098      */
5099     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)5100     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
5101             throws SecurityException {
5102         throwIfParentInstance("getCertInstallerPackage");
5103         if (mService != null) {
5104             try {
5105                 return mService.getCertInstallerPackage(admin);
5106             } catch (RemoteException e) {
5107                 throw e.rethrowFromSystemServer();
5108             }
5109         }
5110         return null;
5111     }
5112 
5113     /**
5114      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
5115      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
5116      * constants.
5117      * <p>
5118      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
5119      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
5120      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
5121      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
5122      * <p>
5123      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
5124      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
5125      * {@code delegatePackage}.
5126      *
5127      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5128      * @param delegatePackage The package name of the app which will be given access.
5129      * @param scopes The groups of privileged APIs whose access should be granted to
5130      *            {@code delegatedPackage}.
5131      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5132      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)5133      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
5134             @NonNull List<String> scopes) {
5135         throwIfParentInstance("setDelegatedScopes");
5136         if (mService != null) {
5137             try {
5138                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
5139             } catch (RemoteException e) {
5140                 throw e.rethrowFromSystemServer();
5141             }
5142         }
5143     }
5144 
5145     /**
5146      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
5147      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
5148      * passing {@code null} for {@code admin} and their own package name as
5149      * {@code delegatedPackage}.
5150      *
5151      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5152      *            {@code null} if the caller is {@code delegatedPackage}.
5153      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
5154      * @return A list containing the scopes given to {@code delegatedPackage}.
5155      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5156      */
5157      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)5158      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
5159              @NonNull String delegatedPackage) {
5160          throwIfParentInstance("getDelegatedScopes");
5161          if (mService != null) {
5162              try {
5163                  return mService.getDelegatedScopes(admin, delegatedPackage);
5164              } catch (RemoteException e) {
5165                  throw e.rethrowFromSystemServer();
5166              }
5167          }
5168          return null;
5169     }
5170 
5171     /**
5172      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
5173      * granted a delegation scope.
5174      *
5175      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5176      * @param delegationScope The scope whose delegates should be retrieved.
5177      * @return A list of package names of the current delegated packages for
5178                {@code delegationScope}.
5179      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5180      */
5181      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)5182      public List<String> getDelegatePackages(@NonNull ComponentName admin,
5183              @NonNull String delegationScope) {
5184         throwIfParentInstance("getDelegatePackages");
5185         if (mService != null) {
5186             try {
5187                 return mService.getDelegatePackages(admin, delegationScope);
5188             } catch (RemoteException e) {
5189                 throw e.rethrowFromSystemServer();
5190             }
5191         }
5192         return null;
5193     }
5194 
5195     /**
5196      * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
5197      * @hide
5198      */
5199     public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
5200 
5201     /**
5202      * Called by a device or profile owner to configure an always-on VPN connection through a
5203      * specific application for the current user. This connection is automatically granted and
5204      * persisted after a reboot.
5205      * <p> To support the always-on feature, an app must
5206      * <ul>
5207      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
5208      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
5209      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
5210      *     <li><i>not</i> explicitly opt out of the feature through
5211      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
5212      * </ul>
5213      * The call will fail if called with the package name of an unsupported VPN app.
5214      * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
5215      * of the VPN provider could break networking for all apps. This method clears any lockdown
5216      * whitelist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
5217      *
5218      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
5219      *        remove an existing always-on VPN configuration.
5220      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
5221      *        {@code false} otherwise. This has no effect when clearing.
5222      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5223      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
5224      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
5225      *         set as always-on, or if always-on VPN is not available.
5226      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
5227      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)5228     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
5229             boolean lockdownEnabled) throws NameNotFoundException {
5230         setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
5231     }
5232 
5233     /**
5234      * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
5235      * admin to specify a set of apps that should be able to access the network directly when VPN
5236      * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
5237      * System apps can always bypass VPN.
5238      * <p> Note that the system doesn't update the whitelist when packages are installed or
5239      * uninstalled, the admin app must call this method to keep the list up to date.
5240      * <p> When {@code lockdownEnabled} is false {@code lockdownWhitelist} is ignored . When
5241      * {@code lockdownEnabled} is {@code true} and {@code lockdownWhitelist} is {@code null} or
5242      * empty, only system apps can bypass VPN.
5243      * <p> Setting always-on VPN package to {@code null} or using
5244      * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown whitelist.
5245      *
5246      * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
5247      *         to remove an existing always-on VPN configuration
5248      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
5249      *         {@code false} otherwise. This has no effect when clearing.
5250      * @param lockdownWhitelist Packages that will be able to access the network directly when VPN
5251      *         is in lockdown mode but not connected. Has no effect when clearing.
5252      * @throws SecurityException if {@code admin} is not a device or a profile
5253      *         owner.
5254      * @throws NameNotFoundException if {@code vpnPackage} or one of
5255      *         {@code lockdownWhitelist} is not installed.
5256      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
5257      *         not support being set as always-on, or if always-on VPN is not
5258      *         available.
5259      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownWhitelist)5260     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
5261             boolean lockdownEnabled, @Nullable Set<String> lockdownWhitelist)
5262             throws NameNotFoundException {
5263         throwIfParentInstance("setAlwaysOnVpnPackage");
5264         if (mService != null) {
5265             try {
5266                 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
5267                         lockdownWhitelist == null ? null : new ArrayList<>(lockdownWhitelist));
5268             } catch (ServiceSpecificException e) {
5269                 switch (e.errorCode) {
5270                     case ERROR_VPN_PACKAGE_NOT_FOUND:
5271                         throw new NameNotFoundException(e.getMessage());
5272                     default:
5273                         throw new RuntimeException(
5274                                 "Unknown error setting always-on VPN: " + e.errorCode, e);
5275                 }
5276             } catch (RemoteException e) {
5277                 throw e.rethrowFromSystemServer();
5278             }
5279         }
5280     }
5281 
5282     /**
5283      * Called by device or profile owner to query whether current always-on VPN is configured in
5284      * lockdown mode. Returns {@code false} when no always-on configuration is set.
5285      *
5286      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5287      *
5288      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5289      *
5290      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
5291      */
isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)5292     public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
5293         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
5294         if (mService != null) {
5295             try {
5296                 return mService.isAlwaysOnVpnLockdownEnabled(admin);
5297             } catch (RemoteException e) {
5298                 throw e.rethrowFromSystemServer();
5299             }
5300         }
5301         return false;
5302     }
5303 
5304     /**
5305      * Called by device or profile owner to query the set of packages that are allowed to access
5306      * the network directly when always-on VPN is in lockdown mode but not connected. Returns
5307      * {@code null} when always-on VPN is not active or not in lockdown mode.
5308      *
5309      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5310      *
5311      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5312      *
5313      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
5314      */
getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)5315     public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
5316         throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
5317         if (mService != null) {
5318             try {
5319                 final List<String> whitelist =
5320                         mService.getAlwaysOnVpnLockdownWhitelist(admin);
5321                 return whitelist == null ? null : new HashSet<>(whitelist);
5322             } catch (RemoteException e) {
5323                 throw e.rethrowFromSystemServer();
5324             }
5325         }
5326         return null;
5327     }
5328 
5329     /**
5330      * Called by a device or profile owner to read the name of the package administering an
5331      * always-on VPN connection for the current user. If there is no such package, or the always-on
5332      * VPN is provided by the system instead of by an application, {@code null} will be returned.
5333      *
5334      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
5335      *         is set.
5336      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5337      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)5338     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
5339         throwIfParentInstance("getAlwaysOnVpnPackage");
5340         if (mService != null) {
5341             try {
5342                 return mService.getAlwaysOnVpnPackage(admin);
5343             } catch (RemoteException e) {
5344                 throw e.rethrowFromSystemServer();
5345             }
5346         }
5347         return null;
5348     }
5349 
5350     /**
5351      * Called by an application that is administering the device to disable all cameras on the
5352      * device, for this user. After setting this, no applications running as this user will be able
5353      * to access any cameras on the device.
5354      * <p>
5355      * If the caller is device owner, then the restriction will be applied to all users.
5356      * <p>
5357      * The calling device admin must have requested
5358      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
5359      * not, a security exception will be thrown.
5360      *
5361      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5362      * @param disabled Whether or not the camera should be disabled.
5363      * @throws SecurityException if {@code admin} is not an active administrator or does not use
5364      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
5365      */
setCameraDisabled(@onNull ComponentName admin, boolean disabled)5366     public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
5367         throwIfParentInstance("setCameraDisabled");
5368         if (mService != null) {
5369             try {
5370                 mService.setCameraDisabled(admin, disabled);
5371             } catch (RemoteException e) {
5372                 throw e.rethrowFromSystemServer();
5373             }
5374         }
5375     }
5376 
5377     /**
5378      * Determine whether or not the device's cameras have been disabled for this user,
5379      * either by the calling admin, if specified, or all admins.
5380      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
5381      * have disabled the camera
5382      */
getCameraDisabled(@ullable ComponentName admin)5383     public boolean getCameraDisabled(@Nullable ComponentName admin) {
5384         throwIfParentInstance("getCameraDisabled");
5385         return getCameraDisabled(admin, myUserId());
5386     }
5387 
5388     /** @hide per-user version */
5389     @UnsupportedAppUsage
getCameraDisabled(@ullable ComponentName admin, int userHandle)5390     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
5391         if (mService != null) {
5392             try {
5393                 return mService.getCameraDisabled(admin, userHandle);
5394             } catch (RemoteException e) {
5395                 throw e.rethrowFromSystemServer();
5396             }
5397         }
5398         return false;
5399     }
5400 
5401     /**
5402      * Called by a device owner to request a bugreport.
5403      * <p>
5404      * If the device contains secondary users or profiles, they must be affiliated with the device.
5405      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
5406      *
5407      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5408      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
5409      *         wasn't triggered because a previous bugreport operation is still active (either the
5410      *         bugreport is still running or waiting for the user to share or decline)
5411      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
5412      *         profile or secondary user that is not affiliated with the device.
5413      * @see #isAffiliatedUser
5414      */
requestBugreport(@onNull ComponentName admin)5415     public boolean requestBugreport(@NonNull ComponentName admin) {
5416         throwIfParentInstance("requestBugreport");
5417         if (mService != null) {
5418             try {
5419                 return mService.requestBugreport(admin);
5420             } catch (RemoteException e) {
5421                 throw e.rethrowFromSystemServer();
5422             }
5423         }
5424         return false;
5425     }
5426 
5427     /**
5428      * Determine whether or not creating a guest user has been disabled for the device
5429      *
5430      * @hide
5431      */
getGuestUserDisabled(@ullable ComponentName admin)5432     public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
5433         // Currently guest users can always be created if multi-user is enabled
5434         // TODO introduce a policy for guest user creation
5435         return false;
5436     }
5437 
5438     /**
5439      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
5440      * screen capture also prevents the content from being shown on display devices that do not have
5441      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
5442      * secure surfaces and secure displays.
5443      * <p>
5444      * The calling device admin must be a device or profile owner. If it is not, a security
5445      * exception will be thrown.
5446      * <p>
5447      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
5448      * assist requests for all activities of the relevant user.
5449      *
5450      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5451      * @param disabled Whether screen capture is disabled or not.
5452      * @throws SecurityException if {@code admin} is not a device or profile owner.
5453      */
setScreenCaptureDisabled(@onNull ComponentName admin, boolean disabled)5454     public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
5455         throwIfParentInstance("setScreenCaptureDisabled");
5456         if (mService != null) {
5457             try {
5458                 mService.setScreenCaptureDisabled(admin, disabled);
5459             } catch (RemoteException e) {
5460                 throw e.rethrowFromSystemServer();
5461             }
5462         }
5463     }
5464 
5465     /**
5466      * Determine whether or not screen capture has been disabled by the calling
5467      * admin, if specified, or all admins.
5468      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
5469      * have disabled screen capture.
5470      */
getScreenCaptureDisabled(@ullable ComponentName admin)5471     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
5472         throwIfParentInstance("getScreenCaptureDisabled");
5473         return getScreenCaptureDisabled(admin, myUserId());
5474     }
5475 
5476     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)5477     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
5478         if (mService != null) {
5479             try {
5480                 return mService.getScreenCaptureDisabled(admin, userHandle);
5481             } catch (RemoteException e) {
5482                 throw e.rethrowFromSystemServer();
5483             }
5484         }
5485         return false;
5486     }
5487 
5488     /**
5489      * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
5490      * higher, to set whether auto time is required. If auto time is required, no user will be able
5491      * set the date and time and network date and time will be used.
5492      * <p>
5493      * Note: if auto time is required the user can still manually set the time zone.
5494      * <p>
5495      * The calling device admin must be a device owner, or alternatively a profile owner from
5496      * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
5497      *
5498      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5499      * @param required Whether auto time is set required or not.
5500      * @throws SecurityException if {@code admin} is not a device owner.
5501      */
setAutoTimeRequired(@onNull ComponentName admin, boolean required)5502     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
5503         throwIfParentInstance("setAutoTimeRequired");
5504         if (mService != null) {
5505             try {
5506                 mService.setAutoTimeRequired(admin, required);
5507             } catch (RemoteException e) {
5508                 throw e.rethrowFromSystemServer();
5509             }
5510         }
5511     }
5512 
5513     /**
5514      * @return true if auto time is required.
5515      */
getAutoTimeRequired()5516     public boolean getAutoTimeRequired() {
5517         throwIfParentInstance("getAutoTimeRequired");
5518         if (mService != null) {
5519             try {
5520                 return mService.getAutoTimeRequired();
5521             } catch (RemoteException e) {
5522                 throw e.rethrowFromSystemServer();
5523             }
5524         }
5525         return false;
5526     }
5527 
5528     /**
5529      * Called by a device owner to set whether all users created on the device should be ephemeral.
5530      * <p>
5531      * The system user is exempt from this policy - it is never ephemeral.
5532      * <p>
5533      * The calling device admin must be the device owner. If it is not, a security exception will be
5534      * thrown.
5535      *
5536      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5537      * @param forceEphemeralUsers If true, all the existing users will be deleted and all
5538      *            subsequently created users will be ephemeral.
5539      * @throws SecurityException if {@code admin} is not a device owner.
5540      * @hide
5541      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)5542     public void setForceEphemeralUsers(
5543             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
5544         throwIfParentInstance("setForceEphemeralUsers");
5545         if (mService != null) {
5546             try {
5547                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
5548             } catch (RemoteException e) {
5549                 throw e.rethrowFromSystemServer();
5550             }
5551         }
5552     }
5553 
5554     /**
5555      * @return true if all users are created ephemeral.
5556      * @throws SecurityException if {@code admin} is not a device owner.
5557      * @hide
5558      */
getForceEphemeralUsers(@onNull ComponentName admin)5559     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
5560         throwIfParentInstance("getForceEphemeralUsers");
5561         if (mService != null) {
5562             try {
5563                 return mService.getForceEphemeralUsers(admin);
5564             } catch (RemoteException e) {
5565                 throw e.rethrowFromSystemServer();
5566             }
5567         }
5568         return false;
5569     }
5570 
5571     /**
5572      * Called by an application that is administering the device to disable keyguard customizations,
5573      * such as widgets. After setting this, keyguard features will be disabled according to the
5574      * provided feature list.
5575      * <p>
5576      * The calling device admin must have requested
5577      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
5578      * if it has not, a security exception will be thrown.
5579      * <p>
5580      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
5581      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
5582      * profile owner of a managed profile can set:
5583      * <ul>
5584      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
5585      * is no separate challenge set on the managed profile.
5586      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
5587      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
5588      * there is one, or the parent user otherwise.
5589      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
5590      * by applications in the managed profile.
5591      * </ul>
5592      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
5593      * {@link #KEYGUARD_DISABLE_FACE} and {@link #KEYGUARD_DISABLE_IRIS} can also be
5594      * set on the {@link DevicePolicyManager} instance returned by
5595      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5596      * profile.
5597      * <p>
5598      * Requests to disable other features on a managed profile will be ignored.
5599      * <p>
5600      * The admin can check which features have been disabled by calling
5601      * {@link #getKeyguardDisabledFeatures(ComponentName)}
5602      *
5603      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5604      * @param which The disabled features flag which can be either
5605      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
5606      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
5607      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
5608      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
5609      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
5610      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
5611      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
5612      *            {@link #KEYGUARD_DISABLE_FACE},
5613      *            {@link #KEYGUARD_DISABLE_IRIS}.
5614      * @throws SecurityException if {@code admin} is not an active administrator or does not user
5615      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
5616      */
setKeyguardDisabledFeatures(@onNull ComponentName admin, int which)5617     public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
5618         if (mService != null) {
5619             try {
5620                 mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
5621             } catch (RemoteException e) {
5622                 throw e.rethrowFromSystemServer();
5623             }
5624         }
5625     }
5626 
5627     /**
5628      * Determine whether or not features have been disabled in keyguard either by the calling
5629      * admin, if specified, or all admins that set restrictions on this user and its participating
5630      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
5631      *
5632      * <p>This method can be called on the {@link DevicePolicyManager} instance
5633      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5634      * restrictions on the parent profile.
5635      *
5636      * @param admin The name of the admin component to check, or {@code null} to check whether any
5637      * admins have disabled features in keyguard.
5638      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
5639      * for a list.
5640      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)5641     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
5642         return getKeyguardDisabledFeatures(admin, myUserId());
5643     }
5644 
5645     /** @hide per-user version */
5646     @UnsupportedAppUsage
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)5647     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
5648         if (mService != null) {
5649             try {
5650                 return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
5651             } catch (RemoteException e) {
5652                 throw e.rethrowFromSystemServer();
5653             }
5654         }
5655         return KEYGUARD_DISABLE_FEATURES_NONE;
5656     }
5657 
5658     /**
5659      * @hide
5660      */
5661     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)5662     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
5663             int userHandle) {
5664         if (mService != null) {
5665             try {
5666                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
5667             } catch (RemoteException e) {
5668                 throw e.rethrowFromSystemServer();
5669             }
5670         }
5671     }
5672 
5673     /**
5674      * @hide
5675      */
5676     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)5677     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
5678         setActiveAdmin(policyReceiver, refreshing, myUserId());
5679     }
5680 
5681     /**
5682      * @hide
5683      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)5684     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
5685         if (mService != null) {
5686             try {
5687                 mService.getRemoveWarning(admin, result, myUserId());
5688             } catch (RemoteException e) {
5689                 throw e.rethrowFromSystemServer();
5690             }
5691         }
5692     }
5693 
5694     /**
5695      * @hide
5696      */
5697     @UnsupportedAppUsage
5698     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setActivePasswordState(PasswordMetrics metrics, int userHandle)5699     public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
5700         if (mService != null) {
5701             try {
5702                 mService.setActivePasswordState(metrics, userHandle);
5703             } catch (RemoteException e) {
5704                 throw e.rethrowFromSystemServer();
5705             }
5706         }
5707     }
5708 
5709     /**
5710      * @hide
5711      */
5712     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportPasswordChanged(@serIdInt int userId)5713     public void reportPasswordChanged(@UserIdInt int userId) {
5714         if (mService != null) {
5715             try {
5716                 mService.reportPasswordChanged(userId);
5717             } catch (RemoteException e) {
5718                 throw e.rethrowFromSystemServer();
5719             }
5720         }
5721     }
5722 
5723     /**
5724      * @hide
5725      */
5726     @UnsupportedAppUsage
5727     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedPasswordAttempt(int userHandle)5728     public void reportFailedPasswordAttempt(int userHandle) {
5729         if (mService != null) {
5730             try {
5731                 mService.reportFailedPasswordAttempt(userHandle);
5732             } catch (RemoteException e) {
5733                 throw e.rethrowFromSystemServer();
5734             }
5735         }
5736     }
5737 
5738     /**
5739      * @hide
5740      */
5741     @UnsupportedAppUsage
5742     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulPasswordAttempt(int userHandle)5743     public void reportSuccessfulPasswordAttempt(int userHandle) {
5744         if (mService != null) {
5745             try {
5746                 mService.reportSuccessfulPasswordAttempt(userHandle);
5747             } catch (RemoteException e) {
5748                 throw e.rethrowFromSystemServer();
5749             }
5750         }
5751     }
5752 
5753     /**
5754      * @hide
5755      */
5756     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedBiometricAttempt(int userHandle)5757     public void reportFailedBiometricAttempt(int userHandle) {
5758         if (mService != null) {
5759             try {
5760                 mService.reportFailedBiometricAttempt(userHandle);
5761             } catch (RemoteException e) {
5762                 throw e.rethrowFromSystemServer();
5763             }
5764         }
5765     }
5766 
5767     /**
5768      * @hide
5769      */
5770     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulBiometricAttempt(int userHandle)5771     public void reportSuccessfulBiometricAttempt(int userHandle) {
5772         if (mService != null) {
5773             try {
5774                 mService.reportSuccessfulBiometricAttempt(userHandle);
5775             } catch (RemoteException e) {
5776                 throw e.rethrowFromSystemServer();
5777             }
5778         }
5779     }
5780 
5781     /**
5782      * Should be called when keyguard has been dismissed.
5783      * @hide
5784      */
reportKeyguardDismissed(int userHandle)5785     public void reportKeyguardDismissed(int userHandle) {
5786         if (mService != null) {
5787             try {
5788                 mService.reportKeyguardDismissed(userHandle);
5789             } catch (RemoteException e) {
5790                 throw e.rethrowFromSystemServer();
5791             }
5792         }
5793     }
5794 
5795     /**
5796      * Should be called when keyguard view has been shown to the user.
5797      * @hide
5798      */
reportKeyguardSecured(int userHandle)5799     public void reportKeyguardSecured(int userHandle) {
5800         if (mService != null) {
5801             try {
5802                 mService.reportKeyguardSecured(userHandle);
5803             } catch (RemoteException e) {
5804                 throw e.rethrowFromSystemServer();
5805             }
5806         }
5807     }
5808 
5809     /**
5810      * @hide
5811      * Sets the given package as the device owner.
5812      * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
5813      * @param who the component name to be registered as device owner.
5814      * @return whether the package was successfully registered as the device owner.
5815      * @throws IllegalArgumentException if the package name is null or invalid
5816      * @throws IllegalStateException If the preconditions mentioned are not met.
5817      */
setDeviceOwner(ComponentName who)5818     public boolean setDeviceOwner(ComponentName who) {
5819         return setDeviceOwner(who, null);
5820     }
5821 
5822     /**
5823      * @hide
5824      */
setDeviceOwner(ComponentName who, int userId)5825     public boolean setDeviceOwner(ComponentName who, int userId)  {
5826         return setDeviceOwner(who, null, userId);
5827     }
5828 
5829     /**
5830      * @hide
5831      */
setDeviceOwner(ComponentName who, String ownerName)5832     public boolean setDeviceOwner(ComponentName who, String ownerName) {
5833         return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
5834     }
5835 
5836     /**
5837      * @hide
5838      * Sets the given package as the device owner. The package must already be installed. There
5839      * must not already be a device owner.
5840      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
5841      * this method.
5842      * Calling this after the setup phase of the primary user has completed is allowed only if
5843      * the caller is the shell uid, and there are no additional users and no accounts.
5844      * @param who the component name to be registered as device owner.
5845      * @param ownerName the human readable name of the institution that owns this device.
5846      * @param userId ID of the user on which the device owner runs.
5847      * @return whether the package was successfully registered as the device owner.
5848      * @throws IllegalArgumentException if the package name is null or invalid
5849      * @throws IllegalStateException If the preconditions mentioned are not met.
5850      */
setDeviceOwner(ComponentName who, String ownerName, int userId)5851     public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
5852             throws IllegalArgumentException, IllegalStateException {
5853         if (mService != null) {
5854             try {
5855                 return mService.setDeviceOwner(who, ownerName, userId);
5856             } catch (RemoteException re) {
5857                 throw re.rethrowFromSystemServer();
5858             }
5859         }
5860         return false;
5861     }
5862 
5863     /**
5864      * Used to determine if a particular package has been registered as a Device Owner app.
5865      * A device owner app is a special device admin that cannot be deactivated by the user, once
5866      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
5867      * package is currently registered as the device owner app, pass in the package name from
5868      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
5869      * admin apps that want to check whether they are also registered as the device owner app. The
5870      * exact mechanism by which a device admin app is registered as a device owner app is defined by
5871      * the setup process.
5872      * @param packageName the package name of the app, to compare with the registered device owner
5873      * app, if any.
5874      * @return whether or not the package is registered as the device owner app.
5875      */
isDeviceOwnerApp(String packageName)5876     public boolean isDeviceOwnerApp(String packageName) {
5877         throwIfParentInstance("isDeviceOwnerApp");
5878         return isDeviceOwnerAppOnCallingUser(packageName);
5879     }
5880 
5881     /**
5882      * @return true if a package is registered as device owner, only when it's running on the
5883      * calling user.
5884      *
5885      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
5886      * @hide
5887      */
isDeviceOwnerAppOnCallingUser(String packageName)5888     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
5889         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
5890     }
5891 
5892     /**
5893      * @return true if a package is registered as device owner, even if it's running on a different
5894      * user.
5895      *
5896      * <p>Requires the MANAGE_USERS permission.
5897      *
5898      * @hide
5899      */
isDeviceOwnerAppOnAnyUser(String packageName)5900     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
5901         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
5902     }
5903 
5904     /**
5905      * @return device owner component name, only when it's running on the calling user.
5906      *
5907      * @hide
5908      */
getDeviceOwnerComponentOnCallingUser()5909     public ComponentName getDeviceOwnerComponentOnCallingUser() {
5910         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
5911     }
5912 
5913     /**
5914      * @return device owner component name, even if it's running on a different user.
5915      *
5916      * @hide
5917      */
5918     @SystemApi
5919     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerComponentOnAnyUser()5920     public ComponentName getDeviceOwnerComponentOnAnyUser() {
5921         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
5922     }
5923 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)5924     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
5925         if (packageName == null) {
5926             return false;
5927         }
5928         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
5929         if (deviceOwner == null) {
5930             return false;
5931         }
5932         return packageName.equals(deviceOwner.getPackageName());
5933     }
5934 
getDeviceOwnerComponentInner(boolean callingUserOnly)5935     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
5936         if (mService != null) {
5937             try {
5938                 return mService.getDeviceOwnerComponent(callingUserOnly);
5939             } catch (RemoteException re) {
5940                 throw re.rethrowFromSystemServer();
5941             }
5942         }
5943         return null;
5944     }
5945 
5946     /**
5947      * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
5948      *
5949      * @hide
5950      */
5951     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5952     @SystemApi
getDeviceOwnerUser()5953     public @Nullable UserHandle getDeviceOwnerUser() {
5954         if (mService != null) {
5955             try {
5956                 int userId = mService.getDeviceOwnerUserId();
5957 
5958                 if (userId != UserHandle.USER_NULL) {
5959                     return UserHandle.of(userId);
5960                 }
5961             } catch (RemoteException re) {
5962                 throw re.rethrowFromSystemServer();
5963             }
5964         }
5965         return null;
5966     }
5967 
5968     /**
5969      * @hide
5970      */
getDeviceOwnerUserId()5971     public int getDeviceOwnerUserId() {
5972         if (mService != null) {
5973             try {
5974                 return mService.getDeviceOwnerUserId();
5975             } catch (RemoteException re) {
5976                 throw re.rethrowFromSystemServer();
5977             }
5978         }
5979         return UserHandle.USER_NULL;
5980     }
5981 
5982     /**
5983      * Clears the current device owner. The caller must be the device owner. This function should be
5984      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
5985      * a part of device setup, before it completes.
5986      * <p>
5987      * While some policies previously set by the device owner will be cleared by this method, it is
5988      * a best-effort process and some other policies will still remain in place after the device
5989      * owner is cleared.
5990      *
5991      * @param packageName The package name of the device owner.
5992      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
5993      *             does not own the current device owner component.
5994      *
5995      * @deprecated This method is expected to be used for testing purposes only. The device owner
5996      * will lose control of the device and its data after calling it. In order to protect any
5997      * sensitive data that remains on the device, it is advised that the device owner factory resets
5998      * the device instead of calling this method. See {@link #wipeData(int)}.
5999      */
6000     @Deprecated
clearDeviceOwnerApp(String packageName)6001     public void clearDeviceOwnerApp(String packageName) {
6002         throwIfParentInstance("clearDeviceOwnerApp");
6003         if (mService != null) {
6004             try {
6005                 mService.clearDeviceOwner(packageName);
6006             } catch (RemoteException re) {
6007                 throw re.rethrowFromSystemServer();
6008             }
6009         }
6010     }
6011 
6012     /**
6013      * Returns the device owner package name, only if it's running on the calling user.
6014      *
6015      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
6016      *
6017      * @hide
6018      */
6019     @SystemApi
6020     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()6021     public @Nullable String getDeviceOwner() {
6022         throwIfParentInstance("getDeviceOwner");
6023         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
6024         return name != null ? name.getPackageName() : null;
6025     }
6026 
6027     /**
6028      * Called by the system to find out whether the device is managed by a Device Owner.
6029      *
6030      * @return whether the device is managed by a Device Owner.
6031      * @throws SecurityException if the caller is not the device owner, does not hold the
6032      *         MANAGE_USERS permission and is not the system.
6033      *
6034      * @hide
6035      */
6036     @SystemApi
6037     @TestApi
6038     @SuppressLint("Doclava125")
isDeviceManaged()6039     public boolean isDeviceManaged() {
6040         try {
6041             return mService.hasDeviceOwner();
6042         } catch (RemoteException re) {
6043             throw re.rethrowFromSystemServer();
6044         }
6045     }
6046 
6047     /**
6048      * Returns the device owner name.  Note this method *will* return the device owner
6049      * name when it's running on a different user.
6050      *
6051      * @hide
6052      */
6053     @SystemApi
6054     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerNameOnAnyUser()6055     public String getDeviceOwnerNameOnAnyUser() {
6056         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
6057         if (mService != null) {
6058             try {
6059                 return mService.getDeviceOwnerName();
6060             } catch (RemoteException re) {
6061                 throw re.rethrowFromSystemServer();
6062             }
6063         }
6064         return null;
6065     }
6066 
6067     /**
6068      * @hide
6069      * @deprecated Do not use
6070      * @removed
6071      */
6072     @Deprecated
6073     @SystemApi
6074     @SuppressLint("Doclava125")
getDeviceInitializerApp()6075     public @Nullable String getDeviceInitializerApp() {
6076         return null;
6077     }
6078 
6079     /**
6080      * @hide
6081      * @deprecated Do not use
6082      * @removed
6083      */
6084     @Deprecated
6085     @SystemApi
6086     @SuppressLint("Doclava125")
getDeviceInitializerComponent()6087     public @Nullable ComponentName getDeviceInitializerComponent() {
6088         return null;
6089     }
6090 
6091     /**
6092      * @hide
6093      * @deprecated Use #ACTION_SET_PROFILE_OWNER
6094      * Sets the given component as an active admin and registers the package as the profile
6095      * owner for this user. The package must already be installed and there shouldn't be
6096      * an existing profile owner registered for this user. Also, this method must be called
6097      * before the user setup has been completed.
6098      * <p>
6099      * This method can only be called by system apps that hold MANAGE_USERS permission and
6100      * MANAGE_DEVICE_ADMINS permission.
6101      * @param admin The component to register as an active admin and profile owner.
6102      * @param ownerName The user-visible name of the entity that is managing this user.
6103      * @return whether the admin was successfully registered as the profile owner.
6104      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
6105      *         the user has already been set up.
6106      */
6107     @Deprecated
6108     @SystemApi
6109     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName)6110     public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
6111             throws IllegalArgumentException {
6112         throwIfParentInstance("setActiveProfileOwner");
6113         if (mService != null) {
6114             try {
6115                 final int myUserId = myUserId();
6116                 mService.setActiveAdmin(admin, false, myUserId);
6117                 return mService.setProfileOwner(admin, ownerName, myUserId);
6118             } catch (RemoteException re) {
6119                 throw re.rethrowFromSystemServer();
6120             }
6121         }
6122         return false;
6123     }
6124 
6125     /**
6126      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
6127      * a SecurityException will be thrown. This method is not available to managed profile owners.
6128      * <p>
6129      * While some policies previously set by the profile owner will be cleared by this method, it is
6130      * a best-effort process and some other policies will still remain in place after the profile
6131      * owner is cleared.
6132      *
6133      * @param admin The component to remove as the profile owner.
6134      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
6135      * being called from a managed profile.
6136      *
6137      * @deprecated This method is expected to be used for testing purposes only. The profile owner
6138      * will lose control of the user and its data after calling it. In order to protect any
6139      * sensitive data that remains on this user, it is advised that the profile owner deletes it
6140      * instead of calling this method. See {@link #wipeData(int)}.
6141      */
6142     @Deprecated
clearProfileOwner(@onNull ComponentName admin)6143     public void clearProfileOwner(@NonNull ComponentName admin) {
6144         throwIfParentInstance("clearProfileOwner");
6145         if (mService != null) {
6146             try {
6147                 mService.clearProfileOwner(admin);
6148             } catch (RemoteException re) {
6149                 throw re.rethrowFromSystemServer();
6150             }
6151         }
6152     }
6153 
6154     /**
6155      * @hide
6156      * Checks whether the user was already setup.
6157      */
hasUserSetupCompleted()6158     public boolean hasUserSetupCompleted() {
6159         if (mService != null) {
6160             try {
6161                 return mService.hasUserSetupCompleted();
6162             } catch (RemoteException re) {
6163                 throw re.rethrowFromSystemServer();
6164             }
6165         }
6166         return true;
6167     }
6168 
6169     /**
6170      * @hide
6171      * Sets the given component as the profile owner of the given user profile. The package must
6172      * already be installed. There must not already be a profile owner for this user.
6173      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
6174      * this method.
6175      * Calling this after the setup phase of the specified user has completed is allowed only if:
6176      * - the caller is SYSTEM_UID.
6177      * - or the caller is the shell uid, and there are no accounts on the specified user.
6178      * @param admin the component name to be registered as profile owner.
6179      * @param ownerName the human readable name of the organisation associated with this DPM.
6180      * @param userHandle the userId to set the profile owner for.
6181      * @return whether the component was successfully registered as the profile owner.
6182      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
6183      * preconditions mentioned are not met.
6184      */
setProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName, int userHandle)6185     public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
6186             int userHandle) throws IllegalArgumentException {
6187         if (mService != null) {
6188             try {
6189                 if (ownerName == null) {
6190                     ownerName = "";
6191                 }
6192                 return mService.setProfileOwner(admin, ownerName, userHandle);
6193             } catch (RemoteException re) {
6194                 throw re.rethrowFromSystemServer();
6195             }
6196         }
6197         return false;
6198     }
6199 
6200     /**
6201      * Sets the device owner information to be shown on the lock screen.
6202      * <p>
6203      * If the device owner information is {@code null} or empty then the device owner info is
6204      * cleared and the user owner info is shown on the lock screen if it is set.
6205      * <p>
6206      * If the device owner information contains only whitespaces then the message on the lock screen
6207      * will be blank and the user will not be allowed to change it.
6208      * <p>
6209      * If the device owner information needs to be localized, it is the responsibility of the
6210      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
6211      * and set a new version of this string accordingly.
6212      *
6213      * @param admin The name of the admin component to check.
6214      * @param info Device owner information which will be displayed instead of the user owner info.
6215      * @throws SecurityException if {@code admin} is not a device owner.
6216      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)6217     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
6218         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
6219         if (mService != null) {
6220             try {
6221                 mService.setDeviceOwnerLockScreenInfo(admin, info);
6222             } catch (RemoteException re) {
6223                 throw re.rethrowFromSystemServer();
6224             }
6225         }
6226     }
6227 
6228     /**
6229      * @return The device owner information. If it is not set returns {@code null}.
6230      */
getDeviceOwnerLockScreenInfo()6231     public CharSequence getDeviceOwnerLockScreenInfo() {
6232         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
6233         if (mService != null) {
6234             try {
6235                 return mService.getDeviceOwnerLockScreenInfo();
6236             } catch (RemoteException re) {
6237                 throw re.rethrowFromSystemServer();
6238             }
6239         }
6240         return null;
6241     }
6242 
6243     /**
6244      * Called by device or profile owners to suspend packages for this user. This function can be
6245      * called by a device owner, profile owner, or by a delegate given the
6246      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
6247      * <p>
6248      * A suspended package will not be able to start activities. Its notifications will be hidden,
6249      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
6250      * device.
6251      * <p>
6252      * The package must already be installed. If the package is uninstalled while suspended the
6253      * package will no longer be suspended. The admin can block this by using
6254      * {@link #setUninstallBlocked}.
6255      *
6256      * @param admin The name of the admin component to check, or {@code null} if the caller is a
6257      *            package access delegate.
6258      * @param packageNames The package names to suspend or unsuspend.
6259      * @param suspended If set to {@code true} than the packages will be suspended, if set to
6260      *            {@code false} the packages will be unsuspended.
6261      * @return an array of package names for which the suspended status is not set as requested in
6262      *         this method.
6263      * @throws SecurityException if {@code admin} is not a device or profile owner.
6264      * @see #setDelegatedScopes
6265      * @see #DELEGATION_PACKAGE_ACCESS
6266      */
setPackagesSuspended(@onNull ComponentName admin, @NonNull String[] packageNames, boolean suspended)6267     public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
6268             @NonNull String[] packageNames, boolean suspended) {
6269         throwIfParentInstance("setPackagesSuspended");
6270         if (mService != null) {
6271             try {
6272                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
6273                         suspended);
6274             } catch (RemoteException re) {
6275                 throw re.rethrowFromSystemServer();
6276             }
6277         }
6278         return packageNames;
6279     }
6280 
6281     /**
6282      * Determine if a package is suspended. This function can be called by a device owner, profile
6283      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6284      * {@link #setDelegatedScopes}.
6285      *
6286      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6287      *            {@code null} if the caller is a package access delegate.
6288      * @param packageName The name of the package to retrieve the suspended status of.
6289      * @return {@code true} if the package is suspended or {@code false} if the package is not
6290      *         suspended, could not be found or an error occurred.
6291      * @throws SecurityException if {@code admin} is not a device or profile owner.
6292      * @throws NameNotFoundException if the package could not be found.
6293      * @see #setDelegatedScopes
6294      * @see #DELEGATION_PACKAGE_ACCESS
6295      */
isPackageSuspended(@onNull ComponentName admin, String packageName)6296     public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
6297             throws NameNotFoundException {
6298         throwIfParentInstance("isPackageSuspended");
6299         if (mService != null) {
6300             try {
6301                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
6302             } catch (RemoteException e) {
6303                 throw e.rethrowFromSystemServer();
6304             } catch (IllegalArgumentException ex) {
6305                 throw new NameNotFoundException(packageName);
6306             }
6307         }
6308         return false;
6309     }
6310 
6311     /**
6312      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
6313      * be used. Only the profile owner can call this.
6314      *
6315      * @see #isProfileOwnerApp
6316      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6317      * @throws SecurityException if {@code admin} is not a profile owner.
6318      */
setProfileEnabled(@onNull ComponentName admin)6319     public void setProfileEnabled(@NonNull ComponentName admin) {
6320         throwIfParentInstance("setProfileEnabled");
6321         if (mService != null) {
6322             try {
6323                 mService.setProfileEnabled(admin);
6324             } catch (RemoteException e) {
6325                 throw e.rethrowFromSystemServer();
6326             }
6327         }
6328     }
6329 
6330     /**
6331      * Sets the name of the profile. In the device owner case it sets the name of the user which it
6332      * is called from. Only a profile owner or device owner can call this. If this is never called
6333      * by the profile or device owner, the name will be set to default values.
6334      *
6335      * @see #isProfileOwnerApp
6336      * @see #isDeviceOwnerApp
6337      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
6338      * @param profileName The name of the profile.
6339      * @throws SecurityException if {@code admin} is not a device or profile owner.
6340      */
setProfileName(@onNull ComponentName admin, String profileName)6341     public void setProfileName(@NonNull ComponentName admin, String profileName) {
6342         throwIfParentInstance("setProfileName");
6343         if (mService != null) {
6344             try {
6345                 mService.setProfileName(admin, profileName);
6346             } catch (RemoteException e) {
6347                 throw e.rethrowFromSystemServer();
6348             }
6349         }
6350     }
6351 
6352     /**
6353      * Used to determine if a particular package is registered as the profile owner for the
6354      * user. A profile owner is a special device admin that has additional privileges
6355      * within the profile.
6356      *
6357      * @param packageName The package name of the app to compare with the registered profile owner.
6358      * @return Whether or not the package is registered as the profile owner.
6359      */
isProfileOwnerApp(String packageName)6360     public boolean isProfileOwnerApp(String packageName) {
6361         throwIfParentInstance("isProfileOwnerApp");
6362         if (mService != null) {
6363             try {
6364                 ComponentName profileOwner = mService.getProfileOwner(myUserId());
6365                 return profileOwner != null
6366                         && profileOwner.getPackageName().equals(packageName);
6367             } catch (RemoteException re) {
6368                 throw re.rethrowFromSystemServer();
6369             }
6370         }
6371         return false;
6372     }
6373 
6374     /**
6375      * @hide
6376      * @return the packageName of the owner of the given user profile or {@code null} if no profile
6377      * owner has been set for that user.
6378      * @throws IllegalArgumentException if the userId is invalid.
6379      */
6380     @SystemApi
getProfileOwner()6381     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
6382         throwIfParentInstance("getProfileOwner");
6383         return getProfileOwnerAsUser(mContext.getUserId());
6384     }
6385 
6386     /**
6387      * @see #getProfileOwner()
6388      * @hide
6389      */
6390     @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
6391             conditional = true)
getProfileOwnerAsUser(@onNull UserHandle user)6392     public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
6393         if (mService != null) {
6394             try {
6395                 return mService.getProfileOwnerAsUser(user.getIdentifier());
6396             } catch (RemoteException re) {
6397                 throw re.rethrowFromSystemServer();
6398             }
6399         }
6400         return null;
6401     }
6402 
6403     /**
6404      * @hide
6405      */
6406     @UnsupportedAppUsage
getProfileOwnerAsUser(final int userId)6407     public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
6408         if (mService != null) {
6409             try {
6410                 return mService.getProfileOwnerAsUser(userId);
6411             } catch (RemoteException re) {
6412                 throw re.rethrowFromSystemServer();
6413             }
6414         }
6415         return null;
6416     }
6417 
6418     /**
6419      * @hide
6420      * @return the human readable name of the organisation associated with this DPM or {@code null}
6421      *         if one is not set.
6422      * @throws IllegalArgumentException if the userId is invalid.
6423      */
getProfileOwnerName()6424     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
6425         if (mService != null) {
6426             try {
6427                 return mService.getProfileOwnerName(mContext.getUserId());
6428             } catch (RemoteException re) {
6429                 throw re.rethrowFromSystemServer();
6430             }
6431         }
6432         return null;
6433     }
6434 
6435     /**
6436      * @hide
6437      * @param userId The user for whom to fetch the profile owner name, if any.
6438      * @return the human readable name of the organisation associated with this profile owner or
6439      *         null if one is not set.
6440      * @throws IllegalArgumentException if the userId is invalid.
6441      */
6442     @SystemApi
6443     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getProfileOwnerNameAsUser(int userId)6444     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
6445         throwIfParentInstance("getProfileOwnerNameAsUser");
6446         if (mService != null) {
6447             try {
6448                 return mService.getProfileOwnerName(userId);
6449             } catch (RemoteException re) {
6450                 throw re.rethrowFromSystemServer();
6451             }
6452         }
6453         return null;
6454     }
6455 
6456     /**
6457      * Returns whether the specified package can read the device identifiers.
6458      *
6459      * @param packageName The package name of the app to check for device identifier access.
6460      * @param pid The process id of the package to be checked.
6461      * @param uid The uid of the package to be checked.
6462      * @return whether the package can read the device identifiers.
6463      *
6464      * @hide
6465      */
checkDeviceIdentifierAccess(String packageName, int pid, int uid)6466     public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) {
6467         throwIfParentInstance("checkDeviceIdentifierAccess");
6468         if (packageName == null) {
6469             return false;
6470         }
6471         if (mService != null) {
6472             try {
6473                 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
6474             } catch (RemoteException re) {
6475                 throw re.rethrowFromSystemServer();
6476             }
6477         }
6478         return false;
6479     }
6480 
6481     /**
6482      * Called by a profile owner or device owner to set a default activity that the system selects
6483      * to handle intents that match the given {@link IntentFilter}. This activity will remain the
6484      * default intent handler even if the set of potential event handlers for the intent filter
6485      * changes and if the intent preferences are reset.
6486      * <p>
6487      * Note that the caller should still declare the activity in the manifest, the API just sets
6488      * the activity to be the default one to handle the given intent filter.
6489      * <p>
6490      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
6491      * When the activity is (re)installed, it is automatically reset as default intent handler for
6492      * the filter.
6493      * <p>
6494      * The calling device admin must be a profile owner or device owner. If it is not, a security
6495      * exception will be thrown.
6496      *
6497      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6498      * @param filter The IntentFilter for which a default handler is added.
6499      * @param activity The Activity that is added as default intent handler.
6500      * @throws SecurityException if {@code admin} is not a device or profile owner.
6501      */
addPersistentPreferredActivity(@onNull ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)6502     public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
6503             @NonNull ComponentName activity) {
6504         throwIfParentInstance("addPersistentPreferredActivity");
6505         if (mService != null) {
6506             try {
6507                 mService.addPersistentPreferredActivity(admin, filter, activity);
6508             } catch (RemoteException e) {
6509                 throw e.rethrowFromSystemServer();
6510             }
6511         }
6512     }
6513 
6514     /**
6515      * Called by a profile owner or device owner to remove all persistent intent handler preferences
6516      * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
6517      * <p>
6518      * The calling device admin must be a profile owner. If it is not, a security exception will be
6519      * thrown.
6520      *
6521      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6522      * @param packageName The name of the package for which preferences are removed.
6523      * @throws SecurityException if {@code admin} is not a device or profile owner.
6524      */
clearPackagePersistentPreferredActivities(@onNull ComponentName admin, String packageName)6525     public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
6526             String packageName) {
6527         throwIfParentInstance("clearPackagePersistentPreferredActivities");
6528         if (mService != null) {
6529             try {
6530                 mService.clearPackagePersistentPreferredActivities(admin, packageName);
6531             } catch (RemoteException e) {
6532                 throw e.rethrowFromSystemServer();
6533             }
6534         }
6535     }
6536 
6537     /**
6538      * Called by a device owner to set the default SMS application.
6539      * <p>
6540      * The calling device admin must be a device 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 to set as the default SMS application.
6545      * @throws SecurityException if {@code admin} is not a device owner.
6546      */
setDefaultSmsApplication(@onNull ComponentName admin, @NonNull String packageName)6547     public void setDefaultSmsApplication(@NonNull ComponentName admin,
6548             @NonNull String packageName) {
6549         throwIfParentInstance("setDefaultSmsApplication");
6550         if (mService != null) {
6551             try {
6552                 mService.setDefaultSmsApplication(admin, packageName);
6553             } catch (RemoteException e) {
6554                 throw e.rethrowFromSystemServer();
6555             }
6556         }
6557     }
6558 
6559     /**
6560      * Called by a profile owner or device owner to grant permission to a package to manage
6561      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
6562      * {@link #getApplicationRestrictions}.
6563      * <p>
6564      * This permission is persistent until it is later cleared by calling this method with a
6565      * {@code null} value or uninstalling the managing package.
6566      * <p>
6567      * The supplied application restriction managing package must be installed when calling this
6568      * API, otherwise an {@link NameNotFoundException} will be thrown.
6569      *
6570      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6571      * @param packageName The package name which will be given access to application restrictions
6572      *            APIs. If {@code null} is given the current package will be cleared.
6573      * @throws SecurityException if {@code admin} is not a device or profile owner.
6574      * @throws NameNotFoundException if {@code packageName} is not found
6575      *
6576      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
6577      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
6578      */
6579     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)6580     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
6581             @Nullable String packageName) throws NameNotFoundException {
6582         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
6583         if (mService != null) {
6584             try {
6585                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
6586                     throw new NameNotFoundException(packageName);
6587                 }
6588             } catch (RemoteException e) {
6589                 throw e.rethrowFromSystemServer();
6590             }
6591         }
6592     }
6593 
6594     /**
6595      * Called by a profile owner or device owner to retrieve the application restrictions managing
6596      * package for the current user, or {@code null} if none is set. If there are multiple
6597      * delegates this function will return one of them.
6598      *
6599      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6600      * @return The package name allowed to manage application restrictions on the current user, or
6601      *         {@code null} if none is set.
6602      * @throws SecurityException if {@code admin} is not a device or profile owner.
6603      *
6604      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
6605      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
6606      */
6607     @Deprecated
6608     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)6609     public String getApplicationRestrictionsManagingPackage(
6610             @NonNull ComponentName admin) {
6611         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
6612         if (mService != null) {
6613             try {
6614                 return mService.getApplicationRestrictionsManagingPackage(admin);
6615             } catch (RemoteException e) {
6616                 throw e.rethrowFromSystemServer();
6617             }
6618         }
6619         return null;
6620     }
6621 
6622     /**
6623      * Called by any application to find out whether it has been granted permission via
6624      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
6625      * for the calling user.
6626      *
6627      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
6628      * that method.
6629      *
6630      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
6631      * instead.
6632      */
6633     @Deprecated
isCallerApplicationRestrictionsManagingPackage()6634     public boolean isCallerApplicationRestrictionsManagingPackage() {
6635         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
6636         if (mService != null) {
6637             try {
6638                 return mService.isCallerApplicationRestrictionsManagingPackage(
6639                         mContext.getPackageName());
6640             } catch (RemoteException e) {
6641                 throw e.rethrowFromSystemServer();
6642             }
6643         }
6644         return false;
6645     }
6646 
6647     /**
6648      * Sets the application restrictions for a given target application running in the calling user.
6649      * <p>
6650      * The caller must be a profile or device owner on that user, or the package allowed to manage
6651      * application restrictions via {@link #setDelegatedScopes} with the
6652      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
6653      * <p>
6654      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
6655      * <ul>
6656      * <li>{@code boolean}
6657      * <li>{@code int}
6658      * <li>{@code String} or {@code String[]}
6659      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
6660      * </ul>
6661      * <p>
6662      * If the restrictions are not available yet, but may be applied in the near future, the caller
6663      * can notify the target application of that by adding
6664      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
6665      * <p>
6666      * The application restrictions are only made visible to the target application via
6667      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
6668      * owner, and the application restrictions managing package via
6669      * {@link #getApplicationRestrictions}.
6670      *
6671      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
6672      *
6673      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6674      *            {@code null} if called by the application restrictions managing package.
6675      * @param packageName The name of the package to update restricted settings for.
6676      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
6677      *            set of active restrictions.
6678      * @throws SecurityException if {@code admin} is not a device or profile owner.
6679      * @see #setDelegatedScopes
6680      * @see #DELEGATION_APP_RESTRICTIONS
6681      * @see UserManager#KEY_RESTRICTIONS_PENDING
6682      */
6683     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)6684     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
6685             Bundle settings) {
6686         throwIfParentInstance("setApplicationRestrictions");
6687         if (mService != null) {
6688             try {
6689                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
6690                         settings);
6691             } catch (RemoteException e) {
6692                 throw e.rethrowFromSystemServer();
6693             }
6694         }
6695     }
6696 
6697     /**
6698      * Sets a list of configuration features to enable for a trust agent component. This is meant to
6699      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
6700      * agents but those enabled by this function call. If flag
6701      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
6702      * <p>
6703      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
6704      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
6705      * configuration as set by this function call. In particular: if any admin sets
6706      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
6707      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
6708      * will receive the list of configurations from all admins who set
6709      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
6710      * behavior. The exact meaning of aggregation is trust-agent-specific.
6711      * <p>
6712      * The calling device admin must have requested
6713      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
6714      * if not, a security exception will be thrown.
6715      * <p>
6716      * This method can be called on the {@link DevicePolicyManager} instance returned by
6717      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
6718      * the parent profile.
6719      * <p>
6720      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
6721      * this method has no effect - no trust agent configuration will be set.
6722      *
6723      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6724      * @param target Component name of the agent to be configured.
6725      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
6726      *        documentation of the specific trust agent to determine the interpretation of this
6727      *        bundle.
6728      * @throws SecurityException if {@code admin} is not an active administrator or does not use
6729      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
6730      */
6731     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setTrustAgentConfiguration(@onNull ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)6732     public void setTrustAgentConfiguration(@NonNull ComponentName admin,
6733             @NonNull ComponentName target, PersistableBundle configuration) {
6734         if (mService != null) {
6735             try {
6736                 mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
6737             } catch (RemoteException e) {
6738                 throw e.rethrowFromSystemServer();
6739             }
6740         }
6741     }
6742 
6743     /**
6744      * Gets configuration for the given trust agent based on aggregating all calls to
6745      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
6746      * all device admins.
6747      * <p>
6748      * This method can be called on the {@link DevicePolicyManager} instance returned by
6749      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
6750      * on the parent profile.
6751      * <p>
6752      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
6753      * always returned.
6754      *
6755      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
6756      * this function returns a list of configurations for all admins that declare
6757      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
6758      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
6759      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
6760      * for this {@param agent} or calls it with a null configuration, null is returned.
6761      * @param agent Which component to get enabled features for.
6762      * @return configuration for the given trust agent.
6763      */
6764     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)6765     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
6766             @Nullable ComponentName admin, @NonNull ComponentName agent) {
6767         return getTrustAgentConfiguration(admin, agent, myUserId());
6768     }
6769 
6770     /** @hide per-user version */
6771     @UnsupportedAppUsage
6772     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)6773     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
6774             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
6775         if (mService != null) {
6776             try {
6777                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
6778                         mParentInstance);
6779             } catch (RemoteException e) {
6780                 throw e.rethrowFromSystemServer();
6781             }
6782         }
6783         return new ArrayList<PersistableBundle>(); // empty list
6784     }
6785 
6786     /**
6787      * Called by a profile owner of a managed profile to set whether caller-Id information from the
6788      * managed profile will be shown in the parent profile, for incoming calls.
6789      * <p>
6790      * The calling device admin must be a profile owner. If it is not, a security exception will be
6791      * thrown.
6792      *
6793      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6794      * @param disabled If true caller-Id information in the managed profile is not displayed.
6795      * @throws SecurityException if {@code admin} is not a profile owner.
6796      */
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)6797     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
6798         throwIfParentInstance("setCrossProfileCallerIdDisabled");
6799         if (mService != null) {
6800             try {
6801                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
6802             } catch (RemoteException e) {
6803                 throw e.rethrowFromSystemServer();
6804             }
6805         }
6806     }
6807 
6808     /**
6809      * Called by a profile owner of a managed profile to determine whether or not caller-Id
6810      * information has been disabled.
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      * @throws SecurityException if {@code admin} is not a profile owner.
6817      */
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)6818     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
6819         throwIfParentInstance("getCrossProfileCallerIdDisabled");
6820         if (mService != null) {
6821             try {
6822                 return mService.getCrossProfileCallerIdDisabled(admin);
6823             } catch (RemoteException e) {
6824                 throw e.rethrowFromSystemServer();
6825             }
6826         }
6827         return false;
6828     }
6829 
6830     /**
6831      * Determine whether or not caller-Id information has been disabled.
6832      *
6833      * @param userHandle The user for whom to check the caller-id permission
6834      * @hide
6835      */
getCrossProfileCallerIdDisabled(UserHandle userHandle)6836     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
6837         if (mService != null) {
6838             try {
6839                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
6840             } catch (RemoteException e) {
6841                 throw e.rethrowFromSystemServer();
6842             }
6843         }
6844         return false;
6845     }
6846 
6847     /**
6848      * Called by a profile owner of a managed profile to set whether contacts search from the
6849      * managed profile will be shown in the parent profile, for incoming calls.
6850      * <p>
6851      * The calling device admin must be a profile owner. If it is not, a security exception will be
6852      * thrown.
6853      *
6854      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6855      * @param disabled If true contacts search in the managed profile is not displayed.
6856      * @throws SecurityException if {@code admin} is not a profile owner.
6857      */
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)6858     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
6859             boolean disabled) {
6860         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
6861         if (mService != null) {
6862             try {
6863                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
6864             } catch (RemoteException e) {
6865                 throw e.rethrowFromSystemServer();
6866             }
6867         }
6868     }
6869 
6870     /**
6871      * Called by a profile owner of a managed profile to determine whether or not contacts search
6872      * has been disabled.
6873      * <p>
6874      * The calling device admin must be a profile owner. If it is not, a security exception will be
6875      * thrown.
6876      *
6877      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6878      * @throws SecurityException if {@code admin} is not a profile owner.
6879      */
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)6880     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
6881         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
6882         if (mService != null) {
6883             try {
6884                 return mService.getCrossProfileContactsSearchDisabled(admin);
6885             } catch (RemoteException e) {
6886                 throw e.rethrowFromSystemServer();
6887             }
6888         }
6889         return false;
6890     }
6891 
6892 
6893     /**
6894      * Determine whether or not contacts search has been disabled.
6895      *
6896      * @param userHandle The user for whom to check the contacts search permission
6897      * @hide
6898      */
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)6899     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
6900         if (mService != null) {
6901             try {
6902                 return mService
6903                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
6904             } catch (RemoteException e) {
6905                 throw e.rethrowFromSystemServer();
6906             }
6907         }
6908         return false;
6909     }
6910 
6911     /**
6912      * Start Quick Contact on the managed profile for the user, if the policy allows.
6913      *
6914      * @hide
6915      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)6916     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
6917             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
6918         if (mService != null) {
6919             try {
6920                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
6921                         isContactIdIgnored, directoryId, originalIntent);
6922             } catch (RemoteException e) {
6923                 throw e.rethrowFromSystemServer();
6924             }
6925         }
6926     }
6927 
6928     /**
6929      * Start Quick Contact on the managed profile for the user, if the policy allows.
6930      * @hide
6931      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)6932     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
6933             Intent originalIntent) {
6934         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
6935                 originalIntent);
6936     }
6937 
6938     /**
6939      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
6940      * enterprise contacts.
6941      * <p>
6942      * The calling device admin must be a profile owner. If it is not, a security exception will be
6943      * thrown.
6944      * <p>
6945      * This API works on managed profile only.
6946      *
6947      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6948      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
6949      * @throws SecurityException if {@code admin} is not a profile owner.
6950      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)6951     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
6952         throwIfParentInstance("setBluetoothContactSharingDisabled");
6953         if (mService != null) {
6954             try {
6955                 mService.setBluetoothContactSharingDisabled(admin, disabled);
6956             } catch (RemoteException e) {
6957                 throw e.rethrowFromSystemServer();
6958             }
6959         }
6960     }
6961 
6962     /**
6963      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
6964      * cannot access enterprise contacts.
6965      * <p>
6966      * The calling device admin must be a profile owner. If it is not, a security exception will be
6967      * thrown.
6968      * <p>
6969      * This API works on managed profile only.
6970      *
6971      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6972      * @throws SecurityException if {@code admin} is not a profile owner.
6973      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)6974     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
6975         throwIfParentInstance("getBluetoothContactSharingDisabled");
6976         if (mService != null) {
6977             try {
6978                 return mService.getBluetoothContactSharingDisabled(admin);
6979             } catch (RemoteException e) {
6980                 throw e.rethrowFromSystemServer();
6981             }
6982         }
6983         return true;
6984     }
6985 
6986     /**
6987      * Determine whether or not Bluetooth devices cannot access contacts.
6988      * <p>
6989      * This API works on managed profile UserHandle only.
6990      *
6991      * @param userHandle The user for whom to check the caller-id permission
6992      * @hide
6993      */
getBluetoothContactSharingDisabled(UserHandle userHandle)6994     public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
6995         if (mService != null) {
6996             try {
6997                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
6998                         .getIdentifier());
6999             } catch (RemoteException e) {
7000                 throw e.rethrowFromSystemServer();
7001             }
7002         }
7003         return true;
7004     }
7005 
7006     /**
7007      * Called by the profile owner of a managed profile so that some intents sent in the managed
7008      * profile can also be resolved in the parent, or vice versa. Only activity intents are
7009      * supported.
7010      *
7011      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7012      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
7013      *            other profile
7014      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
7015      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
7016      * @throws SecurityException if {@code admin} is not a device or profile owner.
7017      */
addCrossProfileIntentFilter(@onNull ComponentName admin, IntentFilter filter, int flags)7018     public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
7019         throwIfParentInstance("addCrossProfileIntentFilter");
7020         if (mService != null) {
7021             try {
7022                 mService.addCrossProfileIntentFilter(admin, filter, flags);
7023             } catch (RemoteException e) {
7024                 throw e.rethrowFromSystemServer();
7025             }
7026         }
7027     }
7028 
7029     /**
7030      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
7031      * that go from the managed profile to the parent, or from the parent to the managed profile.
7032      * Only removes those that have been set by the profile owner.
7033      * <p>
7034      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
7035      * the profile is created, some of them ensure the proper functioning of the profile, while
7036      * others enable sharing of data from the parent to the managed profile for user convenience.
7037      * These default intent filters are not cleared when this API is called. If the default cross
7038      * profile data sharing is not desired, they can be disabled with
7039      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
7040      *
7041      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7042      * @throws SecurityException if {@code admin} is not a profile owner.
7043      */
clearCrossProfileIntentFilters(@onNull ComponentName admin)7044     public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
7045         throwIfParentInstance("clearCrossProfileIntentFilters");
7046         if (mService != null) {
7047             try {
7048                 mService.clearCrossProfileIntentFilters(admin);
7049             } catch (RemoteException e) {
7050                 throw e.rethrowFromSystemServer();
7051             }
7052         }
7053     }
7054 
7055     /**
7056      * Called by a profile or device owner to set the permitted
7057      * {@link android.accessibilityservice.AccessibilityService}. When set by
7058      * a device owner or profile owner the restriction applies to all profiles of the user the
7059      * device owner or profile owner is an admin for. By default, the user can use any accessibility
7060      * service. When zero or more packages have been added, accessibility services that are not in
7061      * the list and not part of the system can not be enabled by the user.
7062      * <p>
7063      * Calling with a null value for the list disables the restriction so that all services can be
7064      * used, calling with an empty list only allows the built-in system services. Any non-system
7065      * accessibility service that's currently enabled must be included in the list.
7066      * <p>
7067      * System accessibility services are always available to the user the list can't modify this.
7068      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7069      * @param packageNames List of accessibility service package names.
7070      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
7071      *         contain every enabled non-system accessibility service.
7072      * @throws SecurityException if {@code admin} is not a device or profile owner.
7073      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)7074     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
7075             List<String> packageNames) {
7076         throwIfParentInstance("setPermittedAccessibilityServices");
7077         if (mService != null) {
7078             try {
7079                 return mService.setPermittedAccessibilityServices(admin, packageNames);
7080             } catch (RemoteException e) {
7081                 throw e.rethrowFromSystemServer();
7082             }
7083         }
7084         return false;
7085     }
7086 
7087     /**
7088      * Returns the list of permitted accessibility services set by this device or profile owner.
7089      * <p>
7090      * An empty list means no accessibility services except system services are allowed. Null means
7091      * all accessibility services are allowed.
7092      *
7093      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7094      * @return List of accessiblity service package names.
7095      * @throws SecurityException if {@code admin} is not a device or profile owner.
7096      */
getPermittedAccessibilityServices(@onNull ComponentName admin)7097     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
7098         throwIfParentInstance("getPermittedAccessibilityServices");
7099         if (mService != null) {
7100             try {
7101                 return mService.getPermittedAccessibilityServices(admin);
7102             } catch (RemoteException e) {
7103                 throw e.rethrowFromSystemServer();
7104             }
7105         }
7106         return null;
7107     }
7108 
7109     /**
7110      * Called by the system to check if a specific accessibility service is disabled by admin.
7111      *
7112      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7113      * @param packageName Accessibility service package name that needs to be checked.
7114      * @param userHandle user id the admin is running as.
7115      * @return true if the accessibility service is permitted, otherwise false.
7116      *
7117      * @hide
7118      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)7119     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
7120             @NonNull String packageName, int userHandle) {
7121         if (mService != null) {
7122             try {
7123                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
7124                         userHandle);
7125             } catch (RemoteException e) {
7126                 throw e.rethrowFromSystemServer();
7127             }
7128         }
7129         return false;
7130     }
7131 
7132     /**
7133      * Returns the list of accessibility services permitted by the device or profiles
7134      * owners of this user.
7135      *
7136      * <p>Null means all accessibility services are allowed, if a non-null list is returned
7137      * it will contain the intersection of the permitted lists for any device or profile
7138      * owners that apply to this user. It will also include any system accessibility services.
7139      *
7140      * @param userId which user to check for.
7141      * @return List of accessiblity service package names.
7142      * @hide
7143      */
7144      @SystemApi
7145      @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedAccessibilityServices(int userId)7146      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
7147         throwIfParentInstance("getPermittedAccessibilityServices");
7148         if (mService != null) {
7149             try {
7150                 return mService.getPermittedAccessibilityServicesForUser(userId);
7151             } catch (RemoteException e) {
7152                 throw e.rethrowFromSystemServer();
7153             }
7154         }
7155         return null;
7156      }
7157 
7158     /**
7159      * Called by a profile or device owner to set the permitted input methods services for this
7160      * user. By default, the user can use any input method.
7161      * <p>
7162      * When zero or more packages have been added, input method that are not in the list and not
7163      * part of the system can not be enabled by the user. This method will fail if it is called for
7164      * a admin that is not for the foreground user or a profile of the foreground user. Any
7165      * non-system input method service that's currently enabled must be included in the list.
7166      * <p>
7167      * Calling with a null value for the list disables the restriction so that all input methods can
7168      * be used, calling with an empty list disables all but the system's own input methods.
7169      * <p>
7170      * System input methods are always available to the user - this method can't modify this.
7171      *
7172      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7173      * @param packageNames List of input method package names.
7174      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
7175      *        contain every enabled non-system input method service.
7176      * @throws SecurityException if {@code admin} is not a device or profile owner.
7177      */
setPermittedInputMethods( @onNull ComponentName admin, List<String> packageNames)7178     public boolean setPermittedInputMethods(
7179             @NonNull ComponentName admin, List<String> packageNames) {
7180         throwIfParentInstance("setPermittedInputMethods");
7181         if (mService != null) {
7182             try {
7183                 return mService.setPermittedInputMethods(admin, packageNames);
7184             } catch (RemoteException e) {
7185                 throw e.rethrowFromSystemServer();
7186             }
7187         }
7188         return false;
7189     }
7190 
7191 
7192     /**
7193      * Returns the list of permitted input methods set by this device or profile owner.
7194      * <p>
7195      * An empty list means no input methods except system input methods are allowed. Null means all
7196      * input methods are allowed.
7197      *
7198      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7199      * @return List of input method package names.
7200      * @throws SecurityException if {@code admin} is not a device or profile owner.
7201      */
getPermittedInputMethods(@onNull ComponentName admin)7202     public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
7203         throwIfParentInstance("getPermittedInputMethods");
7204         if (mService != null) {
7205             try {
7206                 return mService.getPermittedInputMethods(admin);
7207             } catch (RemoteException e) {
7208                 throw e.rethrowFromSystemServer();
7209             }
7210         }
7211         return null;
7212     }
7213 
7214     /**
7215      * Called by the system to check if a specific input method is disabled by admin.
7216      *
7217      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7218      * @param packageName Input method package name that needs to be checked.
7219      * @param userHandle user id the admin is running as.
7220      * @return true if the input method is permitted, otherwise false.
7221      *
7222      * @hide
7223      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)7224     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
7225             @NonNull String packageName, int userHandle) {
7226         if (mService != null) {
7227             try {
7228                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
7229             } catch (RemoteException e) {
7230                 throw e.rethrowFromSystemServer();
7231             }
7232         }
7233         return false;
7234     }
7235 
7236     /**
7237      * Returns the list of input methods permitted by the device or profiles owners.
7238      *
7239      * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
7240      * result for the calling user.</p>
7241      *
7242      * <p>On Android P and prior devices, this method returns the result for the current user.</p>
7243      *
7244      * <p>Null means all input methods are allowed, if a non-null list is returned
7245      * it will contain the intersection of the permitted lists for any device or profile
7246      * owners that apply to this user. It will also include any system input methods.
7247      *
7248      * @return List of input method package names.
7249      * @hide
7250      */
7251     @SystemApi
7252     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedInputMethodsForCurrentUser()7253     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
7254         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
7255         if (mService != null) {
7256             try {
7257                 return mService.getPermittedInputMethodsForCurrentUser();
7258             } catch (RemoteException e) {
7259                 throw e.rethrowFromSystemServer();
7260             }
7261         }
7262         return null;
7263     }
7264 
7265     /**
7266      * Called by a profile owner of a managed profile to set the packages that are allowed to use
7267      * a {@link android.service.notification.NotificationListenerService} in the primary user to
7268      * see notifications from the managed profile. By default all packages are permitted by this
7269      * policy. When zero or more packages have been added, notification listeners installed on the
7270      * primary user that are not in the list and are not part of the system won't receive events
7271      * for managed profile notifications.
7272      * <p>
7273      * Calling with a {@code null} value for the list disables the restriction so that all
7274      * notification listener services be used. Calling with an empty list disables all but the
7275      * system's own notification listeners. System notification listener services are always
7276      * available to the user.
7277      * <p>
7278      * If a device or profile owner want to stop notification listeners in their user from seeing
7279      * that user's notifications they should prevent that service from running instead (e.g. via
7280      * {@link #setApplicationHidden(ComponentName, String, boolean)})
7281      *
7282      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7283      * @param packageList List of package names to whitelist
7284      * @return true if setting the restriction succeeded. It will fail if called outside a managed
7285      * profile
7286      * @throws SecurityException if {@code admin} is not a profile owner.
7287      *
7288      * @see android.service.notification.NotificationListenerService
7289      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)7290     public boolean setPermittedCrossProfileNotificationListeners(
7291             @NonNull ComponentName admin, @Nullable List<String> packageList) {
7292         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
7293         if (mService != null) {
7294             try {
7295                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
7296             } catch (RemoteException e) {
7297                 throw e.rethrowFromSystemServer();
7298             }
7299         }
7300         return false;
7301     }
7302 
7303     /**
7304      * Returns the list of packages installed on the primary user that allowed to use a
7305      * {@link android.service.notification.NotificationListenerService} to receive
7306      * notifications from this managed profile, as set by the profile owner.
7307      * <p>
7308      * An empty list means no notification listener services except system ones are allowed.
7309      * A {@code null} return value indicates that all notification listeners are allowed.
7310      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)7311     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
7312             @NonNull ComponentName admin) {
7313         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
7314         if (mService != null) {
7315             try {
7316                 return mService.getPermittedCrossProfileNotificationListeners(admin);
7317             } catch (RemoteException e) {
7318                 throw e.rethrowFromSystemServer();
7319             }
7320         }
7321         return null;
7322     }
7323 
7324     /**
7325      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
7326      * receive events for notifications from the given user id. Can only be called by the system uid
7327      *
7328      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
7329      *
7330      * @hide
7331      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)7332     public boolean isNotificationListenerServicePermitted(
7333             @NonNull String packageName, @UserIdInt int userId) {
7334         if (mService != null) {
7335             try {
7336                 return mService.isNotificationListenerServicePermitted(packageName, userId);
7337             } catch (RemoteException e) {
7338                 throw e.rethrowFromSystemServer();
7339             }
7340         }
7341         return true;
7342     }
7343 
7344     /**
7345      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
7346      * function can be called by a device owner or by a delegate given the
7347      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
7348      * <p>
7349      * Please note that packages returned in this method are not automatically pre-cached.
7350      *
7351      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7352      *            {@code null} if the caller is a keep uninstalled packages delegate.
7353      * @return List of package names to keep cached.
7354      * @see #setDelegatedScopes
7355      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
7356      */
getKeepUninstalledPackages(@ullable ComponentName admin)7357     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
7358         throwIfParentInstance("getKeepUninstalledPackages");
7359         if (mService != null) {
7360             try {
7361                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
7362             } catch (RemoteException e) {
7363                 throw e.rethrowFromSystemServer();
7364             }
7365         }
7366         return null;
7367     }
7368 
7369     /**
7370      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
7371      * function can be called by a device owner or by a delegate given the
7372      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
7373      *
7374      * <p>Please note that setting this policy does not imply that specified apps will be
7375      * automatically pre-cached.</p>
7376      *
7377      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7378      *            {@code null} if the caller is a keep uninstalled packages delegate.
7379      * @param packageNames List of package names to keep cached.
7380      * @throws SecurityException if {@code admin} is not a device owner.
7381      * @see #setDelegatedScopes
7382      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
7383      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)7384     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
7385             @NonNull List<String> packageNames) {
7386         throwIfParentInstance("setKeepUninstalledPackages");
7387         if (mService != null) {
7388             try {
7389                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
7390             } catch (RemoteException e) {
7391                 throw e.rethrowFromSystemServer();
7392             }
7393         }
7394     }
7395 
7396     /**
7397      * Called by a device owner to create a user with the specified name. The UserHandle returned
7398      * by this method should not be persisted as user handles are recycled as users are removed and
7399      * created. If you need to persist an identifier for this user, use
7400      * {@link UserManager#getSerialNumberForUser}.
7401      *
7402      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7403      * @param name the user's name
7404      * @see UserHandle
7405      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
7406      *         user could not be created.
7407      *
7408      * @deprecated From {@link android.os.Build.VERSION_CODES#M}
7409      * @removed From {@link android.os.Build.VERSION_CODES#N}
7410      */
7411     @Deprecated
createUser(@onNull ComponentName admin, String name)7412     public @Nullable UserHandle createUser(@NonNull ComponentName admin, String name) {
7413         return null;
7414     }
7415 
7416     /**
7417      * Called by a device owner to create a user with the specified name. The UserHandle returned
7418      * by this method should not be persisted as user handles are recycled as users are removed and
7419      * created. If you need to persist an identifier for this user, use
7420      * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
7421      * immediately.
7422      *
7423      * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
7424      * as registered as an active admin on the new user.  The profile owner package will be
7425      * installed on the new user if it already is installed on the device.
7426      *
7427      * <p>If the optionalInitializeData is not null, then the extras will be passed to the
7428      * profileOwnerComponent when onEnable is called.
7429      *
7430      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7431      * @param name the user's name
7432      * @param ownerName the human readable name of the organisation associated with this DPM.
7433      * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
7434      *      the user.
7435      * @param adminExtras Extras that will be passed to onEnable of the admin receiver
7436      *      on the new user.
7437      * @see UserHandle
7438      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
7439      *         user could not be created.
7440      *
7441      * @deprecated From {@link android.os.Build.VERSION_CODES#M}
7442      * @removed From {@link android.os.Build.VERSION_CODES#N}
7443      */
7444     @Deprecated
createAndInitializeUser(@onNull ComponentName admin, String name, String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras)7445     public @Nullable UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
7446             String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
7447         return null;
7448     }
7449 
7450     /**
7451       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
7452       */
7453     public static final int SKIP_SETUP_WIZARD = 0x0001;
7454 
7455     /**
7456      * Flag used by {@link #createAndManageUser} to specify that the user should be created
7457      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
7458      * device.
7459      */
7460     public static final int MAKE_USER_EPHEMERAL = 0x0002;
7461 
7462     /**
7463      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
7464      * demo user.
7465      * @hide
7466      */
7467     public static final int MAKE_USER_DEMO = 0x0004;
7468 
7469     /**
7470      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
7471      * the disabling of system apps during provisioning.
7472      */
7473     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
7474 
7475     /**
7476      * @hide
7477      */
7478     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
7479             SKIP_SETUP_WIZARD,
7480             MAKE_USER_EPHEMERAL,
7481             MAKE_USER_DEMO,
7482             LEAVE_ALL_SYSTEM_APPS_ENABLED
7483     })
7484     @Retention(RetentionPolicy.SOURCE)
7485     public @interface CreateAndManageUserFlags {}
7486 
7487     /**
7488      * Called by a device owner to create a user with the specified name and a given component of
7489      * the calling package as profile owner. The UserHandle returned by this method should not be
7490      * persisted as user handles are recycled as users are removed and created. If you need to
7491      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
7492      * user will not be started in the background.
7493      * <p>
7494      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
7495      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
7496      * be registered as an active admin on the new user. The profile owner package will be installed
7497      * on the new user.
7498      * <p>
7499      * If the adminExtras are not null, they will be stored on the device until the user is started
7500      * for the first time. Then the extras will be passed to the admin when onEnable is called.
7501      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
7502      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
7503      * returning {@code null} on failure.
7504      *
7505      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7506      * @param name The user's name.
7507      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
7508      *            same package as admin, otherwise no user is created and an
7509      *            IllegalArgumentException is thrown.
7510      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
7511      *            user.
7512      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
7513      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
7514      * @see UserHandle
7515      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
7516      *         user could not be created.
7517      * @throws SecurityException if {@code admin} is not a device owner.
7518      * @throws UserOperationException if the user could not be created and the calling app is
7519      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
7520      * {@link android.os.Build.VERSION_CODES#P}.
7521      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)7522     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
7523             @NonNull String name,
7524             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
7525             @CreateAndManageUserFlags int flags) {
7526         throwIfParentInstance("createAndManageUser");
7527         try {
7528             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
7529         } catch (ServiceSpecificException e) {
7530             throw new UserOperationException(e.getMessage(), e.errorCode);
7531         } catch (RemoteException re) {
7532             throw re.rethrowFromSystemServer();
7533         }
7534     }
7535 
7536     /**
7537      * Called by a device owner to remove a user/profile and all associated data. The primary user
7538      * can not be removed.
7539      *
7540      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7541      * @param userHandle the user to remove.
7542      * @return {@code true} if the user was removed, {@code false} otherwise.
7543      * @throws SecurityException if {@code admin} is not a device owner.
7544      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)7545     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
7546         throwIfParentInstance("removeUser");
7547         try {
7548             return mService.removeUser(admin, userHandle);
7549         } catch (RemoteException re) {
7550             throw re.rethrowFromSystemServer();
7551         }
7552     }
7553 
7554     /**
7555      * Called by a device owner to switch the specified secondary user to the foreground.
7556      *
7557      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7558      * @param userHandle the user to switch to; null will switch to primary.
7559      * @return {@code true} if the switch was successful, {@code false} otherwise.
7560      * @throws SecurityException if {@code admin} is not a device owner.
7561      * @see Intent#ACTION_USER_FOREGROUND
7562      * @see #getSecondaryUsers(ComponentName)
7563      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)7564     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
7565         throwIfParentInstance("switchUser");
7566         try {
7567             return mService.switchUser(admin, userHandle);
7568         } catch (RemoteException re) {
7569             throw re.rethrowFromSystemServer();
7570         }
7571     }
7572 
7573     /**
7574      * Called by a device owner to start the specified secondary user in background.
7575      *
7576      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7577      * @param userHandle the user to be started in background.
7578      * @return one of the following result codes:
7579      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
7580      * {@link UserManager#USER_OPERATION_SUCCESS},
7581      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
7582      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
7583      * @throws SecurityException if {@code admin} is not a device owner.
7584      * @see #getSecondaryUsers(ComponentName)
7585      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)7586     public @UserOperationResult int startUserInBackground(
7587             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
7588         throwIfParentInstance("startUserInBackground");
7589         try {
7590             return mService.startUserInBackground(admin, userHandle);
7591         } catch (RemoteException re) {
7592             throw re.rethrowFromSystemServer();
7593         }
7594     }
7595 
7596     /**
7597      * Called by a device owner to stop the specified secondary user.
7598      *
7599      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7600      * @param userHandle the user to be stopped.
7601      * @return one of the following result codes:
7602      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
7603      * {@link UserManager#USER_OPERATION_SUCCESS},
7604      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
7605      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
7606      * @throws SecurityException if {@code admin} is not a device owner.
7607      * @see #getSecondaryUsers(ComponentName)
7608      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)7609     public @UserOperationResult int stopUser(
7610             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
7611         throwIfParentInstance("stopUser");
7612         try {
7613             return mService.stopUser(admin, userHandle);
7614         } catch (RemoteException re) {
7615             throw re.rethrowFromSystemServer();
7616         }
7617     }
7618 
7619     /**
7620      * Called by a profile owner of secondary user that is affiliated with the device to stop the
7621      * calling user and switch back to primary.
7622      *
7623      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7624      * @return one of the following result codes:
7625      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
7626      * {@link UserManager#USER_OPERATION_SUCCESS},
7627      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
7628      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
7629      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
7630      * @see #getSecondaryUsers(ComponentName)
7631      */
logoutUser(@onNull ComponentName admin)7632     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
7633         throwIfParentInstance("logoutUser");
7634         try {
7635             return mService.logoutUser(admin);
7636         } catch (RemoteException re) {
7637             throw re.rethrowFromSystemServer();
7638         }
7639     }
7640 
7641     /**
7642      * Called by a device owner to list all secondary users on the device. Managed profiles are not
7643      * considered as secondary users.
7644      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
7645      * and {@link #stopUser}.
7646      *
7647      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7648      * @return list of other {@link UserHandle}s on the device.
7649      * @throws SecurityException if {@code admin} is not a device owner.
7650      * @see #removeUser(ComponentName, UserHandle)
7651      * @see #switchUser(ComponentName, UserHandle)
7652      * @see #startUserInBackground(ComponentName, UserHandle)
7653      * @see #stopUser(ComponentName, UserHandle)
7654      */
getSecondaryUsers(@onNull ComponentName admin)7655     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
7656         throwIfParentInstance("getSecondaryUsers");
7657         try {
7658             return mService.getSecondaryUsers(admin);
7659         } catch (RemoteException re) {
7660             throw re.rethrowFromSystemServer();
7661         }
7662     }
7663 
7664     /**
7665      * Checks if the profile owner is running in an ephemeral user.
7666      *
7667      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7668      * @return whether the profile owner is running in an ephemeral user.
7669      */
isEphemeralUser(@onNull ComponentName admin)7670     public boolean isEphemeralUser(@NonNull ComponentName admin) {
7671         throwIfParentInstance("isEphemeralUser");
7672         try {
7673             return mService.isEphemeralUser(admin);
7674         } catch (RemoteException re) {
7675             throw re.rethrowFromSystemServer();
7676         }
7677     }
7678 
7679     /**
7680      * Retrieves the application restrictions for a given target application running in the calling
7681      * user.
7682      * <p>
7683      * The caller must be a profile or device owner on that user, or the package allowed to manage
7684      * application restrictions via {@link #setDelegatedScopes} with the
7685      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
7686      *
7687      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
7688      *
7689      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7690      *            {@code null} if called by the application restrictions managing package.
7691      * @param packageName The name of the package to fetch restricted settings of.
7692      * @return {@link Bundle} of settings corresponding to what was set last time
7693      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
7694      *         {@link Bundle} if no restrictions have been set.
7695      * @throws SecurityException if {@code admin} is not a device or profile owner.
7696      * @see #setDelegatedScopes
7697      * @see #DELEGATION_APP_RESTRICTIONS
7698      */
7699     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)7700     public @NonNull Bundle getApplicationRestrictions(
7701             @Nullable ComponentName admin, String packageName) {
7702         throwIfParentInstance("getApplicationRestrictions");
7703         if (mService != null) {
7704             try {
7705                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
7706                         packageName);
7707             } catch (RemoteException e) {
7708                 throw e.rethrowFromSystemServer();
7709             }
7710         }
7711         return null;
7712     }
7713 
7714     /**
7715      * Called by a profile or device owner to set a user restriction specified by the key.
7716      * <p>
7717      * The calling device admin must be a profile or device owner; if it is not, a security
7718      * exception will be thrown.
7719      *
7720      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7721      * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
7722      *            for the list of keys.
7723      * @throws SecurityException if {@code admin} is not a device or profile owner.
7724      */
addUserRestriction(@onNull ComponentName admin, String key)7725     public void addUserRestriction(@NonNull ComponentName admin, String key) {
7726         throwIfParentInstance("addUserRestriction");
7727         if (mService != null) {
7728             try {
7729                 mService.setUserRestriction(admin, key, true);
7730             } catch (RemoteException e) {
7731                 throw e.rethrowFromSystemServer();
7732             }
7733         }
7734     }
7735 
7736     /**
7737      * Called by a profile or device owner to clear a user restriction specified by the key.
7738      * <p>
7739      * The calling device admin must be a profile or device owner; if it is not, a security
7740      * exception will be thrown.
7741      *
7742      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7743      * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
7744      *            for the list of keys.
7745      * @throws SecurityException if {@code admin} is not a device or profile owner.
7746      */
clearUserRestriction(@onNull ComponentName admin, String key)7747     public void clearUserRestriction(@NonNull ComponentName admin, String key) {
7748         throwIfParentInstance("clearUserRestriction");
7749         if (mService != null) {
7750             try {
7751                 mService.setUserRestriction(admin, key, false);
7752             } catch (RemoteException e) {
7753                 throw e.rethrowFromSystemServer();
7754             }
7755         }
7756     }
7757 
7758     /**
7759      * Called by a profile or device owner to get user restrictions set with
7760      * {@link #addUserRestriction(ComponentName, String)}.
7761      * <p>
7762      * The target user may have more restrictions set by the system or other device owner / profile
7763      * owner. To get all the user restrictions currently set, use
7764      * {@link UserManager#getUserRestrictions()}.
7765      *
7766      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7767      * @throws SecurityException if {@code admin} is not a device or profile owner.
7768      */
getUserRestrictions(@onNull ComponentName admin)7769     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
7770         throwIfParentInstance("getUserRestrictions");
7771         Bundle ret = null;
7772         if (mService != null) {
7773             try {
7774                 ret = mService.getUserRestrictions(admin);
7775             } catch (RemoteException e) {
7776                 throw e.rethrowFromSystemServer();
7777             }
7778         }
7779         return ret == null ? new Bundle() : ret;
7780     }
7781 
7782     /**
7783      * Called by any app to display a support dialog when a feature was disabled by an admin.
7784      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
7785      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
7786      * was disabled by an admin, and include a link for more information. The default content of
7787      * the dialog can be changed by the restricting admin via
7788      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
7789      * set (i.e. the feature is available), then the return value will be {@code null}.
7790      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
7791      *            user restriction from {@link UserManager}, e.g.
7792      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
7793      *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
7794      * @return Intent An intent to be used to start the dialog-activity if the restriction is
7795      *            set by an admin, or null if the restriction does not exist or no admin set it.
7796      */
createAdminSupportIntent(@onNull String restriction)7797     public Intent createAdminSupportIntent(@NonNull String restriction) {
7798         throwIfParentInstance("createAdminSupportIntent");
7799         if (mService != null) {
7800             try {
7801                 return mService.createAdminSupportIntent(restriction);
7802             } catch (RemoteException e) {
7803                 throw e.rethrowFromSystemServer();
7804             }
7805         }
7806         return null;
7807     }
7808 
7809     /**
7810      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
7811      * actual package file remain. This function can be called by a device owner, profile owner, or
7812      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
7813      * {@link #setDelegatedScopes}.
7814      *
7815      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7816      *            {@code null} if the caller is a package access delegate.
7817      * @param packageName The name of the package to hide or unhide.
7818      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
7819      *            unhidden.
7820      * @return boolean Whether the hidden setting of the package was successfully updated.
7821      * @throws SecurityException if {@code admin} is not a device or profile owner.
7822      * @see #setDelegatedScopes
7823      * @see #DELEGATION_PACKAGE_ACCESS
7824      */
setApplicationHidden(@onNull ComponentName admin, String packageName, boolean hidden)7825     public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
7826             boolean hidden) {
7827         throwIfParentInstance("setApplicationHidden");
7828         if (mService != null) {
7829             try {
7830                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
7831                         hidden);
7832             } catch (RemoteException e) {
7833                 throw e.rethrowFromSystemServer();
7834             }
7835         }
7836         return false;
7837     }
7838 
7839     /**
7840      * Determine if a package is hidden. This function can be called by a device owner, profile
7841      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
7842      * {@link #setDelegatedScopes}.
7843      *
7844      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7845      *            {@code null} if the caller is a package access delegate.
7846      * @param packageName The name of the package to retrieve the hidden status of.
7847      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
7848      * @throws SecurityException if {@code admin} is not a device or profile owner.
7849      * @see #setDelegatedScopes
7850      * @see #DELEGATION_PACKAGE_ACCESS
7851      */
isApplicationHidden(@onNull ComponentName admin, String packageName)7852     public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
7853         throwIfParentInstance("isApplicationHidden");
7854         if (mService != null) {
7855             try {
7856                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName);
7857             } catch (RemoteException e) {
7858                 throw e.rethrowFromSystemServer();
7859             }
7860         }
7861         return false;
7862     }
7863 
7864     /**
7865      * Re-enable a system app that was disabled by default when the user was initialized. This
7866      * function can be called by a device owner, profile owner, or by a delegate given the
7867      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
7868      *
7869      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7870      *            {@code null} if the caller is an enable system app delegate.
7871      * @param packageName The package to be re-enabled in the calling profile.
7872      * @throws SecurityException if {@code admin} is not a device or profile owner.
7873      * @see #setDelegatedScopes
7874      * @see #DELEGATION_PACKAGE_ACCESS
7875      */
enableSystemApp(@onNull ComponentName admin, String packageName)7876     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
7877         throwIfParentInstance("enableSystemApp");
7878         if (mService != null) {
7879             try {
7880                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
7881             } catch (RemoteException e) {
7882                 throw e.rethrowFromSystemServer();
7883             }
7884         }
7885     }
7886 
7887     /**
7888      * Re-enable system apps by intent that were disabled by default when the user was initialized.
7889      * This function can be called by a device owner, profile owner, or by a delegate given the
7890      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
7891      *
7892      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7893      *            {@code null} if the caller is an enable system app delegate.
7894      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
7895      *            intent will be re-enabled in the calling profile.
7896      * @return int The number of activities that matched the intent and were installed.
7897      * @throws SecurityException if {@code admin} is not a device or profile owner.
7898      * @see #setDelegatedScopes
7899      * @see #DELEGATION_PACKAGE_ACCESS
7900      */
enableSystemApp(@onNull ComponentName admin, Intent intent)7901     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
7902         throwIfParentInstance("enableSystemApp");
7903         if (mService != null) {
7904             try {
7905                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
7906             } catch (RemoteException e) {
7907                 throw e.rethrowFromSystemServer();
7908             }
7909         }
7910         return 0;
7911     }
7912 
7913     /**
7914      * Install an existing package that has been installed in another user, or has been kept after
7915      * removal via {@link #setKeepUninstalledPackages}.
7916      * This function can be called by a device owner, profile owner or a delegate given
7917      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
7918      * When called in a secondary user or managed profile, the user/profile must be affiliated with
7919      * the device. See {@link #isAffiliatedUser}.
7920      *
7921      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7922      * @param packageName The package to be installed in the calling profile.
7923      * @return {@code true} if the app is installed; {@code false} otherwise.
7924      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
7925      * an affiliated user or profile.
7926      * @see #setKeepUninstalledPackages
7927      * @see #setDelegatedScopes
7928      * @see #isAffiliatedUser
7929      * @see #DELEGATION_PACKAGE_ACCESS
7930      */
installExistingPackage(@onNull ComponentName admin, String packageName)7931     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
7932         throwIfParentInstance("installExistingPackage");
7933         if (mService != null) {
7934             try {
7935                 return mService.installExistingPackage(admin, mContext.getPackageName(),
7936                         packageName);
7937             } catch (RemoteException e) {
7938                 throw e.rethrowFromSystemServer();
7939             }
7940         }
7941         return false;
7942     }
7943 
7944     /**
7945      * Called by a device owner or profile owner to disable account management for a specific type
7946      * of account.
7947      * <p>
7948      * The calling device admin must be a device owner or profile owner. If it is not, a security
7949      * exception will be thrown.
7950      * <p>
7951      * When account management is disabled for an account type, adding or removing an account of
7952      * that type will not be possible.
7953      * <p>
7954      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
7955      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
7956      * management for a specific type is disabled.
7957      *
7958      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7959      * @param accountType For which account management is disabled or enabled.
7960      * @param disabled The boolean indicating that account management will be disabled (true) or
7961      *            enabled (false).
7962      * @throws SecurityException if {@code admin} is not a device or profile owner.
7963      */
setAccountManagementDisabled(@onNull ComponentName admin, String accountType, boolean disabled)7964     public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
7965             boolean disabled) {
7966         throwIfParentInstance("setAccountManagementDisabled");
7967         if (mService != null) {
7968             try {
7969                 mService.setAccountManagementDisabled(admin, accountType, disabled);
7970             } catch (RemoteException e) {
7971                 throw e.rethrowFromSystemServer();
7972             }
7973         }
7974     }
7975 
7976     /**
7977      * Gets the array of accounts for which account management is disabled by the profile owner.
7978      *
7979      * <p> Account management can be disabled/enabled by calling
7980      * {@link #setAccountManagementDisabled}.
7981      *
7982      * @return a list of account types for which account management has been disabled.
7983      *
7984      * @see #setAccountManagementDisabled
7985      */
getAccountTypesWithManagementDisabled()7986     public @Nullable String[] getAccountTypesWithManagementDisabled() {
7987         throwIfParentInstance("getAccountTypesWithManagementDisabled");
7988         return getAccountTypesWithManagementDisabledAsUser(myUserId());
7989     }
7990 
7991     /**
7992      * @see #getAccountTypesWithManagementDisabled()
7993      * @hide
7994      */
getAccountTypesWithManagementDisabledAsUser(int userId)7995     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7996         if (mService != null) {
7997             try {
7998                 return mService.getAccountTypesWithManagementDisabledAsUser(userId);
7999             } catch (RemoteException e) {
8000                 throw e.rethrowFromSystemServer();
8001             }
8002         }
8003 
8004         return null;
8005     }
8006 
8007     /**
8008      * Sets which packages may enter lock task mode.
8009      * <p>
8010      * Any packages that share uid with an allowed package will also be allowed to activate lock
8011      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
8012      * package list results in locked tasks belonging to those packages to be finished.
8013      * <p>
8014      * This function can only be called by the device owner, a profile owner of an affiliated user
8015      * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
8016      * Any package set via this method will be cleared if the user becomes unaffiliated.
8017      *
8018      * @param packages The list of packages allowed to enter lock task mode
8019      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8020      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8021      * affiliated user or profile, or the profile owner when no device owner is set.
8022      * @see #isAffiliatedUser
8023      * @see Activity#startLockTask()
8024      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
8025      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
8026      * @see UserManager#DISALLOW_CREATE_WINDOWS
8027      */
setLockTaskPackages(@onNull ComponentName admin, @NonNull String[] packages)8028     public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
8029             throws SecurityException {
8030         throwIfParentInstance("setLockTaskPackages");
8031         if (mService != null) {
8032             try {
8033                 mService.setLockTaskPackages(admin, packages);
8034             } catch (RemoteException e) {
8035                 throw e.rethrowFromSystemServer();
8036             }
8037         }
8038     }
8039 
8040     /**
8041      * Returns the list of packages allowed to start the lock task mode.
8042      *
8043      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8044      * affiliated user or profile, or the profile owner when no device owner is set.
8045      * @see #isAffiliatedUser
8046      * @see #setLockTaskPackages
8047      */
getLockTaskPackages(@onNull ComponentName admin)8048     public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
8049         throwIfParentInstance("getLockTaskPackages");
8050         if (mService != null) {
8051             try {
8052                 return mService.getLockTaskPackages(admin);
8053             } catch (RemoteException e) {
8054                 throw e.rethrowFromSystemServer();
8055             }
8056         }
8057         return new String[0];
8058     }
8059 
8060     /**
8061      * This function lets the caller know whether the given component is allowed to start the
8062      * lock task mode.
8063      * @param pkg The package to check
8064      */
isLockTaskPermitted(String pkg)8065     public boolean isLockTaskPermitted(String pkg) {
8066         throwIfParentInstance("isLockTaskPermitted");
8067         if (mService != null) {
8068             try {
8069                 return mService.isLockTaskPermitted(pkg);
8070             } catch (RemoteException e) {
8071                 throw e.rethrowFromSystemServer();
8072             }
8073         }
8074         return false;
8075     }
8076 
8077     /**
8078      * Sets which system features are enabled when the device runs in lock task mode. This method
8079      * doesn't affect the features when lock task mode is inactive. Any system features not included
8080      * in {@code flags} are implicitly disabled when calling this method. By default, only
8081      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled—all the other features are disabled. To
8082      * disable the global actions dialog, call this method omitting
8083      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
8084      *
8085      * <p>This method can only be called by the device owner, a profile owner of an affiliated
8086      * user or profile, or the profile owner when no device owner is set. See
8087      * {@link #isAffiliatedUser}.
8088      * Any features set using this method are cleared if the user becomes unaffiliated.
8089      *
8090      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8091      * @param flags The system features enabled during lock task mode.
8092      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8093      * affiliated user or profile, or the profile owner when no device owner is set.
8094      * @see #isAffiliatedUser
8095      **/
setLockTaskFeatures(@onNull ComponentName admin, @LockTaskFeature int flags)8096     public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
8097         throwIfParentInstance("setLockTaskFeatures");
8098         if (mService != null) {
8099             try {
8100                 mService.setLockTaskFeatures(admin, flags);
8101             } catch (RemoteException e) {
8102                 throw e.rethrowFromSystemServer();
8103             }
8104         }
8105     }
8106 
8107     /**
8108      * Gets which system features are enabled for LockTask mode.
8109      *
8110      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8111      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
8112      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8113      * affiliated user or profile, or the profile owner when no device owner is set.
8114      * @see #isAffiliatedUser
8115      * @see #setLockTaskFeatures
8116      */
getLockTaskFeatures(@onNull ComponentName admin)8117     public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
8118         throwIfParentInstance("getLockTaskFeatures");
8119         if (mService != null) {
8120             try {
8121                 return mService.getLockTaskFeatures(admin);
8122             } catch (RemoteException e) {
8123                 throw e.rethrowFromSystemServer();
8124             }
8125         }
8126         return 0;
8127     }
8128 
8129     /**
8130      * Called by device owner to update {@link android.provider.Settings.Global} settings.
8131      * Validation that the value of the setting is in the correct form for the setting type should
8132      * be performed by the caller.
8133      * <p>
8134      * The settings that can be updated with this method are:
8135      * <ul>
8136      * <li>{@link android.provider.Settings.Global#ADB_ENABLED}</li>
8137      * <li>{@link android.provider.Settings.Global#AUTO_TIME}</li>
8138      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE}</li>
8139      * <li>{@link android.provider.Settings.Global#DATA_ROAMING}</li>
8140      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
8141      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}</li>
8142      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
8143      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
8144      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
8145      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
8146      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
8147      * </ul>
8148      * <p>
8149      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
8150      * <ul>
8151      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
8152      * {@link android.bluetooth.BluetoothAdapter#enable()} and
8153      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
8154      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
8155      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
8156      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
8157      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
8158      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
8159      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
8160      * </ul>
8161      *
8162      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8163      * @param setting The name of the setting to update.
8164      * @param value The value to update the setting to.
8165      * @throws SecurityException if {@code admin} is not a device owner.
8166      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)8167     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
8168         throwIfParentInstance("setGlobalSetting");
8169         if (mService != null) {
8170             try {
8171                 mService.setGlobalSetting(admin, setting, value);
8172             } catch (RemoteException e) {
8173                 throw e.rethrowFromSystemServer();
8174             }
8175         }
8176     }
8177 
8178     /** @hide */
8179     @StringDef({
8180             Settings.System.SCREEN_BRIGHTNESS_MODE,
8181             Settings.System.SCREEN_BRIGHTNESS,
8182             Settings.System.SCREEN_OFF_TIMEOUT
8183     })
8184     @Retention(RetentionPolicy.SOURCE)
8185     public @interface SystemSettingsWhitelist {}
8186 
8187     /**
8188      * Called by a device or profile owner to update {@link android.provider.Settings.System}
8189      * settings. Validation that the value of the setting is in the correct form for the setting
8190      * type should be performed by the caller.
8191      * <p>
8192      * The settings that can be updated by a device owner or profile owner of secondary user with
8193      * this method are:
8194      * <ul>
8195      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
8196      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
8197      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
8198      * </ul>
8199      * <p>
8200      *
8201      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
8202      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8203      * @param setting The name of the setting to update.
8204      * @param value The value to update the setting to.
8205      * @throws SecurityException if {@code admin} is not a device or profile owner.
8206      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)8207     public void setSystemSetting(@NonNull ComponentName admin,
8208             @NonNull @SystemSettingsWhitelist String setting, String value) {
8209         throwIfParentInstance("setSystemSetting");
8210         if (mService != null) {
8211             try {
8212                 mService.setSystemSetting(admin, setting, value);
8213             } catch (RemoteException e) {
8214                 throw e.rethrowFromSystemServer();
8215             }
8216         }
8217     }
8218 
8219     /**
8220      * Called by device owner to set the system wall clock time. This only takes effect if called
8221      * when {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false} will be
8222      * returned.
8223      *
8224      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
8225      * @param millis time in milliseconds since the Epoch
8226      * @return {@code true} if set time succeeded, {@code false} otherwise.
8227      * @throws SecurityException if {@code admin} is not a device owner.
8228      */
setTime(@onNull ComponentName admin, long millis)8229     public boolean setTime(@NonNull ComponentName admin, long millis) {
8230         throwIfParentInstance("setTime");
8231         if (mService != null) {
8232             try {
8233                 return mService.setTime(admin, millis);
8234             } catch (RemoteException e) {
8235                 throw e.rethrowFromSystemServer();
8236             }
8237         }
8238         return false;
8239     }
8240 
8241     /**
8242      * Called by device owner to set the system's persistent default time zone. This only takes
8243      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE} is 0, otherwise
8244      * {@code false} will be returned.
8245      *
8246      * @see android.app.AlarmManager#setTimeZone(String)
8247      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
8248      * @param timeZone one of the Olson ids from the list returned by
8249      *     {@link java.util.TimeZone#getAvailableIDs}
8250      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
8251      * @throws SecurityException if {@code admin} is not a device owner.
8252      */
setTimeZone(@onNull ComponentName admin, String timeZone)8253     public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
8254         throwIfParentInstance("setTimeZone");
8255         if (mService != null) {
8256             try {
8257                 return mService.setTimeZone(admin, timeZone);
8258             } catch (RemoteException e) {
8259                 throw e.rethrowFromSystemServer();
8260             }
8261         }
8262         return false;
8263     }
8264 
8265     /**
8266      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
8267      * settings. Validation that the value of the setting is in the correct form for the setting
8268      * type should be performed by the caller.
8269      * <p>
8270      * The settings that can be updated by a profile or device owner with this method are:
8271      * <ul>
8272      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
8273      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
8274      * </ul>
8275      * <p>
8276      * A device owner can additionally update the following settings:
8277      * <ul>
8278      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}</li>
8279      * </ul>
8280      *
8281      * <strong>Note: Starting from Android O, apps should no longer call this method with the
8282      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
8283      * deprecated. Instead, device owners or profile owners should use the restriction
8284      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
8285      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
8286      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
8287      * an {@link UnsupportedOperationException} is thrown.
8288      *
8289      * Starting from Android Q, the device and profile owner can also call
8290      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
8291      * all users.
8292      * </strong>
8293      *
8294      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8295      * @param setting The name of the setting to update.
8296      * @param value The value to update the setting to.
8297      * @throws SecurityException if {@code admin} is not a device or profile owner.
8298      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)8299     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
8300         throwIfParentInstance("setSecureSetting");
8301         if (mService != null) {
8302             try {
8303                 mService.setSecureSetting(admin, setting, value);
8304             } catch (RemoteException e) {
8305                 throw e.rethrowFromSystemServer();
8306             }
8307         }
8308     }
8309 
8310     /**
8311      * Designates a specific service component as the provider for making permission requests of a
8312      * local or remote administrator of the user.
8313      * <p/>
8314      * Only a profile owner can designate the restrictions provider.
8315      *
8316      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8317      * @param provider The component name of the service that implements
8318      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
8319      *            provider previously assigned.
8320      * @throws SecurityException if {@code admin} is not a device or profile owner.
8321      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)8322     public void setRestrictionsProvider(@NonNull ComponentName admin,
8323             @Nullable ComponentName provider) {
8324         throwIfParentInstance("setRestrictionsProvider");
8325         if (mService != null) {
8326             try {
8327                 mService.setRestrictionsProvider(admin, provider);
8328             } catch (RemoteException re) {
8329                 throw re.rethrowFromSystemServer();
8330             }
8331         }
8332     }
8333 
8334     /**
8335      * Called by profile or device owners to set the master volume mute on or off.
8336      * This has no effect when set on a managed profile.
8337      *
8338      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8339      * @param on {@code true} to mute master volume, {@code false} to turn mute off.
8340      * @throws SecurityException if {@code admin} is not a device or profile owner.
8341      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)8342     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
8343         throwIfParentInstance("setMasterVolumeMuted");
8344         if (mService != null) {
8345             try {
8346                 mService.setMasterVolumeMuted(admin, on);
8347             } catch (RemoteException re) {
8348                 throw re.rethrowFromSystemServer();
8349             }
8350         }
8351     }
8352 
8353     /**
8354      * Called by profile or device owners to check whether the master volume mute is on or off.
8355      *
8356      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8357      * @return {@code true} if master volume is muted, {@code false} if it's not.
8358      * @throws SecurityException if {@code admin} is not a device or profile owner.
8359      */
isMasterVolumeMuted(@onNull ComponentName admin)8360     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
8361         throwIfParentInstance("isMasterVolumeMuted");
8362         if (mService != null) {
8363             try {
8364                 return mService.isMasterVolumeMuted(admin);
8365             } catch (RemoteException re) {
8366                 throw re.rethrowFromSystemServer();
8367             }
8368         }
8369         return false;
8370     }
8371 
8372     /**
8373      * Change whether a user can uninstall a package. This function can be called by a device owner,
8374      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
8375      * {@link #setDelegatedScopes}.
8376      *
8377      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8378      *             {@code null} if the caller is a block uninstall delegate.
8379      * @param packageName package to change.
8380      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
8381      * @throws SecurityException if {@code admin} is not a device or profile owner.
8382      * @see #setDelegatedScopes
8383      * @see #DELEGATION_BLOCK_UNINSTALL
8384      */
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)8385     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
8386             boolean uninstallBlocked) {
8387         throwIfParentInstance("setUninstallBlocked");
8388         if (mService != null) {
8389             try {
8390                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
8391                     uninstallBlocked);
8392             } catch (RemoteException re) {
8393                 throw re.rethrowFromSystemServer();
8394             }
8395         }
8396     }
8397 
8398     /**
8399      * Check whether the user has been blocked by device policy from uninstalling a package.
8400      * Requires the caller to be the profile owner if checking a specific admin's policy.
8401      * <p>
8402      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
8403      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
8404      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
8405      * will cause a NullPointerException to be raised.
8406      *
8407      * @param admin The name of the admin component whose blocking policy will be checked, or
8408      *            {@code null} to check whether any admin has blocked the uninstallation.
8409      * @param packageName package to check.
8410      * @return true if uninstallation is blocked.
8411      * @throws SecurityException if {@code admin} is not a device or profile owner.
8412      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)8413     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
8414         throwIfParentInstance("isUninstallBlocked");
8415         if (mService != null) {
8416             try {
8417                 return mService.isUninstallBlocked(admin, packageName);
8418             } catch (RemoteException re) {
8419                 throw re.rethrowFromSystemServer();
8420             }
8421         }
8422         return false;
8423     }
8424 
8425     /**
8426      * Called by the profile owner of a managed profile to enable widget providers from a given
8427      * package to be available in the parent profile. As a result the user will be able to add
8428      * widgets from the white-listed package running under the profile to a widget host which runs
8429      * under the parent profile, for example the home screen. Note that a package may have zero or
8430      * more provider components, where each component provides a different widget type.
8431      * <p>
8432      * <strong>Note:</strong> By default no widget provider package is white-listed.
8433      *
8434      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8435      * @param packageName The package from which widget providers are white-listed.
8436      * @return Whether the package was added.
8437      * @throws SecurityException if {@code admin} is not a profile owner.
8438      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
8439      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
8440      */
addCrossProfileWidgetProvider(@onNull ComponentName admin, String packageName)8441     public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
8442         throwIfParentInstance("addCrossProfileWidgetProvider");
8443         if (mService != null) {
8444             try {
8445                 return mService.addCrossProfileWidgetProvider(admin, packageName);
8446             } catch (RemoteException re) {
8447                 throw re.rethrowFromSystemServer();
8448             }
8449         }
8450         return false;
8451     }
8452 
8453     /**
8454      * Called by the profile owner of a managed profile to disable widget providers from a given
8455      * package to be available in the parent profile. For this method to take effect the package
8456      * should have been added via
8457      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
8458      * <p>
8459      * <strong>Note:</strong> By default no widget provider package is white-listed.
8460      *
8461      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8462      * @param packageName The package from which widget providers are no longer white-listed.
8463      * @return Whether the package was removed.
8464      * @throws SecurityException if {@code admin} is not a profile owner.
8465      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
8466      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
8467      */
removeCrossProfileWidgetProvider( @onNull ComponentName admin, String packageName)8468     public boolean removeCrossProfileWidgetProvider(
8469             @NonNull ComponentName admin, String packageName) {
8470         throwIfParentInstance("removeCrossProfileWidgetProvider");
8471         if (mService != null) {
8472             try {
8473                 return mService.removeCrossProfileWidgetProvider(admin, packageName);
8474             } catch (RemoteException re) {
8475                 throw re.rethrowFromSystemServer();
8476             }
8477         }
8478         return false;
8479     }
8480 
8481     /**
8482      * Called by the profile owner of a managed profile to query providers from which packages are
8483      * available in the parent profile.
8484      *
8485      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8486      * @return The white-listed package list.
8487      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
8488      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
8489      * @throws SecurityException if {@code admin} is not a profile owner.
8490      */
getCrossProfileWidgetProviders(@onNull ComponentName admin)8491     public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
8492         throwIfParentInstance("getCrossProfileWidgetProviders");
8493         if (mService != null) {
8494             try {
8495                 List<String> providers = mService.getCrossProfileWidgetProviders(admin);
8496                 if (providers != null) {
8497                     return providers;
8498                 }
8499             } catch (RemoteException re) {
8500                 throw re.rethrowFromSystemServer();
8501             }
8502         }
8503         return Collections.emptyList();
8504     }
8505 
8506     /**
8507      * Called by profile or device owners to set the user's photo.
8508      *
8509      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8510      * @param icon the bitmap to set as the photo.
8511      * @throws SecurityException if {@code admin} is not a device or profile owner.
8512      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)8513     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
8514         throwIfParentInstance("setUserIcon");
8515         try {
8516             mService.setUserIcon(admin, icon);
8517         } catch (RemoteException re) {
8518             throw re.rethrowFromSystemServer();
8519         }
8520     }
8521 
8522     /**
8523      * Called by device owners to set a local system update policy. When a new policy is set,
8524      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
8525      * <p>
8526      * If the supplied system update policy has freeze periods set but the freeze periods do not
8527      * meet 90-day maximum length or 60-day minimum separation requirement set out in
8528      * {@link SystemUpdatePolicy#setFreezePeriods},
8529      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
8530      * keeps a record of freeze periods the device experienced previously, and combines them with
8531      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
8532      * separation constraints. As a result, freeze periods that passed validation during
8533      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
8534      * the freeze period history. If this is causing issues during development,
8535      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
8536      *
8537      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
8538      *            components in the device owner package can set system update policies and the most
8539      *            recent policy takes effect.
8540      * @param policy the new policy, or {@code null} to clear the current policy.
8541      * @throws SecurityException if {@code admin} is not a device owner.
8542      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
8543      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
8544      *             meet the requirement.
8545      * @see SystemUpdatePolicy
8546      * @see SystemUpdatePolicy#setFreezePeriods(List)
8547      */
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)8548     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
8549         throwIfParentInstance("setSystemUpdatePolicy");
8550         if (mService != null) {
8551             try {
8552                 mService.setSystemUpdatePolicy(admin, policy);
8553             } catch (RemoteException re) {
8554                 throw re.rethrowFromSystemServer();
8555             }
8556         }
8557     }
8558 
8559     /**
8560      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
8561      *
8562      * @return The current policy object, or {@code null} if no policy is set.
8563      */
getSystemUpdatePolicy()8564     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
8565         throwIfParentInstance("getSystemUpdatePolicy");
8566         if (mService != null) {
8567             try {
8568                 return mService.getSystemUpdatePolicy();
8569             } catch (RemoteException re) {
8570                 throw re.rethrowFromSystemServer();
8571             }
8572         }
8573         return null;
8574     }
8575 
8576     /**
8577      * Reset record of previous system update freeze period the device went through.
8578      * Only callable by ADB.
8579      * @hide
8580      */
clearSystemUpdatePolicyFreezePeriodRecord()8581     public void clearSystemUpdatePolicyFreezePeriodRecord() {
8582         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
8583         if (mService == null) {
8584             return;
8585         }
8586         try {
8587             mService.clearSystemUpdatePolicyFreezePeriodRecord();
8588         } catch (RemoteException re) {
8589             throw re.rethrowFromSystemServer();
8590         }
8591     }
8592 
8593     /**
8594      * Called by a device owner or profile owner of secondary users that is affiliated with the
8595      * device to disable the keyguard altogether.
8596      * <p>
8597      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
8598      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
8599      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
8600      * disabled.
8601      *
8602      * <p>
8603      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
8604      * keyguard if it is currently shown.
8605      *
8606      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8607      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
8608      * @return {@code false} if attempting to disable the keyguard while a lock password was in
8609      *         place. {@code true} otherwise.
8610      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
8611      * secondary user that is affiliated with the device.
8612      * @see #isAffiliatedUser
8613      * @see #getSecondaryUsers
8614      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)8615     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
8616         throwIfParentInstance("setKeyguardDisabled");
8617         try {
8618             return mService.setKeyguardDisabled(admin, disabled);
8619         } catch (RemoteException re) {
8620             throw re.rethrowFromSystemServer();
8621         }
8622     }
8623 
8624     /**
8625      * Called by device owner or profile owner of secondary users  that is affiliated with the
8626      * device to disable the status bar. Disabling the status bar blocks notifications, quick
8627      * settings and other screen overlays that allow escaping from a single use device.
8628      * <p>
8629      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
8630      * status bar in LockTask mode can be configured with
8631      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
8632      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
8633      * mode.
8634      *
8635      * <p>This policy does not have any effect while on the lock screen, where the status bar will
8636      * not be disabled. Using LockTask instead of this method is recommended.
8637      *
8638      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8639      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
8640      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
8641      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
8642      * secondary user that is affiliated with the device.
8643      * @see #isAffiliatedUser
8644      * @see #getSecondaryUsers
8645      */
setStatusBarDisabled(@onNull ComponentName admin, boolean disabled)8646     public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
8647         throwIfParentInstance("setStatusBarDisabled");
8648         try {
8649             return mService.setStatusBarDisabled(admin, disabled);
8650         } catch (RemoteException re) {
8651             throw re.rethrowFromSystemServer();
8652         }
8653     }
8654 
8655     /**
8656      * Called by the system update service to notify device and profile owners of pending system
8657      * updates.
8658      *
8659      * This method should only be used when it is unknown whether the pending system
8660      * update is a security patch. Otherwise, use
8661      * {@link #notifyPendingSystemUpdate(long, boolean)}.
8662      *
8663      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
8664      *         indicating when the current pending update was first available. {@code -1} if no
8665      *         update is available.
8666      * @see #notifyPendingSystemUpdate(long, boolean)
8667      * @hide
8668      */
8669     @SystemApi
8670     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)8671     public void notifyPendingSystemUpdate(long updateReceivedTime) {
8672         throwIfParentInstance("notifyPendingSystemUpdate");
8673         if (mService != null) {
8674             try {
8675                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
8676             } catch (RemoteException re) {
8677                 throw re.rethrowFromSystemServer();
8678             }
8679         }
8680     }
8681 
8682     /**
8683      * Called by the system update service to notify device and profile owners of pending system
8684      * updates.
8685      *
8686      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
8687      * when it is known whether the pending system update is a security patch.
8688      *
8689      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
8690      *         indicating when the current pending update was first available. {@code -1} if no
8691      *         update is available.
8692      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
8693      *         {@code false} if not.
8694      * @see #notifyPendingSystemUpdate(long)
8695      * @hide
8696      */
8697     @SystemApi
8698     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)8699     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
8700         throwIfParentInstance("notifyPendingSystemUpdate");
8701         if (mService != null) {
8702             try {
8703                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
8704                         isSecurityPatch));
8705             } catch (RemoteException re) {
8706                 throw re.rethrowFromSystemServer();
8707             }
8708         }
8709     }
8710 
8711     /**
8712      * Called by device or profile owners to get information about a pending system update.
8713      *
8714      * @param admin Which profile or device owner this request is associated with.
8715      * @return Information about a pending system update or {@code null} if no update pending.
8716      * @throws SecurityException if {@code admin} is not a device or profile owner.
8717      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
8718      */
getPendingSystemUpdate(@onNull ComponentName admin)8719     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
8720         throwIfParentInstance("getPendingSystemUpdate");
8721         try {
8722             return mService.getPendingSystemUpdate(admin);
8723         } catch (RemoteException re) {
8724             throw re.rethrowFromSystemServer();
8725         }
8726     }
8727 
8728     /**
8729      * Set the default response for future runtime permission requests by applications. This
8730      * function can be called by a device owner, profile owner, or by a delegate given the
8731      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
8732      * The policy can allow for normal operation which prompts the user to grant a permission, or
8733      * can allow automatic granting or denying of runtime permission requests by an application.
8734      * This also applies to new permissions declared by app updates. When a permission is denied or
8735      * granted this way, the effect is equivalent to setting the permission * grant state via
8736      * {@link #setPermissionGrantState}.
8737      * <p/>
8738      * As this policy only acts on runtime permission requests, it only applies to applications
8739      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
8740      *
8741      * @param admin Which profile or device owner this request is associated with.
8742      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
8743      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
8744      * @throws SecurityException if {@code admin} is not a device or profile owner.
8745      * @see #setPermissionGrantState
8746      * @see #setDelegatedScopes
8747      * @see #DELEGATION_PERMISSION_GRANT
8748      */
setPermissionPolicy(@onNull ComponentName admin, int policy)8749     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
8750         throwIfParentInstance("setPermissionPolicy");
8751         try {
8752             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
8753         } catch (RemoteException re) {
8754             throw re.rethrowFromSystemServer();
8755         }
8756     }
8757 
8758     /**
8759      * Returns the current runtime permission policy set by the device or profile owner. The
8760      * default is {@link #PERMISSION_POLICY_PROMPT}.
8761      *
8762      * @param admin Which profile or device owner this request is associated with.
8763      * @return the current policy for future permission requests.
8764      */
getPermissionPolicy(ComponentName admin)8765     public int getPermissionPolicy(ComponentName admin) {
8766         throwIfParentInstance("getPermissionPolicy");
8767         try {
8768             return mService.getPermissionPolicy(admin);
8769         } catch (RemoteException re) {
8770             throw re.rethrowFromSystemServer();
8771         }
8772     }
8773 
8774     /**
8775      * Sets the grant state of a runtime permission for a specific application. The state can be
8776      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
8777      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
8778      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
8779      * the permission is granted and the user cannot manage it through the UI. This method can only
8780      * be called by a profile owner, device owner, or a delegate given the
8781      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
8782      * <p/>
8783      * Note that user cannot manage other permissions in the affected group through the UI
8784      * either and their granted state will be kept as the current value. Thus, it's recommended that
8785      * you set the grant state of all the permissions in the affected group.
8786      * <p/>
8787      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
8788      * the permission. It retains the previous grant, if any.
8789      * <p/>
8790      * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
8791      * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
8792      * &lt; {@link android.os.Build.VERSION_CODES#M}.
8793      * <p/>
8794      * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
8795      * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
8796      * application built with a {@code targetSdkVersion} &lt;
8797      * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
8798      * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
8799      *
8800      * @param admin Which profile or device owner this request is associated with.
8801      * @param packageName The application to grant or revoke a permission to.
8802      * @param permission The permission to grant or revoke.
8803      * @param grantState The permission grant state which is one of
8804      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
8805      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
8806      * @return whether the permission was successfully granted or revoked.
8807      * @throws SecurityException if {@code admin} is not a device or profile owner.
8808      * @see #PERMISSION_GRANT_STATE_DENIED
8809      * @see #PERMISSION_GRANT_STATE_DEFAULT
8810      * @see #PERMISSION_GRANT_STATE_GRANTED
8811      * @see #setDelegatedScopes
8812      * @see #DELEGATION_PERMISSION_GRANT
8813      */
setPermissionGrantState(@onNull ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)8814     public boolean setPermissionGrantState(@NonNull ComponentName admin,
8815             @NonNull String packageName, @NonNull String permission,
8816             @PermissionGrantState int grantState) {
8817         throwIfParentInstance("setPermissionGrantState");
8818         try {
8819             CompletableFuture<Boolean> result = new CompletableFuture<>();
8820 
8821             mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
8822                     permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
8823 
8824             // Timeout
8825             BackgroundThread.getHandler().sendMessageDelayed(
8826                     obtainMessage(CompletableFuture::complete, result, false),
8827                     20_000);
8828 
8829             return result.get();
8830         } catch (RemoteException re) {
8831             throw re.rethrowFromSystemServer();
8832         } catch (InterruptedException | ExecutionException e) {
8833             throw new RuntimeException(e);
8834         }
8835     }
8836 
8837     /**
8838      * Returns the current grant state of a runtime permission for a specific application. This
8839      * function can be called by a device owner, profile owner, or by a delegate given the
8840      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
8841      *
8842      * @param admin Which profile or device owner this request is associated with, or {@code null}
8843      *            if the caller is a permission grant delegate.
8844      * @param packageName The application to check the grant state for.
8845      * @param permission The permission to check for.
8846      * @return the current grant state specified by device policy. If the profile or device owner
8847      *         has not set a grant state, the return value is
8848      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
8849      *         permission is currently granted for the package.
8850      *         <p/>
8851      *         If a grant state was set by the profile or device owner, then the return value will
8852      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
8853      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
8854      *         currently denied or granted.
8855      * @throws SecurityException if {@code admin} is not a device or profile owner.
8856      * @see #setPermissionGrantState(ComponentName, String, String, int)
8857      * @see PackageManager#checkPermission(String, String)
8858      * @see #setDelegatedScopes
8859      * @see #DELEGATION_PERMISSION_GRANT
8860      */
getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)8861     public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
8862             @NonNull String packageName, @NonNull String permission) {
8863         throwIfParentInstance("getPermissionGrantState");
8864         try {
8865             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
8866                     permission);
8867         } catch (RemoteException re) {
8868             throw re.rethrowFromSystemServer();
8869         }
8870     }
8871 
8872     /**
8873      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
8874      * or device, setting itself as the device or profile owner.
8875      *
8876      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
8877      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
8878      * @return whether provisioning a managed profile or device is possible.
8879      * @throws IllegalArgumentException if the supplied action is not valid.
8880      */
isProvisioningAllowed(@onNull String action)8881     public boolean isProvisioningAllowed(@NonNull String action) {
8882         throwIfParentInstance("isProvisioningAllowed");
8883         try {
8884             return mService.isProvisioningAllowed(action, mContext.getPackageName());
8885         } catch (RemoteException re) {
8886             throw re.rethrowFromSystemServer();
8887         }
8888     }
8889 
8890     /**
8891      * Checks whether it is possible to initiate provisioning a managed device,
8892      * profile or user, setting the given package as owner.
8893      *
8894      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
8895      *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
8896      *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
8897      *        {@link #ACTION_PROVISION_MANAGED_USER}
8898      * @param packageName The package of the component that would be set as device, user, or profile
8899      *        owner.
8900      * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
8901      * @hide
8902      */
checkProvisioningPreCondition( String action, @NonNull String packageName)8903     public @ProvisioningPreCondition int checkProvisioningPreCondition(
8904             String action, @NonNull String packageName) {
8905         try {
8906             return mService.checkProvisioningPreCondition(action, packageName);
8907         } catch (RemoteException re) {
8908             throw re.rethrowFromSystemServer();
8909         }
8910     }
8911 
8912     /**
8913      * Return if this user is a managed profile of another user. An admin can become the profile
8914      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
8915      * user with {@link #createAndManageUser}
8916      * @param admin Which profile owner this request is associated with.
8917      * @return if this user is a managed profile of another user.
8918      */
isManagedProfile(@onNull ComponentName admin)8919     public boolean isManagedProfile(@NonNull ComponentName admin) {
8920         throwIfParentInstance("isManagedProfile");
8921         try {
8922             return mService.isManagedProfile(admin);
8923         } catch (RemoteException re) {
8924             throw re.rethrowFromSystemServer();
8925         }
8926     }
8927 
8928     /**
8929      * @hide
8930      * Return if this user is a system-only user. An admin can manage a device from a system only
8931      * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
8932      * @param admin Which device owner this request is associated with.
8933      * @return if this user is a system-only user.
8934      */
isSystemOnlyUser(@onNull ComponentName admin)8935     public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
8936         try {
8937             return mService.isSystemOnlyUser(admin);
8938         } catch (RemoteException re) {
8939             throw re.rethrowFromSystemServer();
8940         }
8941     }
8942 
8943     /**
8944      * Called by device owner to get the MAC address of the Wi-Fi device.
8945      *
8946      * @param admin Which device owner this request is associated with.
8947      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
8948      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
8949      *         <p>
8950      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
8951      * @throws SecurityException if {@code admin} is not a device owner.
8952      */
getWifiMacAddress(@onNull ComponentName admin)8953     public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
8954         throwIfParentInstance("getWifiMacAddress");
8955         try {
8956             return mService.getWifiMacAddress(admin);
8957         } catch (RemoteException re) {
8958             throw re.rethrowFromSystemServer();
8959         }
8960     }
8961 
8962     /**
8963      * Called by device owner to reboot the device. If there is an ongoing call on the device,
8964      * throws an {@link IllegalStateException}.
8965      * @param admin Which device owner the request is associated with.
8966      * @throws IllegalStateException if device has an ongoing call.
8967      * @throws SecurityException if {@code admin} is not a device owner.
8968      * @see TelephonyManager#CALL_STATE_IDLE
8969      */
reboot(@onNull ComponentName admin)8970     public void reboot(@NonNull ComponentName admin) {
8971         throwIfParentInstance("reboot");
8972         try {
8973             mService.reboot(admin);
8974         } catch (RemoteException re) {
8975             throw re.rethrowFromSystemServer();
8976         }
8977     }
8978 
8979     /**
8980      * Called by a device admin to set the short support message. This will be displayed to the user
8981      * in settings screens where funtionality has been disabled by the admin. The message should be
8982      * limited to a short statement such as "This setting is disabled by your administrator. Contact
8983      * someone@example.com for support." If the message is longer than 200 characters it may be
8984      * truncated.
8985      * <p>
8986      * If the short support message needs to be localized, it is the responsibility of the
8987      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
8988      * and set a new version of this string accordingly.
8989      *
8990      * @see #setLongSupportMessage
8991      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8992      * @param message Short message to be displayed to the user in settings or null to clear the
8993      *            existing message.
8994      * @throws SecurityException if {@code admin} is not an active administrator.
8995      */
setShortSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)8996     public void setShortSupportMessage(@NonNull ComponentName admin,
8997             @Nullable CharSequence message) {
8998         throwIfParentInstance("setShortSupportMessage");
8999         if (mService != null) {
9000             try {
9001                 mService.setShortSupportMessage(admin, message);
9002             } catch (RemoteException e) {
9003                 throw e.rethrowFromSystemServer();
9004             }
9005         }
9006     }
9007 
9008     /**
9009      * Called by a device admin to get the short support message.
9010      *
9011      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9012      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
9013      *         null if no message has been set.
9014      * @throws SecurityException if {@code admin} is not an active administrator.
9015      */
getShortSupportMessage(@onNull ComponentName admin)9016     public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
9017         throwIfParentInstance("getShortSupportMessage");
9018         if (mService != null) {
9019             try {
9020                 return mService.getShortSupportMessage(admin);
9021             } catch (RemoteException e) {
9022                 throw e.rethrowFromSystemServer();
9023             }
9024         }
9025         return null;
9026     }
9027 
9028     /**
9029      * Called by a device admin to set the long support message. This will be displayed to the user
9030      * in the device administators settings screen.
9031      * <p>
9032      * If the long support message needs to be localized, it is the responsibility of the
9033      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9034      * and set a new version of this string accordingly.
9035      *
9036      * @see #setShortSupportMessage
9037      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9038      * @param message Long message to be displayed to the user in settings or null to clear the
9039      *            existing message.
9040      * @throws SecurityException if {@code admin} is not an active administrator.
9041      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)9042     public void setLongSupportMessage(@NonNull ComponentName admin,
9043             @Nullable CharSequence message) {
9044         throwIfParentInstance("setLongSupportMessage");
9045         if (mService != null) {
9046             try {
9047                 mService.setLongSupportMessage(admin, message);
9048             } catch (RemoteException e) {
9049                 throw e.rethrowFromSystemServer();
9050             }
9051         }
9052     }
9053 
9054     /**
9055      * Called by a device admin to get the long support message.
9056      *
9057      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9058      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
9059      *         null if no message has been set.
9060      * @throws SecurityException if {@code admin} is not an active administrator.
9061      */
getLongSupportMessage(@onNull ComponentName admin)9062     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
9063         throwIfParentInstance("getLongSupportMessage");
9064         if (mService != null) {
9065             try {
9066                 return mService.getLongSupportMessage(admin);
9067             } catch (RemoteException e) {
9068                 throw e.rethrowFromSystemServer();
9069             }
9070         }
9071         return null;
9072     }
9073 
9074     /**
9075      * Called by the system to get the short support message.
9076      *
9077      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9078      * @param userHandle user id the admin is running as.
9079      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
9080      *
9081      * @hide
9082      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)9083     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
9084             int userHandle) {
9085         if (mService != null) {
9086             try {
9087                 return mService.getShortSupportMessageForUser(admin, userHandle);
9088             } catch (RemoteException e) {
9089                 throw e.rethrowFromSystemServer();
9090             }
9091         }
9092         return null;
9093     }
9094 
9095 
9096     /**
9097      * Called by the system to get the long support message.
9098      *
9099      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9100      * @param userHandle user id the admin is running as.
9101      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
9102      *
9103      * @hide
9104      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)9105     public @Nullable CharSequence getLongSupportMessageForUser(
9106             @NonNull ComponentName admin, int userHandle) {
9107         if (mService != null) {
9108             try {
9109                 return mService.getLongSupportMessageForUser(admin, userHandle);
9110             } catch (RemoteException e) {
9111                 throw e.rethrowFromSystemServer();
9112             }
9113         }
9114         return null;
9115     }
9116 
9117     /**
9118      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
9119      * whose calls act on the parent profile.
9120      *
9121      * <p>The following methods are supported for the parent instance, all other methods will
9122      * throw a SecurityException when called on the parent instance:
9123      * <ul>
9124      * <li>{@link #getPasswordQuality}</li>
9125      * <li>{@link #setPasswordQuality}</li>
9126      * <li>{@link #getPasswordMinimumLength}</li>
9127      * <li>{@link #setPasswordMinimumLength}</li>
9128      * <li>{@link #getPasswordMinimumUpperCase}</li>
9129      * <li>{@link #setPasswordMinimumUpperCase}</li>
9130      * <li>{@link #getPasswordMinimumLowerCase}</li>
9131      * <li>{@link #setPasswordMinimumLowerCase}</li>
9132      * <li>{@link #getPasswordMinimumLetters}</li>
9133      * <li>{@link #setPasswordMinimumLetters}</li>
9134      * <li>{@link #getPasswordMinimumNumeric}</li>
9135      * <li>{@link #setPasswordMinimumNumeric}</li>
9136      * <li>{@link #getPasswordMinimumSymbols}</li>
9137      * <li>{@link #setPasswordMinimumSymbols}</li>
9138      * <li>{@link #getPasswordMinimumNonLetter}</li>
9139      * <li>{@link #setPasswordMinimumNonLetter}</li>
9140      * <li>{@link #getPasswordHistoryLength}</li>
9141      * <li>{@link #setPasswordHistoryLength}</li>
9142      * <li>{@link #getPasswordExpirationTimeout}</li>
9143      * <li>{@link #setPasswordExpirationTimeout}</li>
9144      * <li>{@link #getPasswordExpiration}</li>
9145      * <li>{@link #getPasswordMaximumLength}</li>
9146      * <li>{@link #isActivePasswordSufficient}</li>
9147      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
9148      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
9149      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
9150      * <li>{@link #getMaximumTimeToLock}</li>
9151      * <li>{@link #setMaximumTimeToLock}</li>
9152      * <li>{@link #lockNow}</li>
9153      * <li>{@link #getKeyguardDisabledFeatures}</li>
9154      * <li>{@link #setKeyguardDisabledFeatures}</li>
9155      * <li>{@link #getTrustAgentConfiguration}</li>
9156      * <li>{@link #setTrustAgentConfiguration}</li>
9157      * <li>{@link #getRequiredStrongAuthTimeout}</li>
9158      * <li>{@link #setRequiredStrongAuthTimeout}</li>
9159      * </ul>
9160      *
9161      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
9162      * @throws SecurityException if {@code admin} is not a profile owner.
9163      */
getParentProfileInstance(@onNull ComponentName admin)9164     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
9165         throwIfParentInstance("getParentProfileInstance");
9166         try {
9167             if (!mService.isManagedProfile(admin)) {
9168                 throw new SecurityException("The current user does not have a parent profile.");
9169             }
9170             return new DevicePolicyManager(mContext, mService, true);
9171         } catch (RemoteException e) {
9172             throw e.rethrowFromSystemServer();
9173         }
9174     }
9175 
9176     /**
9177      * Called by device owner to control the security logging feature.
9178      *
9179      * <p> Security logs contain various information intended for security auditing purposes.
9180      * See {@link SecurityEvent} for details.
9181      *
9182      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
9183      * are unaffiliated secondary users or profiles on the device, regardless of whether the
9184      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
9185      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
9186      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
9187      *
9188      * @param admin Which device owner this request is associated with.
9189      * @param enabled whether security logging should be enabled or not.
9190      * @throws SecurityException if {@code admin} is not a device owner.
9191      * @see #setAffiliationIds
9192      * @see #retrieveSecurityLogs
9193      */
setSecurityLoggingEnabled(@onNull ComponentName admin, boolean enabled)9194     public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
9195         throwIfParentInstance("setSecurityLoggingEnabled");
9196         try {
9197             mService.setSecurityLoggingEnabled(admin, enabled);
9198         } catch (RemoteException re) {
9199             throw re.rethrowFromSystemServer();
9200         }
9201     }
9202 
9203     /**
9204      * Return whether security logging is enabled or not by the device owner.
9205      *
9206      * <p>Can only be called by the device owner, otherwise a {@link SecurityException} will be
9207      * thrown.
9208      *
9209      * @param admin Which device owner this request is associated with.
9210      * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
9211      * @throws SecurityException if {@code admin} is not a device owner.
9212      */
isSecurityLoggingEnabled(@ullable ComponentName admin)9213     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
9214         throwIfParentInstance("isSecurityLoggingEnabled");
9215         try {
9216             return mService.isSecurityLoggingEnabled(admin);
9217         } catch (RemoteException re) {
9218             throw re.rethrowFromSystemServer();
9219         }
9220     }
9221 
9222     /**
9223      * Called by device owner to retrieve all new security logging entries since the last call to
9224      * this API after device boots.
9225      *
9226      * <p> Access to the logs is rate limited and it will only return new logs after the device
9227      * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
9228      *
9229      * <p>If there is any other user or profile on the device, it must be affiliated with the
9230      * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
9231      *
9232      * @param admin Which device owner this request is associated with.
9233      * @return the new batch of security logs which is a list of {@link SecurityEvent},
9234      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
9235      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
9236      * profile or secondary user that is not affiliated with the device.
9237      * @see #isAffiliatedUser
9238      * @see DeviceAdminReceiver#onSecurityLogsAvailable
9239      */
retrieveSecurityLogs(@onNull ComponentName admin)9240     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
9241         throwIfParentInstance("retrieveSecurityLogs");
9242         try {
9243             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
9244             if (list != null) {
9245                 return list.getList();
9246             } else {
9247                 // Rate limit exceeded.
9248                 return null;
9249             }
9250         } catch (RemoteException re) {
9251             throw re.rethrowFromSystemServer();
9252         }
9253     }
9254 
9255     /**
9256      * Makes all accumulated network logs available to DPC in a new batch.
9257      * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
9258      * @hide
9259      */
forceNetworkLogs()9260     public long forceNetworkLogs() {
9261         if (mService == null) {
9262             return -1;
9263         }
9264         try {
9265             return mService.forceNetworkLogs();
9266         } catch (RemoteException re) {
9267             throw re.rethrowFromSystemServer();
9268         }
9269     }
9270 
9271     /**
9272      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
9273      * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
9274      * @hide
9275      */
forceSecurityLogs()9276     public long forceSecurityLogs() {
9277         if (mService == null) {
9278             return 0;
9279         }
9280         try {
9281             return mService.forceSecurityLogs();
9282         } catch (RemoteException re) {
9283             throw re.rethrowFromSystemServer();
9284         }
9285     }
9286 
9287     /**
9288      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
9289      * profile.
9290      *
9291      * @hide
9292      */
getParentProfileInstance(UserInfo uInfo)9293     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
9294         mContext.checkSelfPermission(
9295                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
9296         if (!uInfo.isManagedProfile()) {
9297             throw new SecurityException("The user " + uInfo.id
9298                     + " does not have a parent profile.");
9299         }
9300         return new DevicePolicyManager(mContext, mService, true);
9301     }
9302 
9303     /**
9304      * Called by a device or profile owner to restrict packages from using metered data.
9305      *
9306      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9307      * @param packageNames the list of package names to be restricted.
9308      * @return a list of package names which could not be restricted.
9309      * @throws SecurityException if {@code admin} is not a device or profile owner.
9310      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)9311     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
9312             @NonNull List<String> packageNames) {
9313         throwIfParentInstance("setMeteredDataDisabled");
9314         if (mService != null) {
9315             try {
9316                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
9317             } catch (RemoteException re) {
9318                 throw re.rethrowFromSystemServer();
9319             }
9320         }
9321         return packageNames;
9322     }
9323 
9324     /**
9325      * Called by a device or profile owner to retrieve the list of packages which are restricted
9326      * by the admin from using metered data.
9327      *
9328      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9329      * @return the list of restricted package names.
9330      * @throws SecurityException if {@code admin} is not a device or profile owner.
9331      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)9332     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
9333         throwIfParentInstance("getMeteredDataDisabled");
9334         if (mService != null) {
9335             try {
9336                 return mService.getMeteredDataDisabledPackages(admin);
9337             } catch (RemoteException re) {
9338                 throw re.rethrowFromSystemServer();
9339             }
9340         }
9341         return new ArrayList<>();
9342     }
9343 
9344     /**
9345      * Called by the system to check if a package is restricted from using metered data
9346      * by {@param admin}.
9347      *
9348      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9349      * @param packageName the package whose restricted status is needed.
9350      * @param userId the user to which {@param packageName} belongs.
9351      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
9352      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
9353      * @hide
9354      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)9355     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
9356             String packageName, @UserIdInt int userId) {
9357         throwIfParentInstance("getMeteredDataDisabledForUser");
9358         if (mService != null) {
9359             try {
9360                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
9361             } catch (RemoteException re) {
9362                 throw re.rethrowFromSystemServer();
9363             }
9364         }
9365         return false;
9366     }
9367 
9368     /**
9369      * Called by device owners to retrieve device logs from before the device's last reboot.
9370      * <p>
9371      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
9372      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
9373      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
9374      * about data corruption when parsing. </strong>
9375      *
9376      * <p>If there is any other user or profile on the device, it must be affiliated with the
9377      * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
9378      *
9379      * @param admin Which device owner this request is associated with.
9380      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
9381      *         is not supported on the device.
9382      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
9383      * profile or secondary user that is not affiliated with the device.
9384      * @see #isAffiliatedUser
9385      * @see #retrieveSecurityLogs
9386      */
retrievePreRebootSecurityLogs( @onNull ComponentName admin)9387     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
9388             @NonNull ComponentName admin) {
9389         throwIfParentInstance("retrievePreRebootSecurityLogs");
9390         try {
9391             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
9392             if (list != null) {
9393                 return list.getList();
9394             } else {
9395                 return null;
9396             }
9397         } catch (RemoteException re) {
9398             throw re.rethrowFromSystemServer();
9399         }
9400     }
9401 
9402     /**
9403      * Called by a profile owner of a managed profile to set the color used for customization. This
9404      * color is used as background color of the confirm credentials screen for that user. The
9405      * default color is teal (#00796B).
9406      * <p>
9407      * The confirm credentials screen can be created using
9408      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
9409      *
9410      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9411      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
9412      * @throws SecurityException if {@code admin} is not a profile owner.
9413      */
setOrganizationColor(@onNull ComponentName admin, int color)9414     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
9415         throwIfParentInstance("setOrganizationColor");
9416         try {
9417             // always enforce alpha channel to have 100% opacity
9418             color |= 0xFF000000;
9419             mService.setOrganizationColor(admin, color);
9420         } catch (RemoteException re) {
9421             throw re.rethrowFromSystemServer();
9422         }
9423     }
9424 
9425     /**
9426      * @hide
9427      *
9428      * Sets the color used for customization.
9429      *
9430      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
9431      * @param userId which user to set the color to.
9432      * @RequiresPermission(allOf = {
9433      *       Manifest.permission.MANAGE_USERS,
9434      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
9435      */
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)9436     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
9437         try {
9438             // always enforce alpha channel to have 100% opacity
9439             color |= 0xFF000000;
9440             mService.setOrganizationColorForUser(color, userId);
9441         } catch (RemoteException re) {
9442             throw re.rethrowFromSystemServer();
9443         }
9444     }
9445 
9446     /**
9447      * Called by a profile owner of a managed profile to retrieve the color used for customization.
9448      * This color is used as background color of the confirm credentials screen for that user.
9449      *
9450      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9451      * @return The 24bit (0xRRGGBB) representation of the color to be used.
9452      * @throws SecurityException if {@code admin} is not a profile owner.
9453      */
getOrganizationColor(@onNull ComponentName admin)9454     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
9455         throwIfParentInstance("getOrganizationColor");
9456         try {
9457             return mService.getOrganizationColor(admin);
9458         } catch (RemoteException re) {
9459             throw re.rethrowFromSystemServer();
9460         }
9461     }
9462 
9463     /**
9464      * @hide
9465      * Retrieve the customization color for a given user.
9466      *
9467      * @param userHandle The user id of the user we're interested in.
9468      * @return The 24bit (0xRRGGBB) representation of the color to be used.
9469      */
getOrganizationColorForUser(int userHandle)9470     public @ColorInt int getOrganizationColorForUser(int userHandle) {
9471         try {
9472             return mService.getOrganizationColorForUser(userHandle);
9473         } catch (RemoteException re) {
9474             throw re.rethrowFromSystemServer();
9475         }
9476     }
9477 
9478     /**
9479      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
9480      * the organization under management.
9481      *
9482      * <p>If the organization name needs to be localized, it is the responsibility of the {@link
9483      * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
9484      * a new version of this string accordingly.
9485      *
9486      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9487      * @param title The organization name or {@code null} to clear a previously set name.
9488      * @throws SecurityException if {@code admin} is not a device or profile owner.
9489      */
setOrganizationName(@onNull ComponentName admin, @Nullable CharSequence title)9490     public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
9491         throwIfParentInstance("setOrganizationName");
9492         try {
9493             mService.setOrganizationName(admin, title);
9494         } catch (RemoteException re) {
9495             throw re.rethrowFromSystemServer();
9496         }
9497     }
9498 
9499     /**
9500      * Called by a profile owner of a managed profile to retrieve the name of the organization under
9501      * management.
9502      *
9503      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9504      * @return The organization name or {@code null} if none is set.
9505      * @throws SecurityException if {@code admin} is not a profile owner.
9506      */
getOrganizationName(@onNull ComponentName admin)9507     public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
9508         throwIfParentInstance("getOrganizationName");
9509         try {
9510             return mService.getOrganizationName(admin);
9511         } catch (RemoteException re) {
9512             throw re.rethrowFromSystemServer();
9513         }
9514     }
9515 
9516     /**
9517      * Called by the system to retrieve the name of the organization managing the device.
9518      *
9519      * @return The organization name or {@code null} if none is set.
9520      * @throws SecurityException if the caller is not the device owner, does not hold the
9521      *         MANAGE_USERS permission and is not the system.
9522      *
9523      * @hide
9524      */
9525     @SystemApi
9526     @TestApi
9527     @SuppressLint("Doclava125")
getDeviceOwnerOrganizationName()9528     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
9529         try {
9530             return mService.getDeviceOwnerOrganizationName();
9531         } catch (RemoteException re) {
9532             throw re.rethrowFromSystemServer();
9533         }
9534     }
9535 
9536     /**
9537      * Retrieve the default title message used in the confirm credentials screen for a given user.
9538      *
9539      * @param userHandle The user id of the user we're interested in.
9540      * @return The organization name or {@code null} if none is set.
9541      *
9542      * @hide
9543      */
getOrganizationNameForUser(int userHandle)9544     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
9545         try {
9546             return mService.getOrganizationNameForUser(userHandle);
9547         } catch (RemoteException re) {
9548             throw re.rethrowFromSystemServer();
9549         }
9550     }
9551 
9552     /**
9553      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
9554      *         return {@link #STATE_USER_UNMANAGED}
9555      * @hide
9556      */
9557     @SystemApi
9558     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
9559     @UserProvisioningState
getUserProvisioningState()9560     public int getUserProvisioningState() {
9561         throwIfParentInstance("getUserProvisioningState");
9562         if (mService != null) {
9563             try {
9564                 return mService.getUserProvisioningState();
9565             } catch (RemoteException e) {
9566                 throw e.rethrowFromSystemServer();
9567             }
9568         }
9569         return STATE_USER_UNMANAGED;
9570     }
9571 
9572     /**
9573      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
9574      *
9575      * @param state to store
9576      * @param userHandle for user
9577      * @hide
9578      */
setUserProvisioningState(@serProvisioningState int state, int userHandle)9579     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
9580         if (mService != null) {
9581             try {
9582                 mService.setUserProvisioningState(state, userHandle);
9583             } catch (RemoteException e) {
9584                 throw e.rethrowFromSystemServer();
9585             }
9586         }
9587     }
9588 
9589     /**
9590      * Indicates the entity that controls the device or profile owner. Two users/profiles are
9591      * affiliated if the set of ids set by their device or profile owners intersect.
9592      *
9593      * <p>A user/profile that is affiliated with the device owner user is considered to be
9594      * affiliated with the device.
9595      *
9596      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
9597      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user or profile
9598      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
9599      * affiliation ids are set by its profile owner as soon as possible after the user/profile is
9600      * created.
9601      *
9602      * @param admin Which profile or device owner this request is associated with.
9603      * @param ids A set of opaque non-empty affiliation ids.
9604      *
9605      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
9606      * @see #isAffiliatedUser
9607      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)9608     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
9609         throwIfParentInstance("setAffiliationIds");
9610         if (ids == null) {
9611             throw new IllegalArgumentException("ids must not be null");
9612         }
9613         try {
9614             mService.setAffiliationIds(admin, new ArrayList<>(ids));
9615         } catch (RemoteException e) {
9616             throw e.rethrowFromSystemServer();
9617         }
9618     }
9619 
9620     /**
9621      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
9622      * empty set if none have been set.
9623      */
getAffiliationIds(@onNull ComponentName admin)9624     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
9625         throwIfParentInstance("getAffiliationIds");
9626         try {
9627             return new ArraySet<>(mService.getAffiliationIds(admin));
9628         } catch (RemoteException e) {
9629             throw e.rethrowFromSystemServer();
9630         }
9631     }
9632 
9633     /**
9634      * Returns whether this user/profile is affiliated with the device.
9635      * <p>
9636      * By definition, the user that the device owner runs on is always affiliated with the device.
9637      * Any other user/profile is considered affiliated with the device if the set specified by its
9638      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
9639      * @see #setAffiliationIds
9640      */
isAffiliatedUser()9641     public boolean isAffiliatedUser() {
9642         throwIfParentInstance("isAffiliatedUser");
9643         try {
9644             return mService.isAffiliatedUser();
9645         } catch (RemoteException e) {
9646             throw e.rethrowFromSystemServer();
9647         }
9648     }
9649 
9650     /**
9651      * @hide
9652      * Returns whether the uninstall for {@code packageName} for the current user is in queue
9653      * to be started
9654      * @param packageName the package to check for
9655      * @return whether the uninstall intent for {@code packageName} is pending
9656      */
isUninstallInQueue(String packageName)9657     public boolean isUninstallInQueue(String packageName) {
9658         try {
9659             return mService.isUninstallInQueue(packageName);
9660         } catch (RemoteException re) {
9661             throw re.rethrowFromSystemServer();
9662         }
9663     }
9664 
9665     /**
9666      * @hide
9667      * @param packageName the package containing active DAs to be uninstalled
9668      */
uninstallPackageWithActiveAdmins(String packageName)9669     public void uninstallPackageWithActiveAdmins(String packageName) {
9670         try {
9671             mService.uninstallPackageWithActiveAdmins(packageName);
9672         } catch (RemoteException re) {
9673             throw re.rethrowFromSystemServer();
9674         }
9675     }
9676 
9677     /**
9678      * @hide
9679      * Remove a test admin synchronously without sending it a broadcast about being removed.
9680      * If the admin is a profile owner or device owner it will still be removed.
9681      *
9682      * @param userHandle user id to remove the admin for.
9683      * @param admin The administration compononent to remove.
9684      * @throws SecurityException if the caller is not shell / root or the admin package
9685      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
9686      */
forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle)9687     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
9688         try {
9689             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
9690         } catch (RemoteException re) {
9691             throw re.rethrowFromSystemServer();
9692         }
9693     }
9694 
9695     /**
9696      * Returns whether the device has been provisioned.
9697      *
9698      * <p>Not for use by third-party applications.
9699      *
9700      * @hide
9701      */
9702     @SystemApi
9703     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()9704     public boolean isDeviceProvisioned() {
9705         try {
9706             return mService.isDeviceProvisioned();
9707         } catch (RemoteException re) {
9708             throw re.rethrowFromSystemServer();
9709         }
9710     }
9711 
9712     /**
9713       * Writes that the provisioning configuration has been applied.
9714       *
9715       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
9716       * permission.
9717       *
9718       * <p>Not for use by third-party applications.
9719       *
9720       * @hide
9721       */
9722     @SystemApi
9723     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()9724     public void setDeviceProvisioningConfigApplied() {
9725         try {
9726             mService.setDeviceProvisioningConfigApplied();
9727         } catch (RemoteException re) {
9728             throw re.rethrowFromSystemServer();
9729         }
9730     }
9731 
9732     /**
9733      * Returns whether the provisioning configuration has been applied.
9734      *
9735      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
9736      *
9737      * <p>Not for use by third-party applications.
9738      *
9739      * @return whether the provisioning configuration has been applied.
9740      *
9741      * @hide
9742      */
9743     @SystemApi
9744     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()9745     public boolean isDeviceProvisioningConfigApplied() {
9746         try {
9747             return mService.isDeviceProvisioningConfigApplied();
9748         } catch (RemoteException re) {
9749             throw re.rethrowFromSystemServer();
9750         }
9751     }
9752 
9753     /**
9754      * @hide
9755      * Force update user setup completed status. This API has no effect on user build.
9756      * @throws {@link SecurityException} if the caller has no
9757      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
9758      *         not {@link UserHandle#SYSTEM_USER}
9759      */
forceUpdateUserSetupComplete()9760     public void forceUpdateUserSetupComplete() {
9761         try {
9762             mService.forceUpdateUserSetupComplete();
9763         } catch (RemoteException re) {
9764             throw re.rethrowFromSystemServer();
9765         }
9766     }
9767 
9768     @UnsupportedAppUsage
throwIfParentInstance(String functionName)9769     private void throwIfParentInstance(String functionName) {
9770         if (mParentInstance) {
9771             throw new SecurityException(functionName + " cannot be called on the parent instance");
9772         }
9773     }
9774 
9775     /**
9776      * Allows the device owner or profile owner to enable or disable the backup service.
9777      *
9778      * <p> Each user has its own backup service which manages the backup and restore mechanisms in
9779      * that user. Disabling the backup service will prevent data from being backed up or restored.
9780      *
9781      * <p> Device owner calls this API to control backup services across all users on the device.
9782      * Profile owner can use this API to enable or disable the profile's backup service. However,
9783      * for a managed profile its backup functionality is only enabled if both the device owner
9784      * and the profile owner have enabled the backup service.
9785      *
9786      * <p> By default, backup service is disabled on a device with device owner, and within a
9787      * managed profile.
9788      *
9789      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9790      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
9791      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
9792      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)9793     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
9794         throwIfParentInstance("setBackupServiceEnabled");
9795         try {
9796             mService.setBackupServiceEnabled(admin, enabled);
9797         } catch (RemoteException re) {
9798             throw re.rethrowFromSystemServer();
9799         }
9800     }
9801 
9802     /**
9803      * Return whether the backup service is enabled by the device owner or profile owner for the
9804      * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
9805      *
9806      * <p> Whether the backup functionality is actually enabled or not depends on settings from both
9807      * the current user and the device owner, please see
9808      * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
9809      *
9810      * <p> Backup service manages all backup and restore mechanisms on the device.
9811      *
9812      * @return {@code true} if backup service is enabled, {@code false} otherwise.
9813      * @see #setBackupServiceEnabled
9814      */
isBackupServiceEnabled(@onNull ComponentName admin)9815     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
9816         throwIfParentInstance("isBackupServiceEnabled");
9817         try {
9818             return mService.isBackupServiceEnabled(admin);
9819         } catch (RemoteException re) {
9820             throw re.rethrowFromSystemServer();
9821         }
9822     }
9823 
9824     /**
9825      * Called by a device owner or delegated app with {@link #DELEGATION_NETWORK_LOGGING} to
9826      * control the network logging feature.
9827      *
9828      * <p> Network logs contain DNS lookup and connect() library call events. The following library
9829      *     functions are recorded while network logging is active:
9830      *     <ul>
9831      *       <li>{@code getaddrinfo()}</li>
9832      *       <li>{@code gethostbyname()}</li>
9833      *       <li>{@code connect()}</li>
9834      *     </ul>
9835      *
9836      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
9837      *     full system call logging; event reporting is enabled by default for all processes but not
9838      *     strongly enforced.
9839      *     Events from applications using alternative implementations of libc, making direct kernel
9840      *     calls, or deliberately obfuscating traffic may not be recorded.
9841      *
9842      * <p> Some common network events may not be reported. For example:
9843      *     <ul>
9844      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
9845      *           an alternative system for name resolution, and so avoid calling
9846      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
9847      *       <li>Applications may use datagram sockets for performance reasons, for example
9848      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
9849      *           socket, so it will not trigger a network event.</li>
9850      *     </ul>
9851      *
9852      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
9853      *     always-on VPN service.
9854      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
9855      *     and {@link android.net.VpnService} for details.
9856      *
9857      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
9858      * are unaffiliated secondary users or profiles on the device, regardless of whether the
9859      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
9860      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
9861      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
9862      *
9863      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9864      *        {@code null} if called by a delegated app.
9865      * @param enabled whether network logging should be enabled or not.
9866      * @throws SecurityException if {@code admin} is not a device owner.
9867      * @see #setAffiliationIds
9868      * @see #retrieveNetworkLogs
9869      */
setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)9870     public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
9871         throwIfParentInstance("setNetworkLoggingEnabled");
9872         try {
9873             mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
9874         } catch (RemoteException re) {
9875             throw re.rethrowFromSystemServer();
9876         }
9877     }
9878 
9879     /**
9880      * Return whether network logging is enabled by a device owner.
9881      *
9882      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
9883      * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
9884      * or has MANAGE_USERS permission.
9885      * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
9886      * @throws SecurityException if {@code admin} is not a device owner and caller has
9887      * no MANAGE_USERS permission
9888      */
isNetworkLoggingEnabled(@ullable ComponentName admin)9889     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
9890         throwIfParentInstance("isNetworkLoggingEnabled");
9891         try {
9892             return mService.isNetworkLoggingEnabled(admin, mContext.getPackageName());
9893         } catch (RemoteException re) {
9894             throw re.rethrowFromSystemServer();
9895         }
9896     }
9897 
9898     /**
9899      * Called by device owner or delegated app with {@link #DELEGATION_NETWORK_LOGGING} to retrieve
9900      * the most recent batch of network logging events.
9901      * A device owner has to provide a batchToken provided as part of
9902      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
9903      * token of the most recent available batch of logs, {@code null} will be returned.
9904      *
9905      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
9906      *
9907      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
9908      *
9909      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
9910      * after the device device owner has been notified via
9911      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
9912      *
9913      * <p>If a secondary user or profile is created, calling this method will throw a
9914      * {@link SecurityException} until all users become affiliated again. It will also no longer be
9915      * possible to retrieve the network logs batch with the most recent batchToken provided
9916      * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
9917      * {@link DevicePolicyManager#setAffiliationIds}.
9918      *
9919      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9920      *        {@code null} if called by a delegated app.
9921      * @param batchToken A token of the batch to retrieve
9922      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
9923      *        {@code null} if the batch represented by batchToken is no longer available or if
9924      *        logging is disabled.
9925      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
9926      * profile or secondary user that is not affiliated with the device.
9927      * @see #setAffiliationIds
9928      * @see DeviceAdminReceiver#onNetworkLogsAvailable
9929      */
retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)9930     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
9931             long batchToken) {
9932         throwIfParentInstance("retrieveNetworkLogs");
9933         try {
9934             return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
9935         } catch (RemoteException re) {
9936             throw re.rethrowFromSystemServer();
9937         }
9938     }
9939 
9940     /**
9941      * Called by a device owner to bind to a service from a profile owner or vice versa.
9942      * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
9943      * device/profile owners are allowed to bind to services of another profile/device owner.
9944      * <p>
9945      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
9946      * Note that the {@link Context} used to obtain this
9947      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
9948      * to bind to the {@link android.app.Service}.
9949      *
9950      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9951      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
9952      *        explicit component name or a package name to match an
9953      *        {@link IntentFilter} published by a service.
9954      * @param conn Receives information as the service is started and stopped in main thread. This
9955      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
9956      * @param flags Operation options for the binding operation. See
9957      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
9958      * @param targetUser Which user to bind to. Must be one of the users returned by
9959      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
9960      *        be thrown.
9961      * @return If you have successfully bound to the service, {@code true} is returned;
9962      *         {@code false} is returned if the connection is not made and you will not
9963      *         receive the service object.
9964      *
9965      * @see Context#bindService(Intent, ServiceConnection, int)
9966      * @see #getBindDeviceAdminTargetUsers(ComponentName)
9967      */
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser)9968     public boolean bindDeviceAdminServiceAsUser(
9969             @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
9970             @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
9971         throwIfParentInstance("bindDeviceAdminServiceAsUser");
9972         // Keep this in sync with ContextImpl.bindServiceCommon.
9973         try {
9974             final IServiceConnection sd = mContext.getServiceDispatcher(
9975                     conn, mContext.getMainThreadHandler(), flags);
9976             serviceIntent.prepareToLeaveProcess(mContext);
9977             return mService.bindDeviceAdminServiceAsUser(admin,
9978                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
9979                     sd, flags, targetUser.getIdentifier());
9980         } catch (RemoteException re) {
9981             throw re.rethrowFromSystemServer();
9982         }
9983     }
9984 
9985     /**
9986      * Returns the list of target users that the calling device or profile owner can use when
9987      * calling {@link #bindDeviceAdminServiceAsUser}.
9988      * <p>
9989      * A device owner can bind to a service from a profile owner and vice versa, provided that:
9990      * <ul>
9991      * <li>Both belong to the same package name.
9992      * <li>Both users are affiliated. See {@link #setAffiliationIds}.
9993      * </ul>
9994      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)9995     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
9996         throwIfParentInstance("getBindDeviceAdminTargetUsers");
9997         try {
9998             return mService.getBindDeviceAdminTargetUsers(admin);
9999         } catch (RemoteException re) {
10000             throw re.rethrowFromSystemServer();
10001         }
10002     }
10003 
10004     /**
10005      * Called by the system to get the time at which the device owner last retrieved security
10006      * logging entries.
10007      *
10008      * @return the time at which the device owner most recently retrieved security logging entries,
10009      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
10010      * @throws SecurityException if the caller is not the device owner, does not hold the
10011      *         MANAGE_USERS permission and is not the system.
10012      *
10013      * @hide
10014      */
10015     @TestApi
getLastSecurityLogRetrievalTime()10016     public long getLastSecurityLogRetrievalTime() {
10017         try {
10018             return mService.getLastSecurityLogRetrievalTime();
10019         } catch (RemoteException re) {
10020             throw re.rethrowFromSystemServer();
10021         }
10022     }
10023 
10024     /**
10025      * Called by the system to get the time at which the device owner last requested a bug report.
10026      *
10027      * @return the time at which the device owner most recently requested a bug report, in
10028      *         milliseconds since epoch; -1 if a bug report was never requested.
10029      * @throws SecurityException if the caller is not the device owner, does not hold the
10030      *         MANAGE_USERS permission and is not the system.
10031      *
10032      * @hide
10033      */
10034     @TestApi
getLastBugReportRequestTime()10035     public long getLastBugReportRequestTime() {
10036         try {
10037             return mService.getLastBugReportRequestTime();
10038         } catch (RemoteException re) {
10039             throw re.rethrowFromSystemServer();
10040         }
10041     }
10042 
10043     /**
10044      * Called by the system to get the time at which the device owner last retrieved network logging
10045      * events.
10046      *
10047      * @return the time at which the device owner most recently retrieved network logging events, in
10048      *         milliseconds since epoch; -1 if network logging events were never retrieved.
10049      * @throws SecurityException if the caller is not the device owner, does not hold the
10050      *         MANAGE_USERS permission and is not the system.
10051      *
10052      * @hide
10053      */
10054     @TestApi
getLastNetworkLogRetrievalTime()10055     public long getLastNetworkLogRetrievalTime() {
10056         try {
10057             return mService.getLastNetworkLogRetrievalTime();
10058         } catch (RemoteException re) {
10059             throw re.rethrowFromSystemServer();
10060         }
10061     }
10062 
10063     /**
10064      * Called by the system to find out whether the current user's IME was set by the device/profile
10065      * owner or the user.
10066      *
10067      * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
10068      *         otherwise.
10069      * @throws SecurityException if the caller is not the device owner/profile owner.
10070      *
10071      * @hide
10072      */
10073     @TestApi
isCurrentInputMethodSetByOwner()10074     public boolean isCurrentInputMethodSetByOwner() {
10075         try {
10076             return mService.isCurrentInputMethodSetByOwner();
10077         } catch (RemoteException re) {
10078             throw re.rethrowFromSystemServer();
10079         }
10080     }
10081 
10082     /**
10083      * Called by the system to get a list of CA certificates that were installed by the device or
10084      * profile owner.
10085      *
10086      * <p> The caller must be the target user's device owner/profile Owner or hold the
10087      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
10088      *
10089      * @param user The user for whom to retrieve information.
10090      * @return list of aliases identifying CA certificates installed by the device or profile owner
10091      * @throws SecurityException if the caller does not have permission to retrieve information
10092      *         about the given user's CA certificates.
10093      *
10094      * @hide
10095      */
10096     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)10097     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
10098         try {
10099             return mService.getOwnerInstalledCaCerts(user).getList();
10100         } catch (RemoteException re) {
10101             throw re.rethrowFromSystemServer();
10102         }
10103     }
10104 
10105     /**
10106      * Called by the device owner or profile owner to clear application user data of a given
10107      * package. The behaviour of this is equivalent to the target application calling
10108      * {@link android.app.ActivityManager#clearApplicationUserData()}.
10109      *
10110      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
10111      * external storage or user dictionary. This data will not be wiped by calling this API.
10112      *
10113      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10114      * @param packageName The name of the package which will have its user data wiped.
10115      * @param executor The executor through which the listener should be invoked.
10116      * @param listener A callback object that will inform the caller when the clearing is done.
10117      * @throws SecurityException if the caller is not the device owner/profile owner.
10118      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)10119     public void clearApplicationUserData(@NonNull ComponentName admin,
10120             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
10121             @NonNull OnClearApplicationUserDataListener listener) {
10122         throwIfParentInstance("clearAppData");
10123         Preconditions.checkNotNull(executor);
10124         Preconditions.checkNotNull(listener);
10125         try {
10126             mService.clearApplicationUserData(admin, packageName,
10127                     new IPackageDataObserver.Stub() {
10128                         public void onRemoveCompleted(String pkg, boolean succeeded) {
10129                             executor.execute(() ->
10130                                     listener.onApplicationUserDataCleared(pkg, succeeded));
10131                         }
10132                     });
10133         } catch (RemoteException re) {
10134             throw re.rethrowFromSystemServer();
10135         }
10136     }
10137 
10138     /**
10139      * Called by a device owner to specify whether logout is enabled for all secondary users. The
10140      * system may show a logout button that stops the user and switches back to the primary user.
10141      *
10142      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10143      * @param enabled whether logout should be enabled or not.
10144      * @throws SecurityException if {@code admin} is not a device owner.
10145      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)10146     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
10147         throwIfParentInstance("setLogoutEnabled");
10148         try {
10149             mService.setLogoutEnabled(admin, enabled);
10150         } catch (RemoteException re) {
10151             throw re.rethrowFromSystemServer();
10152         }
10153     }
10154 
10155     /**
10156      * Returns whether logout is enabled by a device owner.
10157      *
10158      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
10159      */
isLogoutEnabled()10160     public boolean isLogoutEnabled() {
10161         throwIfParentInstance("isLogoutEnabled");
10162         try {
10163             return mService.isLogoutEnabled();
10164         } catch (RemoteException re) {
10165             throw re.rethrowFromSystemServer();
10166         }
10167     }
10168 
10169     /**
10170      * Callback used in {@link #clearApplicationUserData}
10171      * to indicate that the clearing of an application's user data is done.
10172      */
10173     public interface OnClearApplicationUserDataListener {
10174         /**
10175          * Method invoked when clearing the application user data has completed.
10176          *
10177          * @param packageName The name of the package which had its user data cleared.
10178          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
10179          *                  apps and protected system packages.
10180          */
onApplicationUserDataCleared(String packageName, boolean succeeded)10181         void onApplicationUserDataCleared(String packageName, boolean succeeded);
10182     }
10183 
10184     /**
10185      * Returns set of system apps that should be removed during provisioning.
10186      *
10187      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10188      * @param userId ID of the user to be provisioned.
10189      * @param provisioningAction action indicating type of provisioning, should be one of
10190      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
10191      * {@link #ACTION_PROVISION_MANAGED_USER}.
10192      *
10193      * @hide
10194      */
getDisallowedSystemApps(ComponentName admin, int userId, String provisioningAction)10195     public Set<String> getDisallowedSystemApps(ComponentName admin, int userId,
10196             String provisioningAction) {
10197         try {
10198             return new ArraySet<>(
10199                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
10200         } catch (RemoteException re) {
10201             throw re.rethrowFromSystemServer();
10202         }
10203     }
10204 
10205     /**
10206      * Changes the current administrator to another one. All policies from the current
10207      * administrator are migrated to the new administrator. The whole operation is atomic -
10208      * the transfer is either complete or not done at all.
10209      *
10210      * <p>Depending on the current administrator (device owner, profile owner), you have the
10211      * following expected behaviour:
10212      * <ul>
10213      *     <li>A device owner can only be transferred to a new device owner</li>
10214      *     <li>A profile owner can only be transferred to a new profile owner</li>
10215      * </ul>
10216      *
10217      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
10218      * will be received in the
10219      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
10220      * callback of the new administrator.
10221      *
10222      * <p>The transfer has failed if the original administrator is still the corresponding owner
10223      * after calling this method.
10224      *
10225      * <p>The incoming target administrator must have the
10226      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
10227      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
10228      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
10229      * {@link IllegalArgumentException} will be thrown.
10230      *
10231      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10232      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
10233      * @param bundle data to be sent to the new administrator
10234      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
10235      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
10236      * are components in the same package or {@code target} is not an active admin
10237      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)10238     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
10239             @Nullable PersistableBundle bundle) {
10240         throwIfParentInstance("transferOwnership");
10241         try {
10242             mService.transferOwnership(admin, target, bundle);
10243         } catch (RemoteException re) {
10244             throw re.rethrowFromSystemServer();
10245         }
10246     }
10247 
10248     /**
10249      * Called by a device owner to specify the user session start message. This may be displayed
10250      * during a user switch.
10251      * <p>
10252      * The message should be limited to a short statement or it may be truncated.
10253      * <p>
10254      * If the message needs to be localized, it is the responsibility of the
10255      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
10256      * and set a new version of this message accordingly.
10257      *
10258      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10259      * @param startUserSessionMessage message for starting user session, or {@code null} to use
10260      * system default message.
10261      * @throws SecurityException if {@code admin} is not a device owner.
10262      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)10263     public void setStartUserSessionMessage(
10264             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
10265         throwIfParentInstance("setStartUserSessionMessage");
10266         try {
10267             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
10268         } catch (RemoteException re) {
10269             throw re.rethrowFromSystemServer();
10270         }
10271     }
10272 
10273     /**
10274      * Called by a device owner to specify the user session end message. This may be displayed
10275      * during a user switch.
10276      * <p>
10277      * The message should be limited to a short statement or it may be truncated.
10278      * <p>
10279      * If the message needs to be localized, it is the responsibility of the
10280      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
10281      * and set a new version of this message accordingly.
10282      *
10283      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10284      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
10285      * default message.
10286      * @throws SecurityException if {@code admin} is not a device owner.
10287      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)10288     public void setEndUserSessionMessage(
10289             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
10290         throwIfParentInstance("setEndUserSessionMessage");
10291         try {
10292             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
10293         } catch (RemoteException re) {
10294             throw re.rethrowFromSystemServer();
10295         }
10296     }
10297 
10298     /**
10299      * Returns the user session start message.
10300      *
10301      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10302      * @throws SecurityException if {@code admin} is not a device owner.
10303      */
getStartUserSessionMessage(@onNull ComponentName admin)10304     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
10305         throwIfParentInstance("getStartUserSessionMessage");
10306         try {
10307             return mService.getStartUserSessionMessage(admin);
10308         } catch (RemoteException re) {
10309             throw re.rethrowFromSystemServer();
10310         }
10311     }
10312 
10313     /**
10314      * Returns the user session end message.
10315      *
10316      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10317      * @throws SecurityException if {@code admin} is not a device owner.
10318      */
getEndUserSessionMessage(@onNull ComponentName admin)10319     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
10320         throwIfParentInstance("getEndUserSessionMessage");
10321         try {
10322             return mService.getEndUserSessionMessage(admin);
10323         } catch (RemoteException re) {
10324             throw re.rethrowFromSystemServer();
10325         }
10326     }
10327 
10328     /**
10329      * Called by device owner to add an override APN.
10330      *
10331      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
10332      * override APN. Update the existing conflicted APN with
10333      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
10334      * <p>Two override APNs are considered to conflict when all the following APIs return
10335      * the same values on both override APNs:
10336      * <ul>
10337      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
10338      *   <li>{@link ApnSetting#getApnName()}</li>
10339      *   <li>{@link ApnSetting#getProxyAddressAsString()}</li>
10340      *   <li>{@link ApnSetting#getProxyPort()}</li>
10341      *   <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
10342      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
10343      *   <li>{@link ApnSetting#getMmsc()}</li>
10344      *   <li>{@link ApnSetting#isEnabled()}</li>
10345      *   <li>{@link ApnSetting#getMvnoType()}</li>
10346      *   <li>{@link ApnSetting#getProtocol()}</li>
10347      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
10348      * </ul>
10349      *
10350      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10351      * @param apnSetting the override APN to insert
10352      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
10353      *         the database.
10354      * @throws SecurityException if {@code admin} is not a device owner.
10355      *
10356      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10357      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)10358     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
10359         throwIfParentInstance("addOverrideApn");
10360         if (mService != null) {
10361             try {
10362                 return mService.addOverrideApn(admin, apnSetting);
10363             } catch (RemoteException e) {
10364                 throw e.rethrowFromSystemServer();
10365             }
10366         }
10367         return -1;
10368     }
10369 
10370     /**
10371      * Called by device owner to update an override APN.
10372      *
10373      * <p>This method may returns {@code false} if there is no override APN with the given
10374      * {@code apnId}.
10375      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
10376      * existing override APN. Update the existing conflicted APN instead.
10377      * <p>See {@link #addOverrideApn} for the definition of conflict.
10378      *
10379      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10380      * @param apnId the {@code id} of the override APN to update
10381      * @param apnSetting the override APN to update
10382      * @return {@code true} if the required override APN is successfully updated,
10383      *         {@code false} otherwise.
10384      * @throws SecurityException if {@code admin} is not a device owner.
10385      *
10386      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10387      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)10388     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
10389             @NonNull ApnSetting apnSetting) {
10390         throwIfParentInstance("updateOverrideApn");
10391         if (mService != null) {
10392             try {
10393                 return mService.updateOverrideApn(admin, apnId, apnSetting);
10394             } catch (RemoteException e) {
10395                 throw e.rethrowFromSystemServer();
10396             }
10397         }
10398         return false;
10399     }
10400 
10401     /**
10402      * Called by device owner to remove an override APN.
10403      *
10404      * <p>This method may returns {@code false} if there is no override APN with the given
10405      * {@code apnId}.
10406      *
10407      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10408      * @param apnId the {@code id} of the override APN to remove
10409      * @return {@code true} if the required override APN is successfully removed, {@code false}
10410      *         otherwise.
10411      * @throws SecurityException if {@code admin} is not a device owner.
10412      *
10413      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10414      */
removeOverrideApn(@onNull ComponentName admin, int apnId)10415     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
10416         throwIfParentInstance("removeOverrideApn");
10417         if (mService != null) {
10418             try {
10419                 return mService.removeOverrideApn(admin, apnId);
10420             } catch (RemoteException e) {
10421                 throw e.rethrowFromSystemServer();
10422             }
10423         }
10424         return false;
10425     }
10426 
10427     /**
10428      * Called by device owner to get all override APNs inserted by device owner.
10429      *
10430      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10431      * @return A list of override APNs inserted by device owner.
10432      * @throws SecurityException if {@code admin} is not a device owner.
10433      *
10434      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10435      */
getOverrideApns(@onNull ComponentName admin)10436     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
10437         throwIfParentInstance("getOverrideApns");
10438         if (mService != null) {
10439             try {
10440                 return mService.getOverrideApns(admin);
10441             } catch (RemoteException e) {
10442                 throw e.rethrowFromSystemServer();
10443             }
10444         }
10445         return Collections.emptyList();
10446     }
10447 
10448     /**
10449      * Called by device owner to set if override APNs should be enabled.
10450      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
10451      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
10452      * are ignored.
10453      *
10454      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10455      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
10456      * @throws SecurityException if {@code admin} is not a device owner.
10457      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)10458     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
10459         throwIfParentInstance("setOverrideApnEnabled");
10460         if (mService != null) {
10461             try {
10462                 mService.setOverrideApnsEnabled(admin, enabled);
10463             } catch (RemoteException e) {
10464                 throw e.rethrowFromSystemServer();
10465             }
10466         }
10467     }
10468 
10469     /**
10470      * Called by device owner to check if override APNs are currently enabled.
10471      *
10472      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10473      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
10474      * @throws SecurityException if {@code admin} is not a device owner.
10475      *
10476      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10477      */
isOverrideApnEnabled(@onNull ComponentName admin)10478     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
10479         throwIfParentInstance("isOverrideApnEnabled");
10480         if (mService != null) {
10481             try {
10482                 return mService.isOverrideApnEnabled(admin);
10483             } catch (RemoteException e) {
10484                 throw e.rethrowFromSystemServer();
10485             }
10486         }
10487         return false;
10488     }
10489 
10490     /**
10491      * Returns the data passed from the current administrator to the new administrator during an
10492      * ownership transfer. This is the same {@code bundle} passed in
10493      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
10494      * persisted until the profile owner or device owner is removed.
10495      *
10496      * <p>This is the same <code>bundle</code> received in the
10497      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
10498      * Use this method to retrieve it after the transfer as long as the new administrator is the
10499      * active device or profile owner.
10500      *
10501      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
10502      *
10503      * @see #transferOwnership
10504      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
10505      * @throws SecurityException if the caller is not a device or profile owner.
10506      */
10507     @Nullable
getTransferOwnershipBundle()10508     public PersistableBundle getTransferOwnershipBundle() {
10509         throwIfParentInstance("getTransferOwnershipBundle");
10510         try {
10511             return mService.getTransferOwnershipBundle();
10512         } catch (RemoteException re) {
10513             throw re.rethrowFromSystemServer();
10514         }
10515     }
10516 
10517     /**
10518      * Sets the global Private DNS mode to opportunistic.
10519      * May only be called by the device owner.
10520      *
10521      * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
10522      * resolver prior to attempting name resolution in cleartext.
10523      *
10524      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10525      *
10526      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
10527      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
10528      *
10529      * @throws SecurityException if the caller is not the device owner.
10530      */
setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)10531     public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
10532             @NonNull ComponentName admin) {
10533         throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
10534 
10535         if (mService == null) {
10536             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
10537         }
10538 
10539         try {
10540             return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
10541         } catch (RemoteException re) {
10542             throw re.rethrowFromSystemServer();
10543         }
10544     }
10545 
10546     /**
10547      * Sets the global Private DNS host to be used.
10548      * May only be called by the device owner.
10549      *
10550      * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
10551      * to ensure it is valid. Because of that, the method should not be called on any thread that
10552      * relates to user interaction, such as the UI thread.
10553      *
10554      * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
10555      * must be reachable both from within and outside the VPN. Otherwise, the device may lose
10556      * the ability to resolve hostnames as system traffic to the resolver may not go through the
10557      * VPN.
10558      *
10559      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10560      * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
10561      *
10562      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
10563      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
10564      *         {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
10565      *         implement RFC7858.
10566      *
10567      * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
10568      *
10569      * @throws SecurityException if the caller is not the device owner.
10570      */
setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)10571     @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
10572             @NonNull ComponentName admin, @NonNull String privateDnsHost) {
10573         throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
10574         Preconditions.checkNotNull(privateDnsHost, "dns resolver is null");
10575 
10576         if (mService == null) {
10577             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
10578         }
10579 
10580         if (NetworkUtils.isWeaklyValidatedHostname(privateDnsHost)) {
10581             if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
10582                 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
10583             }
10584         }
10585 
10586         try {
10587             return mService.setGlobalPrivateDns(
10588                     admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
10589         } catch (RemoteException re) {
10590             throw re.rethrowFromSystemServer();
10591         }
10592     }
10593 
10594     /**
10595      * Called by device owner to install a system update from the given file. The device will be
10596      * rebooted in order to finish installing the update. Note that if the device is rebooted, this
10597      * doesn't necessarily mean that the update has been applied successfully. The caller should
10598      * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
10599      * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
10600      * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
10601      * sufficient battery level, the installation will fail with error {@link
10602      * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
10603      *
10604      * @param admin The {@link DeviceAdminReceiver} that this request is associated with.
10605      * @param updateFilePath An Uri of the file that contains the update. The file should be
10606      * readable by the calling app.
10607      * @param executor The executor through which the callback should be invoked.
10608      * @param callback A callback object that will inform the caller when installing an update
10609      * fails.
10610      */
installSystemUpdate( @onNull ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)10611     public void installSystemUpdate(
10612             @NonNull ComponentName admin, @NonNull Uri updateFilePath,
10613             @NonNull @CallbackExecutor Executor executor,
10614             @NonNull InstallSystemUpdateCallback callback) {
10615         throwIfParentInstance("installUpdate");
10616         if (mService == null) {
10617             return;
10618         }
10619         try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
10620                     .openFileDescriptor(updateFilePath, "r")) {
10621             mService.installUpdateFromFile(
10622                     admin, fileDescriptor, new StartInstallingUpdateCallback.Stub() {
10623                         @Override
10624                         public void onStartInstallingUpdateError(
10625                                 int errorCode, String errorMessage) {
10626                             executeCallback(errorCode, errorMessage, executor, callback);
10627                         }
10628                     });
10629         } catch (RemoteException e) {
10630             throw e.rethrowFromSystemServer();
10631         } catch (FileNotFoundException e) {
10632             Log.w(TAG, e);
10633             executeCallback(
10634                     InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
10635                     Log.getStackTraceString(e),
10636                     executor, callback);
10637         } catch (IOException e) {
10638             Log.w(TAG, e);
10639             executeCallback(
10640                     InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
10641                     executor, callback);
10642         }
10643     }
10644 
executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)10645     private void executeCallback(int errorCode, String errorMessage,
10646             @NonNull @CallbackExecutor Executor executor,
10647             @NonNull InstallSystemUpdateCallback callback) {
10648         executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
10649     }
10650 
10651     /**
10652      * Returns the system-wide Private DNS mode.
10653      *
10654      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10655      * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
10656      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
10657      * @throws SecurityException if the caller is not the device owner.
10658      */
getGlobalPrivateDnsMode(@onNull ComponentName admin)10659     public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
10660         throwIfParentInstance("setGlobalPrivateDns");
10661         if (mService == null) {
10662             return PRIVATE_DNS_MODE_UNKNOWN;
10663         }
10664 
10665         try {
10666             return mService.getGlobalPrivateDnsMode(admin);
10667         } catch (RemoteException re) {
10668             throw re.rethrowFromSystemServer();
10669         }
10670     }
10671 
10672     /**
10673      * Returns the system-wide Private DNS host.
10674      *
10675      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10676      * @return The hostname used for Private DNS queries, null if none is set.
10677      * @throws SecurityException if the caller is not the device owner.
10678      */
getGlobalPrivateDnsHost(@onNull ComponentName admin)10679     public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
10680         throwIfParentInstance("setGlobalPrivateDns");
10681         if (mService == null) {
10682             return null;
10683         }
10684 
10685         try {
10686             return mService.getGlobalPrivateDnsHost(admin);
10687         } catch (RemoteException re) {
10688             throw re.rethrowFromSystemServer();
10689         }
10690     }
10691 
10692     /**
10693      * Grants the profile owner of the given user access to device identifiers (such as
10694      * serial number, IMEI and MEID).
10695      *
10696      * <p>This lets the profile owner request inclusion of device identifiers when calling
10697      * {@link generateKeyPair}.
10698      *
10699      * <p>This grant is necessary to guarantee that profile owners can access device identifiers.
10700      *
10701      * <p>Privileged system API - meant to be called by the system, particularly the managed
10702      * provisioning app, when a work profile is set up.
10703      *
10704      * @hide
10705      */
10706     @SystemApi
10707     @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
10708             conditional = true)
setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)10709     public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
10710         if (mService == null) {
10711             return;
10712         }
10713         try {
10714             mService.grantDeviceIdsAccessToProfileOwner(who, myUserId());
10715         } catch (RemoteException re) {
10716             throw re.rethrowFromSystemServer();
10717         }
10718     }
10719 
10720     /**
10721      * Allows a set of packages to access cross-profile calendar APIs.
10722      *
10723      * <p>Called by a profile owner of a managed profile.
10724      *
10725      * <p>Calling with a {@code null} value for the set disables the restriction so that all
10726      * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
10727      * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
10728      * called, no package is allowed to access cross-profile calendar APIs by default.
10729      *
10730      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10731      * @param packageNames set of packages to be whitelisted
10732      * @throws SecurityException if {@code admin} is not a profile owner
10733      *
10734      * @see #getCrossProfileCalendarPackages(ComponentName)
10735      */
setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)10736     public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
10737             @Nullable Set<String> packageNames) {
10738         throwIfParentInstance("setCrossProfileCalendarPackages");
10739         if (mService != null) {
10740             try {
10741                 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
10742                         : new ArrayList<>(packageNames));
10743             } catch (RemoteException e) {
10744                 throw e.rethrowFromSystemServer();
10745             }
10746         }
10747     }
10748 
10749     /**
10750      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
10751      *
10752      * <p>Called by a profile owner of a managed profile.
10753      *
10754      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10755      * @return the set of names of packages that were previously allowed via
10756      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
10757      * empty set if none have been allowed
10758      * @throws SecurityException if {@code admin} is not a profile owner
10759      *
10760      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
10761      */
getCrossProfileCalendarPackages(@onNull ComponentName admin)10762     public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
10763         throwIfParentInstance("getCrossProfileCalendarPackages");
10764         if (mService != null) {
10765             try {
10766                 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
10767                 return packageNames == null ? null : new ArraySet<>(packageNames);
10768             } catch (RemoteException e) {
10769                 throw e.rethrowFromSystemServer();
10770             }
10771         }
10772         return Collections.emptySet();
10773     }
10774 
10775     /**
10776      * Returns if a package is allowed to access cross-profile calendar APIs.
10777      *
10778      * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
10779      * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
10780      * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
10781      * is turned on in the managed profile.
10782      *
10783      * <p>To query for a specific user, use
10784      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
10785      * that user, and get a {@link DevicePolicyManager} from this context.
10786      *
10787      * @param packageName the name of the package
10788      * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
10789      * {@code false} otherwise
10790      *
10791      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
10792      * @see #getCrossProfileCalendarPackages(ComponentName)
10793      * @hide
10794      */
isPackageAllowedToAccessCalendar(@onNull String packageName)10795     public boolean isPackageAllowedToAccessCalendar(@NonNull  String packageName) {
10796         throwIfParentInstance("isPackageAllowedToAccessCalendar");
10797         if (mService != null) {
10798             try {
10799                 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
10800                         myUserId());
10801             } catch (RemoteException e) {
10802                 throw e.rethrowFromSystemServer();
10803             }
10804         }
10805         return false;
10806     }
10807 
10808     /**
10809      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
10810      *
10811      * <p>To query for a specific user, use
10812      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
10813      * that user, and get a {@link DevicePolicyManager} from this context.
10814      *
10815      * @return the set of names of packages that were previously allowed via
10816      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
10817      * empty set if none have been allowed
10818      *
10819      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
10820      * @see #getCrossProfileCalendarPackages(ComponentName)
10821      * @hide
10822      */
getCrossProfileCalendarPackages()10823     public @Nullable Set<String> getCrossProfileCalendarPackages() {
10824         throwIfParentInstance("getCrossProfileCalendarPackages");
10825         if (mService != null) {
10826             try {
10827                 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
10828                         myUserId());
10829                 return packageNames == null ? null : new ArraySet<>(packageNames);
10830             } catch (RemoteException e) {
10831                 throw e.rethrowFromSystemServer();
10832             }
10833         }
10834         return Collections.emptySet();
10835     }
10836 
10837     /**
10838      * Returns whether the device is being used as a managed kiosk. These requirements are as
10839      * follows:
10840      * <ul>
10841      *     <li>The device is in Lock Task (therefore there is also a Device Owner app on the
10842      *     device)</li>
10843      *     <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
10844      *     not enabled, so the system info in the status bar is not visible</li>
10845      *     <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
10846      *     swipe-to-unlock)</li>
10847      *     <li>The device is not in the middle of an ephemeral user session</li>
10848      * </ul>
10849      *
10850      * <p>Publicly-accessible dedicated devices don't have the same privacy model as
10851      * personally-used devices. In particular, user consent popups don't make sense as a barrier to
10852      * accessing persistent data on these devices since the user giving consent and the user whose
10853      * data is on the device are unlikely to be the same. These consent popups prevent the true
10854      * remote management of these devices.
10855      *
10856      * <p>This condition is not sufficient to cover APIs that would access data that only lives for
10857      * the duration of the user's session, since the user has an expectation of privacy in these
10858      * conditions that more closely resembles use of a personal device. In those cases, see {@link
10859      * #isUnattendedManagedKiosk()}.
10860      *
10861      * @hide
10862      */
10863     @SystemApi
10864     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isManagedKiosk()10865     public boolean isManagedKiosk() {
10866         throwIfParentInstance("isManagedKiosk");
10867         if (mService != null) {
10868             try {
10869                 return mService.isManagedKiosk();
10870             } catch (RemoteException e) {
10871                 throw e.rethrowFromSystemServer();
10872             }
10873         }
10874         return false;
10875     }
10876 
10877     /**
10878      * Returns whether the device is being used as an unattended managed kiosk. These requirements
10879      * are as follows:
10880      * <ul>
10881      *     <li>The device is being used as a managed kiosk, as defined at {@link
10882      *     #isManagedKiosk()}</li>
10883      *     <li>The device has not received user input for at least 30 minutes</li>
10884      * </ul>
10885      *
10886      * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
10887      * ensures that the device hasn't been interacted with recently, making it an appropriate check
10888      * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
10889      *
10890      * @hide
10891      */
10892     @SystemApi
10893     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isUnattendedManagedKiosk()10894     public boolean isUnattendedManagedKiosk() {
10895         throwIfParentInstance("isUnattendedManagedKiosk");
10896         if (mService != null) {
10897             try {
10898                 return mService.isUnattendedManagedKiosk();
10899             } catch (RemoteException e) {
10900                 throw e.rethrowFromSystemServer();
10901             }
10902         }
10903         return false;
10904     }
10905 
10906     /**
10907      * Starts an activity to view calendar events in the managed profile.
10908      *
10909      * @param eventId the id of the event to be viewed
10910      * @param start the start time of the event
10911      * @param end the end time of the event
10912      * @param allDay if the event is an all-day event
10913      * @param flags flags to be set for the intent
10914      * @return {@code true} if the activity is started successfully, {@code false} otherwise
10915      *
10916      * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
10917      * long, boolean, int)
10918      *
10919      * @hide
10920      */
startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)10921     public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
10922             boolean allDay, int flags) {
10923         throwIfParentInstance("startViewCalendarEventInManagedProfile");
10924         if (mService != null) {
10925             try {
10926                 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
10927                         eventId, start, end, allDay, flags);
10928             } catch (RemoteException e) {
10929                 throw e.rethrowFromSystemServer();
10930             }
10931         }
10932         return false;
10933     }
10934 }
10935