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 android.annotation.CallbackExecutor;
20 import android.annotation.ColorInt;
21 import android.annotation.IntDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.RequiresFeature;
25 import android.annotation.RequiresPermission;
26 import android.annotation.SdkConstant;
27 import android.annotation.SdkConstant.SdkConstantType;
28 import android.annotation.StringDef;
29 import android.annotation.SuppressLint;
30 import android.annotation.SystemApi;
31 import android.annotation.SystemService;
32 import android.annotation.TestApi;
33 import android.annotation.UserIdInt;
34 import android.annotation.WorkerThread;
35 import android.app.Activity;
36 import android.app.IServiceConnection;
37 import android.app.KeyguardManager;
38 import android.app.admin.SecurityLog.SecurityEvent;
39 import android.content.ComponentName;
40 import android.content.Context;
41 import android.content.Intent;
42 import android.content.IntentFilter;
43 import android.content.ServiceConnection;
44 import android.content.pm.ApplicationInfo;
45 import android.content.pm.IPackageDataObserver;
46 import android.content.pm.PackageManager;
47 import android.content.pm.PackageManager.NameNotFoundException;
48 import android.content.pm.ParceledListSlice;
49 import android.content.pm.UserInfo;
50 import android.graphics.Bitmap;
51 import android.net.ProxyInfo;
52 import android.net.Uri;
53 import android.os.Bundle;
54 import android.os.Parcelable;
55 import android.os.PersistableBundle;
56 import android.os.Process;
57 import android.os.RemoteCallback;
58 import android.os.RemoteException;
59 import android.os.ServiceSpecificException;
60 import android.os.UserHandle;
61 import android.os.UserManager;
62 import android.os.UserManager.UserOperationException;
63 import android.os.UserManager.UserOperationResult;
64 import android.provider.ContactsContract.Directory;
65 import android.provider.Settings;
66 import android.security.AttestedKeyPair;
67 import android.security.Credentials;
68 import android.security.KeyChain;
69 import android.security.KeyChainException;
70 import android.security.keymaster.KeymasterCertificateChain;
71 import android.security.keystore.AttestationUtils;
72 import android.security.keystore.KeyAttestationException;
73 import android.security.keystore.KeyGenParameterSpec;
74 import android.security.keystore.ParcelableKeyGenParameterSpec;
75 import android.service.restrictions.RestrictionsReceiver;
76 import android.telephony.TelephonyManager;
77 import android.telephony.data.ApnSetting;
78 import android.util.ArraySet;
79 import android.util.Log;
80 
81 import com.android.internal.R;
82 import com.android.internal.annotations.VisibleForTesting;
83 import com.android.internal.util.Preconditions;
84 import com.android.org.conscrypt.TrustedCertificateStore;
85 
86 import java.io.ByteArrayInputStream;
87 import java.io.IOException;
88 import java.lang.annotation.Retention;
89 import java.lang.annotation.RetentionPolicy;
90 import java.net.InetSocketAddress;
91 import java.net.Proxy;
92 import java.security.KeyFactory;
93 import java.security.KeyPair;
94 import java.security.NoSuchAlgorithmException;
95 import java.security.PrivateKey;
96 import java.security.cert.Certificate;
97 import java.security.cert.CertificateException;
98 import java.security.cert.CertificateFactory;
99 import java.security.cert.X509Certificate;
100 import java.security.spec.InvalidKeySpecException;
101 import java.security.spec.PKCS8EncodedKeySpec;
102 import java.util.ArrayList;
103 import java.util.Arrays;
104 import java.util.Collections;
105 import java.util.List;
106 import java.util.Set;
107 import java.util.concurrent.Executor;
108 
109 /**
110  * Public interface for managing policies enforced on a device. Most clients of this class must be
111  * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
112  * administrator</a>. Additionally, a device administrator may be registered as either a profile or
113  * device owner. A given method is accessible to all device administrators unless the documentation
114  * for that method specifies that it is restricted to either device or profile owners. Any
115  * application calling an api may only pass as an argument a device administrator component it
116  * owns. Otherwise, a {@link SecurityException} will be thrown.
117  * <div class="special reference">
118  * <h3>Developer Guides</h3>
119  * <p>
120  * For more information about managing policies for device administration, read the <a href=
121  * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
122  * guide. </div>
123  */
124 @SystemService(Context.DEVICE_POLICY_SERVICE)
125 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN)
126 public class DevicePolicyManager {
127 
128     private static String TAG = "DevicePolicyManager";
129 
130     private final Context mContext;
131     private final IDevicePolicyManager mService;
132     private final boolean mParentInstance;
133 
134     /** @hide */
DevicePolicyManager(Context context, IDevicePolicyManager service)135     public DevicePolicyManager(Context context, IDevicePolicyManager service) {
136         this(context, service, false);
137     }
138 
139     /** @hide */
140     @VisibleForTesting
DevicePolicyManager(Context context, IDevicePolicyManager service, boolean parentInstance)141     protected DevicePolicyManager(Context context, IDevicePolicyManager service,
142             boolean parentInstance) {
143         mContext = context;
144         mService = service;
145         mParentInstance = parentInstance;
146     }
147 
148     /** @hide test will override it. */
149     @VisibleForTesting
myUserId()150     protected int myUserId() {
151         return mContext.getUserId();
152     }
153 
154     /**
155      * Activity action: Starts the provisioning flow which sets up a managed profile.
156      *
157      * <p>A managed profile allows data separation for example for the usage of a
158      * device as a personal and corporate device. The user which provisioning is started from and
159      * the managed profile share a launcher.
160      *
161      * <p>This intent will typically be sent by a mobile device management application (MDM).
162      * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
163      * control over the profile.
164      *
165      * <p>It is possible to check if provisioning is allowed or not by querying the method
166      * {@link #isProvisioningAllowed(String)}.
167      *
168      * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
169      * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
170      * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
171      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
172      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
173      *
174      * <p>The intent may also contain the following extras:
175      * <ul>
176      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
177      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
178      * {@link android.os.Build.VERSION_CODES#N}</li>
179      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
180      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
181      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
182      * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
183      * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
184      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
185      * </ul>
186      *
187      * <p>When managed provisioning has completed, broadcasts are sent to the application specified
188      * in the provisioning intent. The
189      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
190      * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
191      * the primary profile.
192      *
193      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
194      * completed, along with the above broadcast, activity intent
195      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
196      *
197      * <p>If provisioning fails, the managedProfile is removed so the device returns to its
198      * previous state.
199      *
200      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
201      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
202      * the provisioning flow was successful, although this doesn't guarantee the full flow will
203      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
204      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
205      */
206     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
207     public static final String ACTION_PROVISION_MANAGED_PROFILE
208         = "android.app.action.PROVISION_MANAGED_PROFILE";
209 
210     /**
211      * Activity action: Starts the provisioning flow which sets up a managed user.
212      *
213      * <p>This intent will typically be sent by a mobile device management application (MDM).
214      * Provisioning configures the user as managed user and sets the MDM as the profile
215      * owner who has full control over the user. Provisioning can only happen before user setup has
216      * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
217      * allowed.
218      *
219      * <p>The intent contains the following extras:
220      * <ul>
221      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
222      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
223      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
224      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
225      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
226      * </ul>
227      *
228      * <p>If provisioning fails, the device returns to its previous state.
229      *
230      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
231      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
232      * the provisioning flow was successful, although this doesn't guarantee the full flow will
233      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
234      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
235      *
236      * @hide
237      */
238     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
239     public static final String ACTION_PROVISION_MANAGED_USER
240         = "android.app.action.PROVISION_MANAGED_USER";
241 
242     /**
243      * Activity action: Starts the provisioning flow which sets up a managed device.
244      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
245      *
246      * <p> During device owner provisioning a device admin app is set as the owner of the device.
247      * A device owner has full control over the device. The device owner can not be modified by the
248      * user.
249      *
250      * <p> A typical use case would be a device that is owned by a company, but used by either an
251      * employee or client.
252      *
253      * <p> An intent with this action can be sent only on an unprovisioned device.
254      * It is possible to check if provisioning is allowed or not by querying the method
255      * {@link #isProvisioningAllowed(String)}.
256      *
257      * <p>The intent contains the following extras:
258      * <ul>
259      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
260      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
261      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
262      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
263      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
264      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
265      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
266      * </ul>
267      *
268      * <p>When device owner provisioning has completed, an intent of the type
269      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
270      * device owner.
271      *
272      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
273      * completed, along with the above broadcast, activity intent
274      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
275      *
276      * <p>If provisioning fails, the device is factory reset.
277      *
278      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
279      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
280      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
281      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
282      */
283     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
284     public static final String ACTION_PROVISION_MANAGED_DEVICE
285         = "android.app.action.PROVISION_MANAGED_DEVICE";
286 
287     /**
288      * Activity action: launch when user provisioning completed, i.e.
289      * {@link #getUserProvisioningState()} returns one of the complete state.
290      *
291      * <p> Please note that the API behavior is not necessarily consistent across various releases,
292      * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
293      * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
294      *
295      * <p> The activity must be protected by permission
296      * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
297      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
298      * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
299      * components are not started by this intent.
300      * @hide
301      */
302     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
303     @SystemApi
304     public static final String ACTION_STATE_USER_SETUP_COMPLETE =
305             "android.app.action.STATE_USER_SETUP_COMPLETE";
306 
307     /**
308      * Activity action: Starts the provisioning flow which sets up a managed device.
309      *
310      * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
311      * the device. A device owner has full control over the device. The device owner can not be
312      * modified by the user and the only way of resetting the device is via factory reset.
313      *
314      * <p>A typical use case would be a device that is owned by a company, but used by either an
315      * employee or client.
316      *
317      * <p>The provisioning message should be sent to an unprovisioned device.
318      *
319      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
320      * by a privileged app with the permission
321      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
322      *
323      * <p>The provisioning intent contains the following properties:
324      * <ul>
325      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
326      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
327      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
328      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
329      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL}, optional</li>
330      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI}, optional</li>
331      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
332      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
333      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
334      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
335      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
336      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
337      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
338      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
339      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
340      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
341      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
342      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
343      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
344      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
345      * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA, optional </li><ul>
346      *
347      * @hide
348      */
349     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
350     @SystemApi
351     public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
352             "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
353 
354     /**
355      * Activity action: Starts the provisioning flow which sets up a managed device.
356      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
357      *
358      * <p>NOTE: This is only supported on split system user devices, and puts the device into a
359      * management state that is distinct from that reached by
360      * {@link #ACTION_PROVISION_MANAGED_DEVICE} - specifically the device owner runs on the system
361      * user, and only has control over device-wide policies, not individual users and their data.
362      * The primary benefit is that multiple non-system users are supported when provisioning using
363      * this form of device management.
364      *
365      * <p>During device owner provisioning a device admin app is set as the owner of the device.
366      * A device owner has full control over the device. The device owner can not be modified by the
367      * user.
368      *
369      * <p>A typical use case would be a device that is owned by a company, but used by either an
370      * employee or client.
371      *
372      * <p>An intent with this action can be sent only on an unprovisioned device.
373      * It is possible to check if provisioning is allowed or not by querying the method
374      * {@link #isProvisioningAllowed(String)}.
375      *
376      * <p>The intent contains the following extras:
377      * <ul>
378      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
379      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
380      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
381      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
382      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
383      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
384      * </ul>
385      *
386      * <p>When device owner provisioning has completed, an intent of the type
387      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
388      * device owner.
389      *
390      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
391      * completed, along with the above broadcast, activity intent
392      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
393      *
394      * <p>If provisioning fails, the device is factory reset.
395      *
396      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
397      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
398      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
399      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
400      *
401      * @hide
402      */
403     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
404     public static final String ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE
405         = "android.app.action.PROVISION_MANAGED_SHAREABLE_DEVICE";
406 
407     /**
408      * Activity action: Finalizes management provisioning, should be used after user-setup
409      * has been completed and {@link #getUserProvisioningState()} returns one of:
410      * <ul>
411      * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
412      * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
413      * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
414      * </ul>
415      *
416      * @hide
417      */
418     @SystemApi
419     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
420     public static final String ACTION_PROVISION_FINALIZATION
421             = "android.app.action.PROVISION_FINALIZATION";
422 
423     /**
424      * Action: Bugreport sharing with device owner has been accepted by the user.
425      *
426      * @hide
427      */
428     public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
429             "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
430 
431     /**
432      * Action: Bugreport sharing with device owner has been declined by the user.
433      *
434      * @hide
435      */
436     public static final String ACTION_BUGREPORT_SHARING_DECLINED =
437             "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
438 
439     /**
440      * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
441      *
442      * @hide
443      */
444     public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
445             "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
446 
447     /**
448      * Extra for shared bugreport's SHA-256 hash.
449      *
450      * @hide
451      */
452     public static final String EXTRA_REMOTE_BUGREPORT_HASH =
453             "android.intent.extra.REMOTE_BUGREPORT_HASH";
454 
455     /**
456      * Extra for remote bugreport notification shown type.
457      *
458      * @hide
459      */
460     public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
461             "android.app.extra.bugreport_notification_type";
462 
463     /**
464      * Notification type for a started remote bugreport flow.
465      *
466      * @hide
467      */
468     public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
469 
470     /**
471      * Notification type for a bugreport that has already been accepted to be shared, but is still
472      * being taken.
473      *
474      * @hide
475      */
476     public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
477 
478     /**
479      * Notification type for a bugreport that has been taken and can be shared or declined.
480      *
481      * @hide
482      */
483     public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
484 
485     /**
486      * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
487      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
488      *
489      * @hide
490      */
491     public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
492 
493     /**
494      * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
495      * allows a mobile device management application or NFC programmer application which starts
496      * managed provisioning to pass data to the management application instance after provisioning.
497      * <p>
498      * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
499      * sends the intent to pass data to itself on the newly created profile.
500      * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
501      * instance of the app on the primary user.
502      * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
503      * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
504      * message should contain a stringified {@link java.util.Properties} instance, whose string
505      * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
506      * management application after provisioning.
507      *
508      * <p>
509      * In both cases the application receives the data in
510      * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
511      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
512      * during the managed provisioning.
513      */
514     public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
515             "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
516 
517     /**
518      * A String extra holding the package name of the mobile device management application that
519      * will be set as the profile owner or device owner.
520      *
521      * <p>If an application starts provisioning directly via an intent with action
522      * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
523      * application that started provisioning. The package will be set as profile owner in that case.
524      *
525      * <p>This package is set as device owner when device owner provisioning is started by an NFC
526      * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
527      *
528      * <p> When this extra is set, the application must have exactly one device admin receiver.
529      * This receiver will be set as the profile or device owner and active admin.
530      *
531      * @see DeviceAdminReceiver
532      * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
533      * supported, but only if there is only one device admin receiver in the package that requires
534      * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
535      */
536     @Deprecated
537     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
538         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
539 
540     /**
541      * A ComponentName extra indicating the device admin receiver of the mobile device management
542      * application that will be set as the profile owner or device owner and active admin.
543      *
544      * <p>If an application starts provisioning directly via an intent with action
545      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
546      * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
547      * component has to match the package name of the application that started provisioning.
548      *
549      * <p>This component is set as device owner and active admin when device owner provisioning is
550      * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
551      * message containing an NFC record with MIME type
552      * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
553      * flattened to a string, via {@link ComponentName#flattenToShortString()}.
554      *
555      * @see DeviceAdminReceiver
556      */
557     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
558         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
559 
560     /**
561      * An {@link android.accounts.Account} extra holding the account to migrate during managed
562      * profile provisioning. If the account supplied is present in the primary user, it will be
563      * copied, along with its credentials to the managed profile and removed from the primary user.
564      *
565      * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}.
566      */
567 
568     public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
569         = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
570 
571     /**
572      * Boolean extra to indicate that the migrated account should be kept. This is used in
573      * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
574      * the account will not be removed from the primary user after it is migrated to the newly
575      * created user or profile.
576      *
577      * <p> Defaults to {@code false}
578      *
579      * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
580      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}
581      */
582     public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
583             = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
584 
585     /**
586      * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
587      * device.
588      */
589     @Deprecated
590     public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
591         = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
592 
593     /**
594      * A integer extra indicating the predominant color to show during the provisioning.
595      * Refer to {@link android.graphics.Color} for how the color is represented.
596      *
597      * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
598      * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
599      */
600     public static final String EXTRA_PROVISIONING_MAIN_COLOR =
601              "android.app.extra.PROVISIONING_MAIN_COLOR";
602 
603     /**
604      * A Boolean extra that can be used by the mobile device management application to skip the
605      * disabling of system apps during provisioning when set to {@code true}.
606      *
607      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
608      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
609      */
610     public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
611             "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
612 
613     /**
614      * A String extra holding the time zone {@link android.app.AlarmManager} that the device
615      * will be set to.
616      *
617      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
618      * provisioning via an NFC bump.
619      */
620     public static final String EXTRA_PROVISIONING_TIME_ZONE
621         = "android.app.extra.PROVISIONING_TIME_ZONE";
622 
623     /**
624      * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
625      * {@link android.app.AlarmManager}.
626      *
627      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
628      * provisioning via an NFC bump.
629      */
630     public static final String EXTRA_PROVISIONING_LOCAL_TIME
631         = "android.app.extra.PROVISIONING_LOCAL_TIME";
632 
633     /**
634      * A String extra holding the {@link java.util.Locale} that the device will be set to.
635      * Format: xx_yy, where xx is the language code, and yy the country code.
636      *
637      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
638      * provisioning via an NFC bump.
639      */
640     public static final String EXTRA_PROVISIONING_LOCALE
641         = "android.app.extra.PROVISIONING_LOCALE";
642 
643     /**
644      * A String extra holding the ssid of the wifi network that should be used during nfc device
645      * owner provisioning for downloading the mobile device management application.
646      *
647      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
648      * provisioning via an NFC bump.
649      */
650     public static final String EXTRA_PROVISIONING_WIFI_SSID
651         = "android.app.extra.PROVISIONING_WIFI_SSID";
652 
653     /**
654      * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
655      * is hidden or not.
656      *
657      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
658      * provisioning via an NFC bump.
659      */
660     public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
661         = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
662 
663     /**
664      * A String extra indicating the security type of the wifi network in
665      * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA} or
666      * {@code WEP}.
667      *
668      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
669      * provisioning via an NFC bump.
670      */
671     public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
672         = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
673 
674     /**
675      * A String extra holding the password of the wifi network in
676      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
677      *
678      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
679      * provisioning via an NFC bump.
680      */
681     public static final String EXTRA_PROVISIONING_WIFI_PASSWORD
682         = "android.app.extra.PROVISIONING_WIFI_PASSWORD";
683 
684     /**
685      * A String extra holding the proxy host for the wifi network in
686      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
687      *
688      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
689      * provisioning via an NFC bump.
690      */
691     public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
692         = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
693 
694     /**
695      * An int extra holding the proxy port for the wifi network in
696      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
697      *
698      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
699      * provisioning via an NFC bump.
700      */
701     public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
702         = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
703 
704     /**
705      * A String extra holding the proxy bypass for the wifi network in
706      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
707      *
708      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
709      * provisioning via an NFC bump.
710      */
711     public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
712         = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
713 
714     /**
715      * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
716      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
717      *
718      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
719      * provisioning via an NFC bump.
720      */
721     public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
722         = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
723 
724     /**
725      * A String extra holding a url that specifies the download location of the device admin
726      * package. When not provided it is assumed that the device admin package is already installed.
727      *
728      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
729      * provisioning via an NFC bump.
730      */
731     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
732         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
733 
734     /**
735      * A String extra holding the localized name of the organization under management.
736      *
737      * The name is displayed only during provisioning.
738      *
739      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
740      *
741      * @hide
742      */
743     @SystemApi
744     public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
745             "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
746 
747     /**
748      * A String extra holding a url to the website of the device provider so the user can open it
749      * during provisioning. If the url is not HTTPS, an error will be shown.
750      *
751      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
752      *
753      * @hide
754      */
755     @SystemApi
756     public static final String EXTRA_PROVISIONING_SUPPORT_URL =
757             "android.app.extra.PROVISIONING_SUPPORT_URL";
758 
759     /**
760      * A String extra holding the localized name of the device admin package. It should be the same
761      * as the app label of the package.
762      *
763      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
764      *
765      * @hide
766      */
767     @SystemApi
768     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
769             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
770 
771     /**
772      * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
773      * shown during the provisioning.
774      * <h5>The following URI schemes are accepted:</h5>
775      * <ul>
776      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
777      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
778      * </ul>
779      *
780      * <p> It is the responsibility of the caller to provide an image with a reasonable
781      * pixel density for the device.
782      *
783      * <p> If a content: URI is passed, the intent should have the flag
784      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
785      * {@link android.content.ClipData} of the intent too.
786      *
787      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
788      *
789      * @hide
790      */
791     @SystemApi
792     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
793             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
794 
795     /**
796      * An int extra holding a minimum required version code for the device admin package. If the
797      * device admin is already installed on the device, it will only be re-downloaded from
798      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
799      * installed package is less than this version code.
800      *
801      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
802      * provisioning via an NFC bump.
803      */
804     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
805         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
806 
807     /**
808      * A String extra holding a http cookie header which should be used in the http request to the
809      * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
810      *
811      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
812      * provisioning via an NFC bump.
813      */
814     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
815         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
816 
817     /**
818      * A String extra holding the URL-safe base64 encoded SHA-256 or SHA-1 hash (see notes below) of
819      * the file at download location specified in
820      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
821      *
822      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
823      * present. The provided checksum must match the checksum of the file at the download
824      * location. If the checksum doesn't match an error will be shown to the user and the user will
825      * be asked to factory reset the device.
826      *
827      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
828      * provisioning via an NFC bump.
829      *
830      * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
831      * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
832      * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
833      * addition to SHA-1. Support for SHA-1 is likely to be removed in future OS releases.
834      */
835     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
836         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
837 
838     /**
839      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
840      * android package archive at the download location specified in {@link
841      * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
842      *
843      * <p>The signatures of an android package archive can be obtained using
844      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
845      * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
846      *
847      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
848      * present. The provided checksum must match the checksum of any signature of the file at
849      * the download location. If the checksum does not match an error will be shown to the user and
850      * the user will be asked to factory reset the device.
851      *
852      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
853      * provisioning via an NFC bump.
854      */
855     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
856         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
857 
858     /**
859      * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
860      * has completed successfully.
861      *
862      * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
863      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
864      *
865      * <p>This intent will contain the following extras
866      * <ul>
867      * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
868      * profile.</li>
869      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
870      * be migrated at provisioning time, if any.</li>
871      * </ul>
872      */
873     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
874     public static final String ACTION_MANAGED_PROFILE_PROVISIONED
875         = "android.app.action.MANAGED_PROFILE_PROVISIONED";
876 
877     /**
878      * Activity action: This activity action is sent to indicate that provisioning of a managed
879      * profile or managed device has completed successfully. It'll be sent at the same time as
880      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
881      * delivered faster as it's an activity intent.
882      *
883      * <p>The intent is only sent to the new device or profile owner.
884      *
885      * @see #ACTION_PROVISION_MANAGED_PROFILE
886      * @see #ACTION_PROVISION_MANAGED_DEVICE
887      */
888     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
889     public static final String ACTION_PROVISIONING_SUCCESSFUL =
890             "android.app.action.PROVISIONING_SUCCESSFUL";
891 
892     /**
893      * A boolean extra indicating whether device encryption can be skipped as part of device owner
894      * or managed profile provisioning.
895      *
896      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
897      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
898      *
899      * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
900      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
901      */
902     public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
903              "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
904 
905     /**
906      * A {@link Uri} extra pointing to a logo image. This image will be shown during the
907      * provisioning. If this extra is not passed, a default image will be shown.
908      * <h5>The following URI schemes are accepted:</h5>
909      * <ul>
910      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
911      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
912      * </ul>
913      *
914      * <p> It is the responsibility of the caller to provide an image with a reasonable
915      * pixel density for the device.
916      *
917      * <p> If a content: URI is passed, the intent should have the flag
918      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
919      * {@link android.content.ClipData} of the intent too.
920      *
921      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
922      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
923      */
924     public static final String EXTRA_PROVISIONING_LOGO_URI =
925             "android.app.extra.PROVISIONING_LOGO_URI";
926 
927     /**
928      * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
929      * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
930      * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
931      * content.
932      *
933      * <p> The extra typically contains one disclaimer from the company of mobile device
934      * management application (MDM), and one disclaimer from the organization.
935      *
936      * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
937      *
938      * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
939      *
940      * <p> Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
941      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
942      */
943     public static final String EXTRA_PROVISIONING_DISCLAIMERS =
944             "android.app.extra.PROVISIONING_DISCLAIMERS";
945 
946     /**
947      * A String extra of localized disclaimer header.
948      *
949      * <p> The extra is typically the company name of mobile device management application (MDM)
950      * or the organization name.
951      *
952      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
953      *
954      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
955      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
956      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
957      *
958      * <pre>
959      *  &lt;meta-data
960      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
961      *      android:resource="@string/disclaimer_header"
962      * /&gt;</pre>
963      */
964     public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
965             "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
966 
967     /**
968      * A {@link Uri} extra pointing to disclaimer content.
969      *
970      * <h5>The following URI schemes are accepted:</h5>
971      * <ul>
972      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
973      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
974      * </ul>
975      *
976      * <p> Styled text is supported in the disclaimer content. The content is parsed by
977      * {@link android.text.Html#fromHtml(String)} and displayed in a
978      * {@link android.widget.TextView}.
979      *
980      * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
981      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
982      * {@link android.content.ClipData} of the intent too.
983      *
984      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
985      *
986      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
987      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
988      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
989      *
990      * <pre>
991      *  &lt;meta-data
992      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
993      *      android:resource="@string/disclaimer_content"
994      * /&gt;</pre>
995      */
996     public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
997             "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
998 
999     /**
1000      * A boolean extra indicating if user setup should be skipped, for when provisioning is started
1001      * during setup-wizard.
1002      *
1003      * <p>If unspecified, defaults to {@code true} to match the behavior in
1004      * {@link android.os.Build.VERSION_CODES#M} and earlier.
1005      *
1006      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or
1007      * {@link #ACTION_PROVISION_MANAGED_USER}.
1008      *
1009      * @hide
1010      */
1011     public static final String EXTRA_PROVISIONING_SKIP_USER_SETUP =
1012             "android.app.extra.PROVISIONING_SKIP_USER_SETUP";
1013 
1014     /**
1015      * A boolean extra indicating if the user consent steps from the provisioning flow should be
1016      * skipped. If unspecified, defaults to {@code false}.
1017      *
1018      * It can only be used by an existing device owner trying to create a managed profile via
1019      * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1020      */
1021     public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1022             "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1023 
1024     /**
1025      * A boolean extra indicating if mobile data should be used during NFC device owner provisioning
1026      * for downloading the mobile device management application. If {@link
1027      * #EXTRA_PROVISIONING_WIFI_SSID} is also specified, wifi network will be used instead.
1028      *
1029      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1030      * provisioning via an NFC bump.
1031      *
1032      * @hide
1033      */
1034     public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA =
1035             "android.app.extra.PROVISIONING_USE_MOBILE_DATA";
1036 
1037     /**
1038      * This MIME type is used for starting the device owner provisioning.
1039      *
1040      * <p>During device owner provisioning a device admin app is set as the owner of the device.
1041      * A device owner has full control over the device. The device owner can not be modified by the
1042      * user and the only way of resetting the device is if the device owner app calls a factory
1043      * reset.
1044      *
1045      * <p> A typical use case would be a device that is owned by a company, but used by either an
1046      * employee or client.
1047      *
1048      * <p> The NFC message must be sent to an unprovisioned device.
1049      *
1050      * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1051      * contains the following properties:
1052      * <ul>
1053      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1054      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1055      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1056      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1057      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1058      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1059      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1060      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1061      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1062      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1063      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1064      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1065      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1066      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1067      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1068      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from
1069      * {@link android.os.Build.VERSION_CODES#M} </li></ul>
1070      *
1071      * <p>
1072      * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1073      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1074      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1075      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1076      */
1077     public static final String MIME_TYPE_PROVISIONING_NFC
1078         = "application/com.android.managedprovisioning";
1079 
1080     /**
1081      * Activity action: ask the user to add a new device administrator to the system.
1082      * The desired policy is the ComponentName of the policy in the
1083      * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
1084      * bring the user through adding the device administrator to the system (or
1085      * allowing them to reject it).
1086      *
1087      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1088      * field to provide the user with additional explanation (in addition
1089      * to your component's description) about what is being added.
1090      *
1091      * <p>If your administrator is already active, this will ordinarily return immediately (without
1092      * user intervention).  However, if your administrator has been updated and is requesting
1093      * additional uses-policy flags, the user will be presented with the new list.  New policies
1094      * will not be available to the updated administrator until the user has accepted the new list.
1095      */
1096     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1097     public static final String ACTION_ADD_DEVICE_ADMIN
1098             = "android.app.action.ADD_DEVICE_ADMIN";
1099 
1100     /**
1101      * @hide
1102      * Activity action: ask the user to add a new device administrator as the profile owner
1103      * for this user. Only system apps can launch this intent.
1104      *
1105      * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
1106      * extra field. This will invoke a UI to bring the user through adding the profile owner admin
1107      * to remotely control restrictions on the user.
1108      *
1109      * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
1110      * result of whether or not the user approved the action. If approved, the result will
1111      * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
1112      * as a profile owner.
1113      *
1114      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1115      * field to provide the user with additional explanation (in addition
1116      * to your component's description) about what is being added.
1117      *
1118      * <p>If there is already a profile owner active or the caller is not a system app, the
1119      * operation will return a failure result.
1120      */
1121     @SystemApi
1122     public static final String ACTION_SET_PROFILE_OWNER
1123             = "android.app.action.SET_PROFILE_OWNER";
1124 
1125     /**
1126      * @hide
1127      * Name of the profile owner admin that controls the user.
1128      */
1129     @SystemApi
1130     public static final String EXTRA_PROFILE_OWNER_NAME
1131             = "android.app.extra.PROFILE_OWNER_NAME";
1132 
1133     /**
1134      * Broadcast action: send when any policy admin changes a policy.
1135      * This is generally used to find out when a new policy is in effect.
1136      *
1137      * @hide
1138      */
1139     public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1140             = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
1141 
1142     /**
1143      * Broadcast action: sent when the device owner is set, changed or cleared.
1144      *
1145      * This broadcast is sent only to the primary user.
1146      * @see #ACTION_PROVISION_MANAGED_DEVICE
1147      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1148      */
1149     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1150     public static final String ACTION_DEVICE_OWNER_CHANGED
1151             = "android.app.action.DEVICE_OWNER_CHANGED";
1152 
1153     /**
1154      * The ComponentName of the administrator component.
1155      *
1156      * @see #ACTION_ADD_DEVICE_ADMIN
1157      */
1158     public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
1159 
1160     /**
1161      * An optional CharSequence providing additional explanation for why the
1162      * admin is being added.
1163      *
1164      * @see #ACTION_ADD_DEVICE_ADMIN
1165      */
1166     public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
1167 
1168     /**
1169      * Constant to indicate the feature of disabling the camera. Used as argument to
1170      * {@link #createAdminSupportIntent(String)}.
1171      * @see #setCameraDisabled(ComponentName, boolean)
1172      */
1173     public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
1174 
1175     /**
1176      * Constant to indicate the feature of disabling screen captures. Used as argument to
1177      * {@link #createAdminSupportIntent(String)}.
1178      * @see #setScreenCaptureDisabled(ComponentName, boolean)
1179      */
1180     public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
1181 
1182     /**
1183      * Constant to indicate the feature of mandatory backups. Used as argument to
1184      * {@link #createAdminSupportIntent(String)}.
1185      * @see #setMandatoryBackupTransport(ComponentName, ComponentName)
1186      * @hide
1187      */
1188     public static final String POLICY_MANDATORY_BACKUPS = "policy_mandatory_backups";
1189 
1190     /**
1191      * Constant to indicate the feature of suspending app. Use it as the value of
1192      * {@link #EXTRA_RESTRICTION}.
1193      * @hide
1194      */
1195     public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
1196 
1197     /**
1198      * A String indicating a specific restricted feature. Can be a user restriction from the
1199      * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1200      * {@link #POLICY_DISABLE_CAMERA}, {@link #POLICY_DISABLE_SCREEN_CAPTURE} or
1201      * {@link #POLICY_MANDATORY_BACKUPS}.
1202      * @see #createAdminSupportIntent(String)
1203      * @hide
1204      */
1205     @TestApi
1206     public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1207 
1208     /**
1209      * Activity action: have the user enter a new password. This activity should
1210      * be launched after using {@link #setPasswordQuality(ComponentName, int)},
1211      * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
1212      * enter a new password that meets the current requirements. You can use
1213      * {@link #isActivePasswordSufficient()} to determine whether you need to
1214      * have the user select a new password in order to meet the current
1215      * constraints. Upon being resumed from this activity, you can check the new
1216      * password characteristics to see if they are sufficient.
1217      *
1218      * If the intent is launched from within a managed profile with a profile
1219      * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1220      * this will trigger entering a new password for the parent of the profile.
1221      * For all other cases it will trigger entering a new password for the user
1222      * or profile it is launched from.
1223      *
1224      * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1225      */
1226     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1227     public static final String ACTION_SET_NEW_PASSWORD
1228             = "android.app.action.SET_NEW_PASSWORD";
1229 
1230     /**
1231      * Activity action: have the user enter a new password for the parent profile.
1232      * If the intent is launched from within a managed profile, this will trigger
1233      * entering a new password for the parent of the profile. In all other cases
1234      * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
1235      */
1236     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1237     public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1238             = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1239 
1240     /**
1241      * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1242      * Network logging was enabled and the user tapped the notification.
1243      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1244      * @hide
1245      */
1246     public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1247             = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1248 
1249     /**
1250      * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1251      * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1252      * {@link #EXTRA_DELEGATION_SCOPES} key.
1253      *
1254      * <p class=”note”> Note: This is a protected intent that can only be sent by the system.</p>
1255      */
1256     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1257     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1258             "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1259 
1260     /**
1261      * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1262      * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1263      */
1264     public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1265 
1266     /**
1267      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1268      * the parent profile to access intents sent from the managed profile.
1269      * That is, when an app in the managed profile calls
1270      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1271      * matching activity in the parent profile.
1272      */
1273     public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1274 
1275     /**
1276      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1277      * the managed profile to access intents sent from the parent profile.
1278      * That is, when an app in the parent profile calls
1279      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1280      * matching activity in the managed profile.
1281      */
1282     public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1283 
1284     /**
1285      * Broadcast action: notify that a new local system update policy has been set by the device
1286      * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1287      */
1288     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1289     public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1290             = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1291 
1292     /**
1293      * Broadcast action to notify ManagedProvisioning that
1294      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has changed.
1295      * @hide
1296      */
1297     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1298     public static final String ACTION_DATA_SHARING_RESTRICTION_CHANGED =
1299             "android.app.action.DATA_SHARING_RESTRICTION_CHANGED";
1300 
1301     /**
1302      * Broadcast action from ManagedProvisioning to notify that the latest change to
1303      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
1304      * applied (cross profile intent filters updated). Only usesd for CTS tests.
1305      * @hide
1306      */
1307     @TestApi
1308     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1309     public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
1310             "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
1311 
1312     /**
1313      * Permission policy to prompt user for new permission requests for runtime permissions.
1314      * Already granted or denied permissions are not affected by this.
1315      */
1316     public static final int PERMISSION_POLICY_PROMPT = 0;
1317 
1318     /**
1319      * Permission policy to always grant new permission requests for runtime permissions.
1320      * Already granted or denied permissions are not affected by this.
1321      */
1322     public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1323 
1324     /**
1325      * Permission policy to always deny new permission requests for runtime permissions.
1326      * Already granted or denied permissions are not affected by this.
1327      */
1328     public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1329 
1330     /**
1331      * Runtime permission state: The user can manage the permission
1332      * through the UI.
1333      */
1334     public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1335 
1336     /**
1337      * Runtime permission state: The permission is granted to the app
1338      * and the user cannot manage the permission through the UI.
1339      */
1340     public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1341 
1342     /**
1343      * Runtime permission state: The permission is denied to the app
1344      * and the user cannot manage the permission through the UI.
1345      */
1346     public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1347 
1348     /**
1349      * Delegation of certificate installation and management. This scope grants access to the
1350      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1351      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1352      */
1353     public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1354 
1355     /**
1356      * Delegation of application restrictions management. This scope grants access to the
1357      * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1358      */
1359     public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1360 
1361     /**
1362      * Delegation of application uninstall block. This scope grants access to the
1363      * {@link #setUninstallBlocked} API.
1364      */
1365     public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1366 
1367     /**
1368      * Delegation of permission policy and permission grant state. This scope grants access to the
1369      * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1370      * and {@link #setPermissionGrantState} APIs.
1371      */
1372     public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1373 
1374     /**
1375      * Delegation of package access state. This scope grants access to the
1376      * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1377      * {@link #setPackagesSuspended} APIs.
1378      */
1379     public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1380 
1381     /**
1382      * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1383      * API.
1384      */
1385     public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1386 
1387     /**
1388      * Delegation for installing existing packages. This scope grants access to the
1389      * {@link #installExistingPackage} API.
1390      */
1391     public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
1392             "delegation-install-existing-package";
1393 
1394     /**
1395      * Delegation of management of uninstalled packages. This scope grants access to the
1396      * {@code #setKeepUninstalledPackages} and {@code #getKeepUninstalledPackages} APIs.
1397      */
1398     public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1399             "delegation-keep-uninstalled-packages";
1400 
1401     /**
1402      * No management for current user in-effect. This is the default.
1403      * @hide
1404      */
1405     @SystemApi
1406     public static final int STATE_USER_UNMANAGED = 0;
1407 
1408     /**
1409      * Management partially setup, user setup needs to be completed.
1410      * @hide
1411      */
1412     @SystemApi
1413     public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1414 
1415     /**
1416      * Management partially setup, user setup completed.
1417      * @hide
1418      */
1419     @SystemApi
1420     public static final int STATE_USER_SETUP_COMPLETE = 2;
1421 
1422     /**
1423      * Management setup and active on current user.
1424      * @hide
1425      */
1426     @SystemApi
1427     public static final int STATE_USER_SETUP_FINALIZED = 3;
1428 
1429     /**
1430      * Management partially setup on a managed profile.
1431      * @hide
1432      */
1433     @SystemApi
1434     public static final int STATE_USER_PROFILE_COMPLETE = 4;
1435 
1436     /**
1437      * @hide
1438      */
1439     @IntDef(prefix = { "STATE_USER_" }, value = {
1440             STATE_USER_UNMANAGED,
1441             STATE_USER_SETUP_INCOMPLETE,
1442             STATE_USER_SETUP_COMPLETE,
1443             STATE_USER_SETUP_FINALIZED,
1444             STATE_USER_PROFILE_COMPLETE
1445     })
1446     @Retention(RetentionPolicy.SOURCE)
1447     public @interface UserProvisioningState {}
1448 
1449     /**
1450      * Result code for {@link #checkProvisioningPreCondition}.
1451      *
1452      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1453      * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1454      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when provisioning is allowed.
1455      *
1456      * @hide
1457      */
1458     public static final int CODE_OK = 0;
1459 
1460     /**
1461      * Result code for {@link #checkProvisioningPreCondition}.
1462      *
1463      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1464      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the device already has a device
1465      * owner.
1466      *
1467      * @hide
1468      */
1469     public static final int CODE_HAS_DEVICE_OWNER = 1;
1470 
1471     /**
1472      * Result code for {@link #checkProvisioningPreCondition}.
1473      *
1474      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1475      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user has a profile owner and for
1476      * {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
1477      *
1478      * @hide
1479      */
1480     public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
1481 
1482     /**
1483      * Result code for {@link #checkProvisioningPreCondition}.
1484      *
1485      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1486      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user isn't running.
1487      *
1488      * @hide
1489      */
1490     public static final int CODE_USER_NOT_RUNNING = 3;
1491 
1492     /**
1493      * Result code for {@link #checkProvisioningPreCondition}.
1494      *
1495      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1496      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the device has already been setup and
1497      * for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
1498      *
1499      * @hide
1500      */
1501     public static final int CODE_USER_SETUP_COMPLETED = 4;
1502 
1503     /**
1504      * Code used to indicate that the device also has a user other than the system user.
1505      *
1506      * @hide
1507      */
1508     public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
1509 
1510     /**
1511      * Code used to indicate that device has an account that prevents provisioning.
1512      *
1513      * @hide
1514      */
1515     public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
1516 
1517     /**
1518      * Result code for {@link #checkProvisioningPreCondition}.
1519      *
1520      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1521      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the user is not a system user.
1522      *
1523      * @hide
1524      */
1525     public static final int CODE_NOT_SYSTEM_USER = 7;
1526 
1527     /**
1528      * Result code for {@link #checkProvisioningPreCondition}.
1529      *
1530      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1531      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} and {@link #ACTION_PROVISION_MANAGED_USER}
1532      * when the device is a watch and is already paired.
1533      *
1534      * @hide
1535      */
1536     public static final int CODE_HAS_PAIRED = 8;
1537 
1538     /**
1539      * Result code for {@link #checkProvisioningPreCondition}.
1540      *
1541      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
1542      * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
1543      *
1544      * @see {@link PackageManager#FEATURE_MANAGED_USERS}
1545      * @hide
1546      */
1547     public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
1548 
1549     /**
1550      * Result code for {@link #checkProvisioningPreCondition}.
1551      *
1552      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user.
1553      *
1554      * @hide
1555      */
1556     public static final int CODE_SYSTEM_USER = 10;
1557 
1558     /**
1559      * Result code for {@link #checkProvisioningPreCondition}.
1560      *
1561      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
1562      * managed profiles.
1563      *
1564      * @hide
1565      */
1566     public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
1567 
1568     /**
1569      * Result code for {@link #checkProvisioningPreCondition}.
1570      *
1571      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} and
1572      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices not running with split system
1573      * user.
1574      *
1575      * @hide
1576      */
1577     public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
1578 
1579     /**
1580      * Result code for {@link #checkProvisioningPreCondition}.
1581      *
1582      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1583      * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1584      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices which do no support device
1585      * admins.
1586      *
1587      * @hide
1588      */
1589     public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
1590 
1591     /**
1592      * Result code for {@link #checkProvisioningPreCondition}.
1593      *
1594      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the device the user is a
1595      * system user on a split system user device.
1596      *
1597      * @hide
1598      */
1599     public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
1600 
1601     /**
1602      * Result code for {@link #checkProvisioningPreCondition}.
1603      *
1604      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when adding a managed profile is
1605      * disallowed by {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
1606      *
1607      * @hide
1608      */
1609     public static final int CODE_ADD_MANAGED_PROFILE_DISALLOWED = 15;
1610 
1611     /**
1612      * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
1613      * conditions.
1614      *
1615      * @hide
1616      */
1617     @Retention(RetentionPolicy.SOURCE)
1618     @IntDef(prefix = { "CODE_" }, value = {
1619             CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
1620             CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
1621             CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
1622             CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
1623             CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER, CODE_ADD_MANAGED_PROFILE_DISALLOWED
1624     })
1625     public @interface ProvisioningPreCondition {}
1626 
1627     /**
1628      * Disable all configurable SystemUI features during LockTask mode. This includes,
1629      * <ul>
1630      *     <li>system info area in the status bar (connectivity icons, clock, etc.)
1631      *     <li>notifications (including alerts, icons, and the notification shade)
1632      *     <li>Home button
1633      *     <li>Recents button and UI
1634      *     <li>global actions menu (i.e. power button menu)
1635      *     <li>keyguard
1636      * </ul>
1637      *
1638      * @see #setLockTaskFeatures(ComponentName, int)
1639      */
1640     public static final int LOCK_TASK_FEATURE_NONE = 0;
1641 
1642     /**
1643      * Enable the system info area in the status bar during LockTask mode. The system info area
1644      * usually occupies the right side of the status bar (although this can differ across OEMs). It
1645      * includes all system information indicators, such as date and time, connectivity, battery,
1646      * vibration mode, etc.
1647      *
1648      * @see #setLockTaskFeatures(ComponentName, int)
1649      */
1650     public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
1651 
1652     /**
1653      * Enable notifications during LockTask mode. This includes notification icons on the status
1654      * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
1655      * Settings panel remains disabled. This feature flag can only be used in combination with
1656      * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
1657      * throws an {@link IllegalArgumentException} if this feature flag is defined without
1658      * {@link #LOCK_TASK_FEATURE_HOME}.
1659      *
1660      * @see #setLockTaskFeatures(ComponentName, int)
1661      */
1662     public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
1663 
1664     /**
1665      * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
1666      * to be registered as the default launcher with
1667      * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
1668      * package needs to be whitelisted for LockTask with
1669      * {@link #setLockTaskPackages(ComponentName, String[])}.
1670      *
1671      * @see #setLockTaskFeatures(ComponentName, int)
1672      */
1673     public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
1674 
1675     /**
1676      * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
1677      * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
1678      * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
1679      * {@link IllegalArgumentException} if this feature flag is defined without
1680      * {@link #LOCK_TASK_FEATURE_HOME}.
1681      *
1682      * @see #setLockTaskFeatures(ComponentName, int)
1683      */
1684     public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
1685 
1686     /**
1687      * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
1688      * the user long-presses the power button, for example. Note that the user may not be able to
1689      * power off the device if this flag is not set.
1690      *
1691      * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
1692      * called for the first time.
1693      *
1694      * @see #setLockTaskFeatures(ComponentName, int)
1695      */
1696     public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
1697 
1698     /**
1699      * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
1700      * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
1701      * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
1702      * credential.
1703      *
1704      * @see #setLockTaskFeatures(ComponentName, int)
1705      */
1706     public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
1707 
1708     /**
1709      * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
1710      *
1711      * @hide
1712      */
1713     @Retention(RetentionPolicy.SOURCE)
1714     @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
1715             LOCK_TASK_FEATURE_NONE,
1716             LOCK_TASK_FEATURE_SYSTEM_INFO,
1717             LOCK_TASK_FEATURE_NOTIFICATIONS,
1718             LOCK_TASK_FEATURE_HOME,
1719             LOCK_TASK_FEATURE_OVERVIEW,
1720             LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
1721             LOCK_TASK_FEATURE_KEYGUARD
1722     })
1723     public @interface LockTaskFeature {}
1724 
1725     /**
1726      * Service action: Action for a service that device owner and profile owner can optionally
1727      * own.  If a device owner or a profile owner has such a service, the system tries to keep
1728      * a bound connection to it, in order to keep their process always running.
1729      * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
1730      * permission.
1731      */
1732     @SdkConstant(SdkConstantType.SERVICE_ACTION)
1733     public static final String ACTION_DEVICE_ADMIN_SERVICE
1734             = "android.app.action.DEVICE_ADMIN_SERVICE";
1735 
1736     /** @hide */
1737     @Retention(RetentionPolicy.SOURCE)
1738     @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
1739         ID_TYPE_BASE_INFO,
1740         ID_TYPE_SERIAL,
1741         ID_TYPE_IMEI,
1742         ID_TYPE_MEID
1743     })
1744     public @interface AttestationIdType {}
1745 
1746     /**
1747      * Specifies that the device should attest its manufacturer details. For use with
1748      * {@link #generateKeyPair}.
1749      *
1750      * @see #generateKeyPair
1751      */
1752     public static final int ID_TYPE_BASE_INFO = 1;
1753 
1754     /**
1755      * Specifies that the device should attest its serial number. For use with
1756      * {@link #generateKeyPair}.
1757      *
1758      * @see #generateKeyPair
1759      */
1760     public static final int ID_TYPE_SERIAL = 2;
1761 
1762     /**
1763      * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
1764      *
1765      * @see #generateKeyPair
1766      */
1767     public static final int ID_TYPE_IMEI = 4;
1768 
1769     /**
1770      * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
1771      *
1772      * @see #generateKeyPair
1773      */
1774     public static final int ID_TYPE_MEID = 8;
1775 
1776     /**
1777      * Specifies that the calling app should be granted access to the installed credentials
1778      * immediately. Otherwise, access to the credentials will be gated by user approval.
1779      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
1780      *
1781      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
1782      */
1783     public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
1784 
1785     /**
1786      * Specifies that a user can select the key via the Certificate Selection prompt.
1787      * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
1788      * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
1789      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
1790      *
1791      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
1792      */
1793     public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
1794 
1795     /**
1796      * Broadcast action: sent when the profile owner is set, changed or cleared.
1797      *
1798      * This broadcast is sent only to the user managed by the new profile owner.
1799      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1800      */
1801     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1802     public static final String ACTION_PROFILE_OWNER_CHANGED =
1803             "android.app.action.PROFILE_OWNER_CHANGED";
1804 
1805     /**
1806      * Return true if the given administrator component is currently active (enabled) in the system.
1807      *
1808      * @param admin The administrator component to check for.
1809      * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
1810      *         otherwise
1811      */
isAdminActive(@onNull ComponentName admin)1812     public boolean isAdminActive(@NonNull ComponentName admin) {
1813         throwIfParentInstance("isAdminActive");
1814         return isAdminActiveAsUser(admin, myUserId());
1815     }
1816 
1817     /**
1818      * @see #isAdminActive(ComponentName)
1819      * @hide
1820      */
isAdminActiveAsUser(@onNull ComponentName admin, int userId)1821     public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
1822         if (mService != null) {
1823             try {
1824                 return mService.isAdminActive(admin, userId);
1825             } catch (RemoteException e) {
1826                 throw e.rethrowFromSystemServer();
1827             }
1828         }
1829         return false;
1830     }
1831 
1832     /**
1833      * Return true if the given administrator component is currently being removed
1834      * for the user.
1835      * @hide
1836      */
isRemovingAdmin(@onNull ComponentName admin, int userId)1837     public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
1838         if (mService != null) {
1839             try {
1840                 return mService.isRemovingAdmin(admin, userId);
1841             } catch (RemoteException e) {
1842                 throw e.rethrowFromSystemServer();
1843             }
1844         }
1845         return false;
1846     }
1847 
1848     /**
1849      * Return a list of all currently active device administrators' component
1850      * names.  If there are no administrators {@code null} may be
1851      * returned.
1852      */
getActiveAdmins()1853     public @Nullable List<ComponentName> getActiveAdmins() {
1854         throwIfParentInstance("getActiveAdmins");
1855         return getActiveAdminsAsUser(myUserId());
1856     }
1857 
1858     /**
1859      * @see #getActiveAdmins()
1860      * @hide
1861      */
getActiveAdminsAsUser(int userId)1862     public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
1863         if (mService != null) {
1864             try {
1865                 return mService.getActiveAdmins(userId);
1866             } catch (RemoteException e) {
1867                 throw e.rethrowFromSystemServer();
1868             }
1869         }
1870         return null;
1871     }
1872 
1873     /**
1874      * Used by package administration code to determine if a package can be stopped
1875      * or uninstalled.
1876      * @hide
1877      */
1878     @SystemApi
1879     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
packageHasActiveAdmins(String packageName)1880     public boolean packageHasActiveAdmins(String packageName) {
1881         return packageHasActiveAdmins(packageName, myUserId());
1882     }
1883 
1884     /**
1885      * Used by package administration code to determine if a package can be stopped
1886      * or uninstalled.
1887      * @hide
1888      */
packageHasActiveAdmins(String packageName, int userId)1889     public boolean packageHasActiveAdmins(String packageName, int userId) {
1890         if (mService != null) {
1891             try {
1892                 return mService.packageHasActiveAdmins(packageName, userId);
1893             } catch (RemoteException e) {
1894                 throw e.rethrowFromSystemServer();
1895             }
1896         }
1897         return false;
1898     }
1899 
1900     /**
1901      * Remove a current administration component.  This can only be called
1902      * by the application that owns the administration component; if you
1903      * try to remove someone else's component, a security exception will be
1904      * thrown.
1905      *
1906      * <p>Note that the operation is not synchronous and the admin might still be active (as
1907      * indicated by {@link #getActiveAdmins()}) by the time this method returns.
1908      *
1909      * @param admin The administration compononent to remove.
1910      * @throws SecurityException if the caller is not in the owner application of {@code admin}.
1911      */
removeActiveAdmin(@onNull ComponentName admin)1912     public void removeActiveAdmin(@NonNull ComponentName admin) {
1913         throwIfParentInstance("removeActiveAdmin");
1914         if (mService != null) {
1915             try {
1916                 mService.removeActiveAdmin(admin, myUserId());
1917             } catch (RemoteException e) {
1918                 throw e.rethrowFromSystemServer();
1919             }
1920         }
1921     }
1922 
1923     /**
1924      * Returns true if an administrator has been granted a particular device policy. This can be
1925      * used to check whether the administrator was activated under an earlier set of policies, but
1926      * requires additional policies after an upgrade.
1927      *
1928      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
1929      *            active administrator, or an exception will be thrown.
1930      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
1931      * @throws SecurityException if {@code admin} is not an active administrator.
1932      */
hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)1933     public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
1934         throwIfParentInstance("hasGrantedPolicy");
1935         if (mService != null) {
1936             try {
1937                 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
1938             } catch (RemoteException e) {
1939                 throw e.rethrowFromSystemServer();
1940             }
1941         }
1942         return false;
1943     }
1944 
1945     /**
1946      * Returns true if the Profile Challenge is available to use for the given profile user.
1947      *
1948      * @hide
1949      */
isSeparateProfileChallengeAllowed(int userHandle)1950     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
1951         if (mService != null) {
1952             try {
1953                 return mService.isSeparateProfileChallengeAllowed(userHandle);
1954             } catch (RemoteException e) {
1955                 throw e.rethrowFromSystemServer();
1956             }
1957         }
1958         return false;
1959     }
1960 
1961     /**
1962      * Constant for {@link #setPasswordQuality}: the policy has no requirements
1963      * for the password.  Note that quality constants are ordered so that higher
1964      * values are more restrictive.
1965      */
1966     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
1967 
1968     /**
1969      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
1970      * recognition technology.  This implies technologies that can recognize the identity of
1971      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
1972      * Note that quality constants are ordered so that higher values are more restrictive.
1973      */
1974     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
1975 
1976     /**
1977      * Constant for {@link #setPasswordQuality}: the policy requires some kind
1978      * of password or pattern, but doesn't care what it is. Note that quality constants
1979      * are ordered so that higher values are more restrictive.
1980      */
1981     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
1982 
1983     /**
1984      * Constant for {@link #setPasswordQuality}: the user must have entered a
1985      * password containing at least numeric characters.  Note that quality
1986      * constants are ordered so that higher values are more restrictive.
1987      */
1988     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
1989 
1990     /**
1991      * Constant for {@link #setPasswordQuality}: the user must have entered a
1992      * password containing at least numeric characters with no repeating (4444)
1993      * or ordered (1234, 4321, 2468) sequences.  Note that quality
1994      * constants are ordered so that higher values are more restrictive.
1995      */
1996     public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
1997 
1998     /**
1999      * Constant for {@link #setPasswordQuality}: the user must have entered a
2000      * password containing at least alphabetic (or other symbol) characters.
2001      * Note that quality constants are ordered so that higher values are more
2002      * restrictive.
2003      */
2004     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
2005 
2006     /**
2007      * Constant for {@link #setPasswordQuality}: the user must have entered a
2008      * password containing at least <em>both></em> numeric <em>and</em>
2009      * alphabetic (or other symbol) characters.  Note that quality constants are
2010      * ordered so that higher values are more restrictive.
2011      */
2012     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
2013 
2014     /**
2015      * Constant for {@link #setPasswordQuality}: the user must have entered a
2016      * password containing at least a letter, a numerical digit and a special
2017      * symbol, by default. With this password quality, passwords can be
2018      * restricted to contain various sets of characters, like at least an
2019      * uppercase letter, etc. These are specified using various methods,
2020      * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
2021      * that quality constants are ordered so that higher values are more
2022      * restrictive.
2023      */
2024     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
2025 
2026     /**
2027      * Constant for {@link #setPasswordQuality}: the user is not allowed to
2028      * modify password. In case this password quality is set, the password is
2029      * managed by a profile owner. The profile owner can set any password,
2030      * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
2031      * that quality constants are ordered so that higher values are more
2032      * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
2033      * the highest.
2034      * @hide
2035      */
2036     public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
2037 
2038     /**
2039      * @hide
2040      *
2041      * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
2042      * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
2043      * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
2044      * used by authenticator to exempt their accounts from this:
2045      *
2046      * <ul>
2047      *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
2048      *     <p>In order to make an apk test-only, add android:testOnly="true" to the
2049      *     &lt;application&gt; tag in the manifest.
2050      *
2051      *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
2052      *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
2053      *     Some authenticators claim to have any features, so to detect it, we also check
2054      *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
2055      *     if any of the accounts have it.
2056      * </ul>
2057      */
2058     @SystemApi
2059     @TestApi
2060     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
2061             "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
2062 
2063     /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
2064     @SystemApi
2065     @TestApi
2066     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
2067             "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
2068 
2069     /**
2070      * Called by an application that is administering the device to set the password restrictions it
2071      * is imposing. After setting this, the user will not be able to enter a new password that is
2072      * not at least as restrictive as what has been set. Note that the current password will remain
2073      * until the user has set a new one, so the change does not take place immediately. To prompt
2074      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2075      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
2076      * <p>
2077      * Quality constants are ordered so that higher values are more restrictive; thus the highest
2078      * requested quality constant (between the policy set here, the user's preference, and any other
2079      * considerations) is the one that is in effect.
2080      * <p>
2081      * The calling device admin must have requested
2082      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2083      * not, a security exception will be thrown.
2084      * <p>
2085      * This method can be called on the {@link DevicePolicyManager} instance returned by
2086      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2087      * profile.
2088      *
2089      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2090      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
2091      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
2092      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2093      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
2094      * @throws SecurityException if {@code admin} is not an active administrator or if {@code admin}
2095      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2096      */
setPasswordQuality(@onNull ComponentName admin, int quality)2097     public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
2098         if (mService != null) {
2099             try {
2100                 mService.setPasswordQuality(admin, quality, mParentInstance);
2101             } catch (RemoteException e) {
2102                 throw e.rethrowFromSystemServer();
2103             }
2104         }
2105     }
2106 
2107     /**
2108      * Retrieve the current minimum password quality for a particular admin or all admins that set
2109      * restrictions on this user and its participating profiles. Restrictions on profiles that have
2110      * a separate challenge are not taken into account.
2111      *
2112      * <p>This method can be called on the {@link DevicePolicyManager} instance
2113      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2114      * restrictions on the parent profile.
2115      *
2116      * @param admin The name of the admin component to check, or {@code null} to aggregate
2117      * all admins.
2118      */
getPasswordQuality(@ullable ComponentName admin)2119     public int getPasswordQuality(@Nullable ComponentName admin) {
2120         return getPasswordQuality(admin, myUserId());
2121     }
2122 
2123     /** @hide per-user version */
getPasswordQuality(@ullable ComponentName admin, int userHandle)2124     public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
2125         if (mService != null) {
2126             try {
2127                 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
2128             } catch (RemoteException e) {
2129                 throw e.rethrowFromSystemServer();
2130             }
2131         }
2132         return PASSWORD_QUALITY_UNSPECIFIED;
2133     }
2134 
2135     /**
2136      * Called by an application that is administering the device to set the minimum allowed password
2137      * length. After setting this, the user will not be able to enter a new password that is not at
2138      * least as restrictive as what has been set. Note that the current password will remain until
2139      * the user has set a new one, so the change does not take place immediately. To prompt the user
2140      * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2141      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2142      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2143      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2144      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
2145      * {@link #setPasswordQuality}.
2146      * <p>
2147      * The calling device admin must have requested
2148      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2149      * not, a security exception will be thrown.
2150      * <p>
2151      * This method can be called on the {@link DevicePolicyManager} instance returned by
2152      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2153      * profile.
2154      *
2155      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2156      * @param length The new desired minimum password length. A value of 0 means there is no
2157      *            restriction.
2158      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2159      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2160      */
setPasswordMinimumLength(@onNull ComponentName admin, int length)2161     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
2162         if (mService != null) {
2163             try {
2164                 mService.setPasswordMinimumLength(admin, length, mParentInstance);
2165             } catch (RemoteException e) {
2166                 throw e.rethrowFromSystemServer();
2167             }
2168         }
2169     }
2170 
2171     /**
2172      * Retrieve the current minimum password length for a particular admin or all admins that set
2173      * restrictions on this user and its participating profiles. Restrictions on profiles that have
2174      * a separate challenge are not taken into account.
2175      *
2176      * <p>This method can be called on the {@link DevicePolicyManager} instance
2177      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2178      * restrictions on the parent profile.
2179      *
2180      * user and its profiles or a particular one.
2181      * @param admin The name of the admin component to check, or {@code null} to aggregate
2182      * all admins.
2183      */
getPasswordMinimumLength(@ullable ComponentName admin)2184     public int getPasswordMinimumLength(@Nullable ComponentName admin) {
2185         return getPasswordMinimumLength(admin, myUserId());
2186     }
2187 
2188     /** @hide per-user version */
getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)2189     public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
2190         if (mService != null) {
2191             try {
2192                 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
2193             } catch (RemoteException e) {
2194                 throw e.rethrowFromSystemServer();
2195             }
2196         }
2197         return 0;
2198     }
2199 
2200     /**
2201      * Called by an application that is administering the device to set the minimum number of upper
2202      * case letters required in the password. After setting this, the user will not be able to enter
2203      * a new password that is not at least as restrictive as what has been set. Note that the
2204      * current password will remain until the user has set a new one, so the change does not take
2205      * place immediately. To prompt the user for a new password, use
2206      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2207      * setting this value. This constraint is only imposed if the administrator has also requested
2208      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2209      * <p>
2210      * The calling device admin must have requested
2211      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2212      * not, a security exception will be thrown.
2213      * <p>
2214      * This method can be called on the {@link DevicePolicyManager} instance returned by
2215      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2216      * profile.
2217      *
2218      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2219      * @param length The new desired minimum number of upper case letters required in the password.
2220      *            A value of 0 means there is no restriction.
2221      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2222      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2223      */
setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)2224     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
2225         if (mService != null) {
2226             try {
2227                 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
2228             } catch (RemoteException e) {
2229                 throw e.rethrowFromSystemServer();
2230             }
2231         }
2232     }
2233 
2234     /**
2235      * Retrieve the current number of upper case letters required in the password
2236      * for a particular admin or all admins that set restrictions on this user and
2237      * its participating profiles. Restrictions on profiles that have a separate challenge
2238      * are not taken into account.
2239      * This is the same value as set by
2240      * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
2241      * and only applies when the password quality is
2242      * {@link #PASSWORD_QUALITY_COMPLEX}.
2243      *
2244      * <p>This method can be called on the {@link DevicePolicyManager} instance
2245      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2246      * restrictions on the parent profile.
2247      *
2248      * @param admin The name of the admin component to check, or {@code null} to
2249      *            aggregate all admins.
2250      * @return The minimum number of upper case letters required in the
2251      *         password.
2252      */
getPasswordMinimumUpperCase(@ullable ComponentName admin)2253     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
2254         return getPasswordMinimumUpperCase(admin, myUserId());
2255     }
2256 
2257     /** @hide per-user version */
getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)2258     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
2259         if (mService != null) {
2260             try {
2261                 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
2262             } catch (RemoteException e) {
2263                 throw e.rethrowFromSystemServer();
2264             }
2265         }
2266         return 0;
2267     }
2268 
2269     /**
2270      * Called by an application that is administering the device to set the minimum number of lower
2271      * case letters required in the password. After setting this, the user will not be able to enter
2272      * a new password that is not at least as restrictive as what has been set. Note that the
2273      * current password will remain until the user has set a new one, so the change does not take
2274      * place immediately. To prompt the user for a new password, use
2275      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2276      * setting this value. This constraint is only imposed if the administrator has also requested
2277      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2278      * <p>
2279      * The calling device admin must have requested
2280      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2281      * not, a security exception will be thrown.
2282      * <p>
2283      * This method can be called on the {@link DevicePolicyManager} instance returned by
2284      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2285      * profile.
2286      *
2287      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2288      * @param length The new desired minimum number of lower case letters required in the password.
2289      *            A value of 0 means there is no restriction.
2290      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2291      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2292      */
setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)2293     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
2294         if (mService != null) {
2295             try {
2296                 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
2297             } catch (RemoteException e) {
2298                 throw e.rethrowFromSystemServer();
2299             }
2300         }
2301     }
2302 
2303     /**
2304      * Retrieve the current number of lower case letters required in the password
2305      * for a particular admin or all admins that set restrictions on this user
2306      * and its participating profiles. Restrictions on profiles that have
2307      * a separate challenge are not taken into account.
2308      * This is the same value as set by
2309      * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
2310      * and only applies when the password quality is
2311      * {@link #PASSWORD_QUALITY_COMPLEX}.
2312      *
2313      * <p>This method can be called on the {@link DevicePolicyManager} instance
2314      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2315      * restrictions on the parent profile.
2316      *
2317      * @param admin The name of the admin component to check, or {@code null} to
2318      *            aggregate all admins.
2319      * @return The minimum number of lower case letters required in the
2320      *         password.
2321      */
getPasswordMinimumLowerCase(@ullable ComponentName admin)2322     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
2323         return getPasswordMinimumLowerCase(admin, myUserId());
2324     }
2325 
2326     /** @hide per-user version */
getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)2327     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
2328         if (mService != null) {
2329             try {
2330                 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
2331             } catch (RemoteException e) {
2332                 throw e.rethrowFromSystemServer();
2333             }
2334         }
2335         return 0;
2336     }
2337 
2338     /**
2339      * Called by an application that is administering the device to set the minimum number of
2340      * letters required in the password. After setting this, the user will not be able to enter a
2341      * new password that is not at least as restrictive as what has been set. Note that the current
2342      * password will remain until the user has set a new one, so the change does not take place
2343      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2344      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2345      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2346      * {@link #setPasswordQuality}. The default value is 1.
2347      * <p>
2348      * The calling device admin must have requested
2349      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2350      * not, a security exception will be thrown.
2351      * <p>
2352      * This method can be called on the {@link DevicePolicyManager} instance returned by
2353      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2354      * profile.
2355      *
2356      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2357      * @param length The new desired minimum number of letters required in the password. A value of
2358      *            0 means there is no restriction.
2359      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2360      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2361      */
setPasswordMinimumLetters(@onNull ComponentName admin, int length)2362     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
2363         if (mService != null) {
2364             try {
2365                 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
2366             } catch (RemoteException e) {
2367                 throw e.rethrowFromSystemServer();
2368             }
2369         }
2370     }
2371 
2372     /**
2373      * Retrieve the current number of letters required in the password
2374      * for a particular admin or all admins that set restrictions on this user
2375      * and its participating profiles. Restrictions on profiles that have
2376      * a separate challenge are not taken into account.
2377      * This is the same value as set by
2378      * {@link #setPasswordMinimumLetters(ComponentName, int)}
2379      * and only applies when the password quality is
2380      * {@link #PASSWORD_QUALITY_COMPLEX}.
2381      *
2382      * <p>This method can be called on the {@link DevicePolicyManager} instance
2383      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2384      * restrictions on the parent profile.
2385      *
2386      * @param admin The name of the admin component to check, or {@code null} to
2387      *            aggregate all admins.
2388      * @return The minimum number of letters required in the password.
2389      */
getPasswordMinimumLetters(@ullable ComponentName admin)2390     public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
2391         return getPasswordMinimumLetters(admin, myUserId());
2392     }
2393 
2394     /** @hide per-user version */
getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)2395     public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
2396         if (mService != null) {
2397             try {
2398                 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
2399             } catch (RemoteException e) {
2400                 throw e.rethrowFromSystemServer();
2401             }
2402         }
2403         return 0;
2404     }
2405 
2406     /**
2407      * Called by an application that is administering the device to set the minimum number of
2408      * numerical digits required in the password. After setting this, the user will not be able to
2409      * enter a new password that is not at least as restrictive as what has been set. Note that the
2410      * current password will remain until the user has set a new one, so the change does not take
2411      * place immediately. To prompt the user for a new password, use
2412      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2413      * setting this value. This constraint is only imposed if the administrator has also requested
2414      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 1.
2415      * <p>
2416      * The calling device admin must have requested
2417      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2418      * not, a security exception will be thrown.
2419      * <p>
2420      * This method can be called on the {@link DevicePolicyManager} instance returned by
2421      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2422      * profile.
2423      *
2424      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2425      * @param length The new desired minimum number of numerical digits required in the password. A
2426      *            value of 0 means there is no restriction.
2427      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2428      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2429      */
setPasswordMinimumNumeric(@onNull ComponentName admin, int length)2430     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
2431         if (mService != null) {
2432             try {
2433                 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
2434             } catch (RemoteException e) {
2435                 throw e.rethrowFromSystemServer();
2436             }
2437         }
2438     }
2439 
2440     /**
2441      * Retrieve the current number of numerical digits required in the password
2442      * for a particular admin or all admins that set restrictions on this user
2443      * and its participating profiles. Restrictions on profiles that have
2444      * a separate challenge are not taken into account.
2445      * This is the same value as set by
2446      * {@link #setPasswordMinimumNumeric(ComponentName, int)}
2447      * and only applies when the password quality is
2448      * {@link #PASSWORD_QUALITY_COMPLEX}.
2449      *
2450      * <p>This method can be called on the {@link DevicePolicyManager} instance
2451      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2452      * restrictions on the parent profile.
2453      *
2454      * @param admin The name of the admin component to check, or {@code null} to
2455      *            aggregate all admins.
2456      * @return The minimum number of numerical digits required in the password.
2457      */
getPasswordMinimumNumeric(@ullable ComponentName admin)2458     public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
2459         return getPasswordMinimumNumeric(admin, myUserId());
2460     }
2461 
2462     /** @hide per-user version */
getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)2463     public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
2464         if (mService != null) {
2465             try {
2466                 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
2467             } catch (RemoteException e) {
2468                 throw e.rethrowFromSystemServer();
2469             }
2470         }
2471         return 0;
2472     }
2473 
2474     /**
2475      * Called by an application that is administering the device to set the minimum number of
2476      * symbols required in the password. After setting this, the user will not be able to enter a
2477      * new password that is not at least as restrictive as what has been set. Note that the current
2478      * password will remain until the user has set a new one, so the change does not take place
2479      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2480      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2481      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2482      * {@link #setPasswordQuality}. The default value is 1.
2483      * <p>
2484      * The calling device admin must have requested
2485      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2486      * not, a security exception will be thrown.
2487      * <p>
2488      * This method can be called on the {@link DevicePolicyManager} instance returned by
2489      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2490      * profile.
2491      *
2492      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2493      * @param length The new desired minimum number of symbols required in the password. A value of
2494      *            0 means there is no restriction.
2495      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2496      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2497      */
setPasswordMinimumSymbols(@onNull ComponentName admin, int length)2498     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
2499         if (mService != null) {
2500             try {
2501                 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
2502             } catch (RemoteException e) {
2503                 throw e.rethrowFromSystemServer();
2504             }
2505         }
2506     }
2507 
2508     /**
2509      * Retrieve the current number of symbols required in the password
2510      * for a particular admin or all admins that set restrictions on this user
2511      * and its participating profiles. Restrictions on profiles that have
2512      * a separate challenge are not taken into account. This is the same value as
2513      * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
2514      * and only applies when the password quality is
2515      * {@link #PASSWORD_QUALITY_COMPLEX}.
2516      *
2517      * <p>This method can be called on the {@link DevicePolicyManager} instance
2518      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2519      * restrictions on the parent profile.
2520      *
2521      * @param admin The name of the admin component to check, or {@code null} to
2522      *            aggregate all admins.
2523      * @return The minimum number of symbols required in the password.
2524      */
getPasswordMinimumSymbols(@ullable ComponentName admin)2525     public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
2526         return getPasswordMinimumSymbols(admin, myUserId());
2527     }
2528 
2529     /** @hide per-user version */
getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)2530     public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
2531         if (mService != null) {
2532             try {
2533                 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
2534             } catch (RemoteException e) {
2535                 throw e.rethrowFromSystemServer();
2536             }
2537         }
2538         return 0;
2539     }
2540 
2541     /**
2542      * Called by an application that is administering the device to set the minimum number of
2543      * non-letter characters (numerical digits or symbols) required in the password. After setting
2544      * this, the user will not be able to enter a new password that is not at least as restrictive
2545      * as what has been set. Note that the current password will remain until the user has set a new
2546      * one, so the change does not take place immediately. To prompt the user for a new password,
2547      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2548      * setting this value. This constraint is only imposed if the administrator has also requested
2549      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2550      * <p>
2551      * The calling device admin must have requested
2552      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2553      * not, a security exception will be thrown.
2554      * <p>
2555      * This method can be called on the {@link DevicePolicyManager} instance returned by
2556      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2557      * profile.
2558      *
2559      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2560      * @param length The new desired minimum number of letters required in the password. A value of
2561      *            0 means there is no restriction.
2562      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2563      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2564      */
setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)2565     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
2566         if (mService != null) {
2567             try {
2568                 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
2569             } catch (RemoteException e) {
2570                 throw e.rethrowFromSystemServer();
2571             }
2572         }
2573     }
2574 
2575     /**
2576      * Retrieve the current number of non-letter characters required in the password
2577      * for a particular admin or all admins that set restrictions on this user
2578      * and its participating profiles. Restrictions on profiles that have
2579      * a separate challenge are not taken into account.
2580      * This is the same value as set by
2581      * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
2582      * and only applies when the password quality is
2583      * {@link #PASSWORD_QUALITY_COMPLEX}.
2584      *
2585      * <p>This method can be called on the {@link DevicePolicyManager} instance
2586      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2587      * restrictions on the parent profile.
2588      *
2589      * @param admin The name of the admin component to check, or {@code null} to
2590      *            aggregate all admins.
2591      * @return The minimum number of letters required in the password.
2592      */
getPasswordMinimumNonLetter(@ullable ComponentName admin)2593     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
2594         return getPasswordMinimumNonLetter(admin, myUserId());
2595     }
2596 
2597     /** @hide per-user version */
getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)2598     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
2599         if (mService != null) {
2600             try {
2601                 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
2602             } catch (RemoteException e) {
2603                 throw e.rethrowFromSystemServer();
2604             }
2605         }
2606         return 0;
2607     }
2608 
2609     /**
2610      * Called by an application that is administering the device to set the length of the password
2611      * history. After setting this, the user will not be able to enter a new password that is the
2612      * same as any password in the history. Note that the current password will remain until the
2613      * user has set a new one, so the change does not take place immediately. To prompt the user for
2614      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2615      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2616      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2617      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX} {@link #PASSWORD_QUALITY_ALPHABETIC}, or
2618      * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
2619      * <p>
2620      * The calling device admin must have requested
2621      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2622      * not, a security exception will be thrown.
2623      * <p>
2624      * This method can be called on the {@link DevicePolicyManager} instance returned by
2625      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2626      * profile.
2627      *
2628      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2629      * @param length The new desired length of password history. A value of 0 means there is no
2630      *            restriction.
2631      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2632      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2633      */
setPasswordHistoryLength(@onNull ComponentName admin, int length)2634     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
2635         if (mService != null) {
2636             try {
2637                 mService.setPasswordHistoryLength(admin, length, mParentInstance);
2638             } catch (RemoteException e) {
2639                 throw e.rethrowFromSystemServer();
2640             }
2641         }
2642     }
2643 
2644     /**
2645      * Called by a device admin to set the password expiration timeout. Calling this method will
2646      * restart the countdown for password expiration for the given admin, as will changing the
2647      * device password (for all admins).
2648      * <p>
2649      * The provided timeout is the time delta in ms and will be added to the current time. For
2650      * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
2651      * 432000000 ms for timeout.
2652      * <p>
2653      * To disable password expiration, a value of 0 may be used for timeout.
2654      * <p>
2655      * The calling device admin must have requested
2656      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
2657      * not, a security exception will be thrown.
2658      * <p>
2659      * Note that setting the password will automatically reset the expiration time for all active
2660      * admins. Active admins do not need to explicitly call this method in that case.
2661      * <p>
2662      * This method can be called on the {@link DevicePolicyManager} instance returned by
2663      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2664      * profile.
2665      *
2666      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2667      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
2668      *            there is no restriction (unlimited).
2669      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2670      *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
2671      */
setPasswordExpirationTimeout(@onNull ComponentName admin, long timeout)2672     public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
2673         if (mService != null) {
2674             try {
2675                 mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
2676             } catch (RemoteException e) {
2677                 throw e.rethrowFromSystemServer();
2678             }
2679         }
2680     }
2681 
2682     /**
2683      * Get the password expiration timeout for the given admin. The expiration timeout is the
2684      * recurring expiration timeout provided in the call to
2685      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
2686      * aggregate of all participating policy administrators if {@code admin} is null. Admins that
2687      * have set restrictions on profiles that have a separate challenge are not taken into account.
2688      *
2689      * <p>This method can be called on the {@link DevicePolicyManager} instance
2690      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2691      * restrictions on the parent profile.
2692      *
2693      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2694      * @return The timeout for the given admin or the minimum of all timeouts
2695      */
getPasswordExpirationTimeout(@ullable ComponentName admin)2696     public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
2697         if (mService != null) {
2698             try {
2699                 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
2700             } catch (RemoteException e) {
2701                 throw e.rethrowFromSystemServer();
2702             }
2703         }
2704         return 0;
2705     }
2706 
2707     /**
2708      * Get the current password expiration time for a particular admin or all admins that set
2709      * restrictions on this user and its participating profiles. Restrictions on profiles that have
2710      * a separate challenge are not taken into account. If admin is {@code null}, then a composite
2711      * of all expiration times is returned - which will be the minimum of all of them.
2712      *
2713      * <p>This method can be called on the {@link DevicePolicyManager} instance
2714      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2715      * the password expiration for the parent profile.
2716      *
2717      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2718      * @return The password expiration time, in milliseconds since epoch.
2719      */
getPasswordExpiration(@ullable ComponentName admin)2720     public long getPasswordExpiration(@Nullable ComponentName admin) {
2721         if (mService != null) {
2722             try {
2723                 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
2724             } catch (RemoteException e) {
2725                 throw e.rethrowFromSystemServer();
2726             }
2727         }
2728         return 0;
2729     }
2730 
2731     /**
2732      * Retrieve the current password history length for a particular admin or all admins that
2733      * set restrictions on this user and its participating profiles. Restrictions on profiles that
2734      * have a separate challenge are not taken into account.
2735      *
2736      * <p>This method can be called on the {@link DevicePolicyManager} instance
2737      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2738      * restrictions on the parent profile.
2739      *
2740      * @param admin The name of the admin component to check, or {@code null} to aggregate
2741      * all admins.
2742      * @return The length of the password history
2743      */
getPasswordHistoryLength(@ullable ComponentName admin)2744     public int getPasswordHistoryLength(@Nullable ComponentName admin) {
2745         return getPasswordHistoryLength(admin, myUserId());
2746     }
2747 
2748     /** @hide per-user version */
getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)2749     public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
2750         if (mService != null) {
2751             try {
2752                 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
2753             } catch (RemoteException e) {
2754                 throw e.rethrowFromSystemServer();
2755             }
2756         }
2757         return 0;
2758     }
2759 
2760     /**
2761      * Return the maximum password length that the device supports for a
2762      * particular password quality.
2763      * @param quality The quality being interrogated.
2764      * @return Returns the maximum length that the user can enter.
2765      */
getPasswordMaximumLength(int quality)2766     public int getPasswordMaximumLength(int quality) {
2767         // Kind-of arbitrary.
2768         return 16;
2769     }
2770 
2771     /**
2772      * Determine whether the current password the user has set is sufficient to meet the policy
2773      * requirements (e.g. quality, minimum length) that have been requested by the admins of this
2774      * user and its participating profiles. Restrictions on profiles that have a separate challenge
2775      * are not taken into account. The user must be unlocked in order to perform the check.
2776      * <p>
2777      * The calling device admin must have requested
2778      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2779      * not, a security exception will be thrown.
2780      * <p>
2781      * This method can be called on the {@link DevicePolicyManager} instance returned by
2782      * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
2783      * the parent profile is sufficient.
2784      *
2785      * @return Returns true if the password meets the current requirements, else false.
2786      * @throws SecurityException if the calling application does not own an active administrator
2787      *             that uses {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2788      * @throws IllegalStateException if the user is not unlocked.
2789      */
isActivePasswordSufficient()2790     public boolean isActivePasswordSufficient() {
2791         if (mService != null) {
2792             try {
2793                 return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
2794             } catch (RemoteException e) {
2795                 throw e.rethrowFromSystemServer();
2796             }
2797         }
2798         return false;
2799     }
2800 
2801     /**
2802      * When called by a profile owner of a managed profile returns true if the profile uses unified
2803      * challenge with its parent user.
2804      *
2805      * <strong>Note</strong>: This method is not concerned with password quality and will return
2806      * false if the profile has empty password as a separate challenge.
2807      *
2808      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2809      * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
2810      * @see UserManager#DISALLOW_UNIFIED_PASSWORD
2811      */
isUsingUnifiedPassword(@onNull ComponentName admin)2812     public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
2813         throwIfParentInstance("isUsingUnifiedPassword");
2814         if (mService != null) {
2815             try {
2816                 return mService.isUsingUnifiedPassword(admin);
2817             } catch (RemoteException e) {
2818                 throw e.rethrowFromSystemServer();
2819             }
2820         }
2821         return true;
2822     }
2823 
2824     /**
2825      * Determine whether the current profile password the user has set is sufficient
2826      * to meet the policy requirements (e.g. quality, minimum length) that have been
2827      * requested by the admins of the parent user and its profiles.
2828      *
2829      * @param userHandle the userId of the profile to check the password for.
2830      * @return Returns true if the password would meet the current requirements, else false.
2831      * @throws SecurityException if {@code userHandle} is not a managed profile.
2832      * @hide
2833      */
isProfileActivePasswordSufficientForParent(int userHandle)2834     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
2835         if (mService != null) {
2836             try {
2837                 return mService.isProfileActivePasswordSufficientForParent(userHandle);
2838             } catch (RemoteException e) {
2839                 throw e.rethrowFromSystemServer();
2840             }
2841         }
2842         return false;
2843     }
2844 
2845     /**
2846      * Retrieve the number of times the user has failed at entering a password since that last
2847      * successful password entry.
2848      * <p>
2849      * This method can be called on the {@link DevicePolicyManager} instance returned by
2850      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
2851      * password attemts for the parent user.
2852      * <p>
2853      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2854      * to be able to call this method; if it has not, a security exception will be thrown.
2855      *
2856      * @return The number of times user has entered an incorrect password since the last correct
2857      *         password entry.
2858      * @throws SecurityException if the calling application does not own an active administrator
2859      *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2860      */
getCurrentFailedPasswordAttempts()2861     public int getCurrentFailedPasswordAttempts() {
2862         return getCurrentFailedPasswordAttempts(myUserId());
2863     }
2864 
2865     /**
2866      * Retrieve the number of times the given user has failed at entering a
2867      * password since that last successful password entry.
2868      *
2869      * <p>The calling device admin must have requested
2870      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
2871      * not and it is not the system uid, a security exception will be thrown.
2872      *
2873      * @hide
2874      */
getCurrentFailedPasswordAttempts(int userHandle)2875     public int getCurrentFailedPasswordAttempts(int userHandle) {
2876         if (mService != null) {
2877             try {
2878                 return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
2879             } catch (RemoteException e) {
2880                 throw e.rethrowFromSystemServer();
2881             }
2882         }
2883         return -1;
2884     }
2885 
2886     /**
2887      * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
2888      *
2889      * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
2890      * @hide
2891      */
getDoNotAskCredentialsOnBoot()2892     public boolean getDoNotAskCredentialsOnBoot() {
2893         if (mService != null) {
2894             try {
2895                 return mService.getDoNotAskCredentialsOnBoot();
2896             } catch (RemoteException e) {
2897                 throw e.rethrowFromSystemServer();
2898             }
2899         }
2900         return false;
2901     }
2902 
2903     /**
2904      * Setting this to a value greater than zero enables a built-in policy that will perform a
2905      * device or profile wipe after too many incorrect device-unlock passwords have been entered.
2906      * This built-in policy combines watching for failed passwords and wiping the device, and
2907      * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2908      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
2909      * <p>
2910      * To implement any other policy (e.g. wiping data for a particular application only, erasing or
2911      * revoking credentials, or reporting the failure to a server), you should implement
2912      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
2913      * use this API, because if the maximum count is reached, the device or profile will be wiped
2914      * immediately, and your callback will not be invoked.
2915      * <p>
2916      * This method can be called on the {@link DevicePolicyManager} instance returned by
2917      * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
2918      * profile.
2919      *
2920      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2921      * @param num The number of failed password attempts at which point the device or profile will
2922      *            be wiped.
2923      * @throws SecurityException if {@code admin} is not an active administrator or does not use
2924      *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2925      *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
2926      */
setMaximumFailedPasswordsForWipe(@onNull ComponentName admin, int num)2927     public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
2928         if (mService != null) {
2929             try {
2930                 mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
2931             } catch (RemoteException e) {
2932                 throw e.rethrowFromSystemServer();
2933             }
2934         }
2935     }
2936 
2937     /**
2938      * Retrieve the current maximum number of login attempts that are allowed before the device
2939      * or profile is wiped, for a particular admin or all admins that set restrictions on this user
2940      * and its participating profiles. Restrictions on profiles that have a separate challenge are
2941      * not taken into account.
2942      *
2943      * <p>This method can be called on the {@link DevicePolicyManager} instance
2944      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2945      * the value for the parent profile.
2946      *
2947      * @param admin The name of the admin component to check, or {@code null} to aggregate
2948      * all admins.
2949      */
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)2950     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
2951         return getMaximumFailedPasswordsForWipe(admin, myUserId());
2952     }
2953 
2954     /** @hide per-user version */
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)2955     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
2956         if (mService != null) {
2957             try {
2958                 return mService.getMaximumFailedPasswordsForWipe(
2959                         admin, userHandle, mParentInstance);
2960             } catch (RemoteException e) {
2961                 throw e.rethrowFromSystemServer();
2962             }
2963         }
2964         return 0;
2965     }
2966 
2967     /**
2968      * Returns the profile with the smallest maximum failed passwords for wipe,
2969      * for the given user. So for primary user, it might return the primary or
2970      * a managed profile. For a secondary user, it would be the same as the
2971      * user passed in.
2972      * @hide Used only by Keyguard
2973      */
getProfileWithMinimumFailedPasswordsForWipe(int userHandle)2974     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
2975         if (mService != null) {
2976             try {
2977                 return mService.getProfileWithMinimumFailedPasswordsForWipe(
2978                         userHandle, mParentInstance);
2979             } catch (RemoteException e) {
2980                 throw e.rethrowFromSystemServer();
2981             }
2982         }
2983         return UserHandle.USER_NULL;
2984     }
2985 
2986     /**
2987      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
2988      * to change the password again until the user has entered it.
2989      */
2990     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
2991 
2992     /**
2993      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
2994      * credentials on device boot.
2995      * If the flag is set, the device can be booted without asking for user password.
2996      * The absence of this flag does not change the current boot requirements. This flag
2997      * can be set by the device owner only. If the app is not the device owner, the flag
2998      * is ignored. Once the flag is set, it cannot be reverted back without resetting the
2999      * device to factory defaults.
3000      */
3001     public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
3002 
3003     /**
3004      * Force a new password for device unlock (the password needed to access the entire device) or
3005      * the work profile challenge on the current user. This takes effect immediately.
3006      * <p>
3007      * <em>For device owner and profile owners targeting SDK level
3008      * {@link android.os.Build.VERSION_CODES#O} or above, this API is no longer available and will
3009      * throw {@link SecurityException}. Please use the new API {@link #resetPasswordWithToken}
3010      * instead. </em>
3011      * <p>
3012      * <em>Note: This API has been limited as of {@link android.os.Build.VERSION_CODES#N} for
3013      * device admins that are not device owner and not profile owner.
3014      * The password can now only be changed if there is currently no password set.  Device owner
3015      * and profile owner can still do this when user is unlocked and does not have a managed
3016      * profile.</em>
3017      * <p>
3018      * The given password must be sufficient for the current password quality and length constraints
3019      * as returned by {@link #getPasswordQuality(ComponentName)} and
3020      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3021      * it will be rejected and false returned. Note that the password may be a stronger quality
3022      * (containing alphanumeric characters when the requested quality is only numeric), in which
3023      * case the currently active quality will be increased to match.
3024      * <p>
3025      * Calling with a null or empty password will clear any existing PIN, pattern or password if the
3026      * current password constraints allow it. <em>Note: This will not work in
3027      * {@link android.os.Build.VERSION_CODES#N} and later for managed profiles, or for device admins
3028      * that are not device owner or profile owner.  Once set, the password cannot be changed to null
3029      * or empty except by these admins.</em>
3030      * <p>
3031      * The calling device admin must have requested
3032      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
3033      * not, a security exception will be thrown.
3034      *
3035      * @param password The new password for the user. Null or empty clears the password.
3036      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3037      *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3038      * @return Returns true if the password was applied, or false if it is not acceptable for the
3039      *         current constraints or if the user has not been decrypted yet.
3040      * @throws SecurityException if the calling application does not own an active administrator
3041      *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
3042      * @throws IllegalStateException if the calling user is locked or has a managed profile.
3043      */
resetPassword(String password, int flags)3044     public boolean resetPassword(String password, int flags) {
3045         throwIfParentInstance("resetPassword");
3046         if (mService != null) {
3047             try {
3048                 return mService.resetPassword(password, flags);
3049             } catch (RemoteException e) {
3050                 throw e.rethrowFromSystemServer();
3051             }
3052         }
3053         return false;
3054     }
3055 
3056     /**
3057      * Called by a profile or device owner to provision a token which can later be used to reset the
3058      * device lockscreen password (if called by device owner), or managed profile challenge (if
3059      * called by profile owner), via {@link #resetPasswordWithToken}.
3060      * <p>
3061      * If the user currently has a lockscreen password, the provisioned token will not be
3062      * immediately usable; it only becomes active after the user performs a confirm credential
3063      * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
3064      * If the user has no lockscreen password, the token is activated immediately. In all cases,
3065      * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
3066      * For security reasons, un-activated tokens are only stored in memory and will be lost once
3067      * the device reboots. In this case a new token needs to be provisioned again.
3068      * <p>
3069      * Once provisioned and activated, the token will remain effective even if the user changes
3070      * or clears the lockscreen password.
3071      * <p>
3072      * <em>This token is highly sensitive and should be treated at the same level as user
3073      * credentials. In particular, NEVER store this token on device in plaintext. Do not store
3074      * the plaintext token in device-encrypted storage if it will be needed to reset password on
3075      * file-based encryption devices before user unlocks. Consider carefully how any password token
3076      * will be stored on your server and who will need access to them. Tokens may be the subject of
3077      * legal access requests.
3078      * </em>
3079      *
3080      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3081      * @param token a secure token a least 32-byte long, which must be generated by a
3082      *        cryptographically strong random number generator.
3083      * @return true if the operation is successful, false otherwise.
3084      * @throws SecurityException if admin is not a device or profile owner.
3085      * @throws IllegalArgumentException if the supplied token is invalid.
3086      */
setResetPasswordToken(ComponentName admin, byte[] token)3087     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
3088         throwIfParentInstance("setResetPasswordToken");
3089         if (mService != null) {
3090             try {
3091                 return mService.setResetPasswordToken(admin, token);
3092             } catch (RemoteException e) {
3093                 throw e.rethrowFromSystemServer();
3094             }
3095         }
3096         return false;
3097     }
3098 
3099     /**
3100      * Called by a profile or device owner to revoke the current password reset token.
3101      *
3102      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3103      * @return true if the operation is successful, false otherwise.
3104      * @throws SecurityException if admin is not a device or profile owner.
3105      */
clearResetPasswordToken(ComponentName admin)3106     public boolean clearResetPasswordToken(ComponentName admin) {
3107         throwIfParentInstance("clearResetPasswordToken");
3108         if (mService != null) {
3109             try {
3110                 return mService.clearResetPasswordToken(admin);
3111             } catch (RemoteException e) {
3112                 throw e.rethrowFromSystemServer();
3113             }
3114         }
3115         return false;
3116     }
3117 
3118     /**
3119      * Called by a profile or device owner to check if the current reset password token is active.
3120      *
3121      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3122      * @return true if the token is active, false otherwise.
3123      * @throws SecurityException if admin is not a device or profile owner.
3124      * @throws IllegalStateException if no token has been set.
3125      */
isResetPasswordTokenActive(ComponentName admin)3126     public boolean isResetPasswordTokenActive(ComponentName admin) {
3127         throwIfParentInstance("isResetPasswordTokenActive");
3128         if (mService != null) {
3129             try {
3130                 return mService.isResetPasswordTokenActive(admin);
3131             } catch (RemoteException e) {
3132                 throw e.rethrowFromSystemServer();
3133             }
3134         }
3135         return false;
3136     }
3137 
3138     /**
3139      * Called by device or profile owner to force set a new device unlock password or a managed
3140      * profile challenge on current user. This takes effect immediately.
3141      * <p>
3142      * Unlike {@link #resetPassword}, this API can change the password even before the user or
3143      * device is unlocked or decrypted. The supplied token must have been previously provisioned via
3144      * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
3145      * <p>
3146      * The given password must be sufficient for the current password quality and length constraints
3147      * as returned by {@link #getPasswordQuality(ComponentName)} and
3148      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3149      * it will be rejected and false returned. Note that the password may be a stronger quality, for
3150      * example, a password containing alphanumeric characters when the requested quality is only
3151      * numeric.
3152      * <p>
3153      * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
3154      * password if the current password constraints allow it.
3155      *
3156      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3157      * @param password The new password for the user. {@code null} or empty clears the password.
3158      * @param token the password reset token previously provisioned by
3159      *        {@link #setResetPasswordToken}.
3160      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3161      *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3162      * @return Returns true if the password was applied, or false if it is not acceptable for the
3163      *         current constraints.
3164      * @throws SecurityException if admin is not a device or profile owner.
3165      * @throws IllegalStateException if the provided token is not valid.
3166      */
resetPasswordWithToken(@onNull ComponentName admin, String password, byte[] token, int flags)3167     public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
3168             byte[] token, int flags) {
3169         throwIfParentInstance("resetPassword");
3170         if (mService != null) {
3171             try {
3172                 return mService.resetPasswordWithToken(admin, password, token, flags);
3173             } catch (RemoteException e) {
3174                 throw e.rethrowFromSystemServer();
3175             }
3176         }
3177         return false;
3178     }
3179 
3180     /**
3181      * Called by an application that is administering the device to set the maximum time for user
3182      * activity until the device will lock. This limits the length that the user can set. It takes
3183      * effect immediately.
3184      * <p>
3185      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3186      * to be able to call this method; if it has not, a security exception will be thrown.
3187      * <p>
3188      * This method can be called on the {@link DevicePolicyManager} instance returned by
3189      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3190      * profile.
3191      *
3192      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3193      * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
3194      *            is no restriction.
3195      * @throws SecurityException if {@code admin} is not an active administrator or it does not use
3196      *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3197      */
setMaximumTimeToLock(@onNull ComponentName admin, long timeMs)3198     public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
3199         if (mService != null) {
3200             try {
3201                 mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
3202             } catch (RemoteException e) {
3203                 throw e.rethrowFromSystemServer();
3204             }
3205         }
3206     }
3207 
3208     /**
3209      * Retrieve the current maximum time to unlock for a particular admin or all admins that set
3210      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3211      * a separate challenge are not taken into account.
3212      *
3213      * <p>This method can be called on the {@link DevicePolicyManager} instance
3214      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3215      * restrictions on the parent profile.
3216      *
3217      * @param admin The name of the admin component to check, or {@code null} to aggregate
3218      * all admins.
3219      * @return time in milliseconds for the given admin or the minimum value (strictest) of
3220      * all admins if admin is null. Returns 0 if there are no restrictions.
3221      */
getMaximumTimeToLock(@ullable ComponentName admin)3222     public long getMaximumTimeToLock(@Nullable ComponentName admin) {
3223         return getMaximumTimeToLock(admin, myUserId());
3224     }
3225 
3226     /** @hide per-user version */
getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)3227     public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
3228         if (mService != null) {
3229             try {
3230                 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
3231             } catch (RemoteException e) {
3232                 throw e.rethrowFromSystemServer();
3233             }
3234         }
3235         return 0;
3236     }
3237 
3238     /**
3239      * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
3240      * strong auth (e.g. fingerprint, trust agents) times out, i.e. the user has to use a strong
3241      * authentication method like password, pin or pattern.
3242      *
3243      * <p>This timeout is used internally to reset the timer to require strong auth again after
3244      * specified timeout each time it has been successfully used.
3245      *
3246      * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
3247      *
3248      * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3249      *
3250      * <p>The calling device admin must be a device or profile owner. If it is not,
3251      * a {@link SecurityException} will be thrown.
3252      *
3253      * <p>The calling device admin can verify the value it has set by calling
3254      * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
3255      *
3256      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
3257      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3258      * profile.
3259      *
3260      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3261      * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
3262      *         with strong authentication method. A value of 0 means the admin is not participating
3263      *         in controlling the timeout.
3264      *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
3265      *         72 hours, respectively. Though discouraged, the admin may choose to require strong
3266      *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
3267      *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3268      *
3269      * @throws SecurityException if {@code admin} is not a device or profile owner.
3270      */
setRequiredStrongAuthTimeout(@onNull ComponentName admin, long timeoutMs)3271     public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
3272             long timeoutMs) {
3273         if (mService != null) {
3274             try {
3275                 mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
3276             } catch (RemoteException e) {
3277                 throw e.rethrowFromSystemServer();
3278             }
3279         }
3280     }
3281 
3282     /**
3283      * Determine for how long the user will be able to use secondary, non strong auth for
3284      * authentication, since last strong method authentication (password, pin or pattern) was used.
3285      * After the returned timeout the user is required to use strong authentication method.
3286      *
3287      * <p>This method can be called on the {@link DevicePolicyManager} instance
3288      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3289      * restrictions on the parent profile.
3290      *
3291      * @param admin The name of the admin component to check, or {@code null} to aggregate
3292      *         accross all participating admins.
3293      * @return The timeout in milliseconds or 0 if not configured for the provided admin.
3294      */
getRequiredStrongAuthTimeout(@ullable ComponentName admin)3295     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
3296         return getRequiredStrongAuthTimeout(admin, myUserId());
3297     }
3298 
3299     /** @hide per-user version */
getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)3300     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
3301         if (mService != null) {
3302             try {
3303                 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
3304             } catch (RemoteException e) {
3305                 throw e.rethrowFromSystemServer();
3306             }
3307         }
3308         return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
3309     }
3310 
3311     /**
3312      * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
3313      * keyring. The user's credential will need to be entered again in order to derive the
3314      * credential encryption key that will be stored back in the keyring for future use.
3315      * <p>
3316      * This flag can only be used by a profile owner when locking a managed profile when
3317      * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3318      * <p>
3319      * In order to secure user data, the user will be stopped and restarted so apps should wait
3320      * until they are next run to perform further actions.
3321      */
3322     public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
3323 
3324     /** @hide */
3325     @Retention(RetentionPolicy.SOURCE)
3326     @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
3327             FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
3328     })
3329     public @interface LockNowFlag {}
3330 
3331     /**
3332      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3333      * this call.
3334      * <p>
3335      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3336      * to be able to call this method; if it has not, a security exception will be thrown.
3337      * <p>
3338      * This method can be called on the {@link DevicePolicyManager} instance returned by
3339      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3340      * <p>
3341      * Equivalent to calling {@link #lockNow(int)} with no flags.
3342      *
3343      * @throws SecurityException if the calling application does not own an active administrator
3344      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3345      */
lockNow()3346     public void lockNow() {
3347         lockNow(0);
3348     }
3349 
3350     /**
3351      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3352      * this call.
3353      * <p>
3354      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3355      * to be able to call this method; if it has not, a security exception will be thrown.
3356      * <p>
3357      * This method can be called on the {@link DevicePolicyManager} instance returned by
3358      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3359      *
3360      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
3361      * @throws SecurityException if the calling application does not own an active administrator
3362      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
3363      *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
3364      *             that is not a profile
3365      *             owner of a managed profile.
3366      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
3367      *             passed when locking the parent profile.
3368      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
3369      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
3370      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3371      */
lockNow(@ockNowFlag int flags)3372     public void lockNow(@LockNowFlag int flags) {
3373         if (mService != null) {
3374             try {
3375                 mService.lockNow(flags, mParentInstance);
3376             } catch (RemoteException e) {
3377                 throw e.rethrowFromSystemServer();
3378             }
3379         }
3380     }
3381 
3382     /**
3383      * Flag for {@link #wipeData(int)}: also erase the device's external
3384      * storage (such as SD cards).
3385      */
3386     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
3387 
3388     /**
3389      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
3390      * data.
3391      *
3392      * <p>This flag may only be set by device owner admins; if it is set by
3393      * other admins a {@link SecurityException} will be thrown.
3394      */
3395     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
3396 
3397     /**
3398      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
3399      */
3400     public static final int WIPE_EUICC = 0x0004;
3401 
3402 
3403     /**
3404      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
3405      * other users will remain unaffected. Calling from the primary user will cause the device to
3406      * reboot, erasing all device data - including all the secondary users and their data - while
3407      * booting up.
3408      * <p>
3409      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
3410      * be able to call this method; if it has not, a security exception will be thrown.
3411      *
3412      * @param flags Bit mask of additional options: currently supported flags are
3413      *            {@link #WIPE_EXTERNAL_STORAGE} and {@link #WIPE_RESET_PROTECTION_DATA}.
3414      * @throws SecurityException if the calling application does not own an active administrator
3415      *             that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
3416      */
wipeData(int flags)3417     public void wipeData(int flags) {
3418         throwIfParentInstance("wipeData");
3419         final String wipeReasonForUser = mContext.getString(
3420                 R.string.work_profile_deleted_description_dpm_wipe);
3421         wipeDataInternal(flags, wipeReasonForUser);
3422     }
3423 
3424     /**
3425      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
3426      * other users will remain unaffected, the provided reason for wiping data can be shown to
3427      * user. Calling from the primary user will cause the device to reboot, erasing all device data
3428      * - including all the secondary users and their data - while booting up. In this case, we don't
3429      * show the reason to the user since the device would be factory reset.
3430      * <p>
3431      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
3432      * be able to call this method; if it has not, a security exception will be thrown.
3433      *
3434      * @param flags Bit mask of additional options: currently supported flags are
3435      *            {@link #WIPE_EXTERNAL_STORAGE} and {@link #WIPE_RESET_PROTECTION_DATA}.
3436      * @param reason a string that contains the reason for wiping data, which can be
3437      *                          presented to the user.
3438      * @throws SecurityException if the calling application does not own an active administrator
3439      *             that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
3440      * @throws IllegalArgumentException if the input reason string is null or empty.
3441      */
wipeData(int flags, @NonNull CharSequence reason)3442     public void wipeData(int flags, @NonNull CharSequence reason) {
3443         throwIfParentInstance("wipeData");
3444         Preconditions.checkNotNull(reason, "CharSequence is null");
3445         wipeDataInternal(flags, reason.toString());
3446     }
3447 
3448     /**
3449      * Internal function for both {@link #wipeData(int)} and
3450      * {@link #wipeData(int, CharSequence)} to call.
3451      *
3452      * @see #wipeData(int)
3453      * @see #wipeData(int, CharSequence)
3454      * @hide
3455      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser)3456     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
3457         if (mService != null) {
3458             try {
3459                 mService.wipeDataWithReason(flags, wipeReasonForUser);
3460             } catch (RemoteException e) {
3461                 throw e.rethrowFromSystemServer();
3462             }
3463         }
3464     }
3465 
3466     /**
3467      * Called by an application that is administering the device to set the
3468      * global proxy and exclusion list.
3469      * <p>
3470      * The calling device admin must have requested
3471      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
3472      * this method; if it has not, a security exception will be thrown.
3473      * Only the first device admin can set the proxy. If a second admin attempts
3474      * to set the proxy, the {@link ComponentName} of the admin originally setting the
3475      * proxy will be returned. If successful in setting the proxy, {@code null} will
3476      * be returned.
3477      * The method can be called repeatedly by the device admin alrady setting the
3478      * proxy to update the proxy and exclusion list.
3479      *
3480      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3481      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
3482      *            Pass Proxy.NO_PROXY to reset the proxy.
3483      * @param exclusionList a list of domains to be excluded from the global proxy.
3484      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
3485      *            of the device admin that sets the proxy.
3486      * @hide
3487      */
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )3488     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
3489             List<String> exclusionList ) {
3490         throwIfParentInstance("setGlobalProxy");
3491         if (proxySpec == null) {
3492             throw new NullPointerException();
3493         }
3494         if (mService != null) {
3495             try {
3496                 String hostSpec;
3497                 String exclSpec;
3498                 if (proxySpec.equals(Proxy.NO_PROXY)) {
3499                     hostSpec = null;
3500                     exclSpec = null;
3501                 } else {
3502                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
3503                         throw new IllegalArgumentException();
3504                     }
3505                     InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
3506                     String hostName = sa.getHostName();
3507                     int port = sa.getPort();
3508                     StringBuilder hostBuilder = new StringBuilder();
3509                     hostSpec = hostBuilder.append(hostName)
3510                         .append(":").append(Integer.toString(port)).toString();
3511                     if (exclusionList == null) {
3512                         exclSpec = "";
3513                     } else {
3514                         StringBuilder listBuilder = new StringBuilder();
3515                         boolean firstDomain = true;
3516                         for (String exclDomain : exclusionList) {
3517                             if (!firstDomain) {
3518                                 listBuilder = listBuilder.append(",");
3519                             } else {
3520                                 firstDomain = false;
3521                             }
3522                             listBuilder = listBuilder.append(exclDomain.trim());
3523                         }
3524                         exclSpec = listBuilder.toString();
3525                     }
3526                     if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
3527                             != android.net.Proxy.PROXY_VALID)
3528                         throw new IllegalArgumentException();
3529                 }
3530                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
3531             } catch (RemoteException e) {
3532                 throw e.rethrowFromSystemServer();
3533             }
3534         }
3535         return null;
3536     }
3537 
3538     /**
3539      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
3540      * HTTP proxies - they are generally network dependent. However if you're doing something
3541      * unusual like general internal filtering this may be useful. On a private network where the
3542      * proxy is not accessible, you may break HTTP using this.
3543      * <p>
3544      * This method requires the caller to be the device owner.
3545      * <p>
3546      * This proxy is only a recommendation and it is possible that some apps will ignore it.
3547      *
3548      * @see ProxyInfo
3549      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3550      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
3551      *            {@code null} value will clear the global HTTP proxy.
3552      * @throws SecurityException if {@code admin} is not the device owner.
3553      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)3554     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
3555             proxyInfo) {
3556         throwIfParentInstance("setRecommendedGlobalProxy");
3557         if (mService != null) {
3558             try {
3559                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
3560             } catch (RemoteException e) {
3561                 throw e.rethrowFromSystemServer();
3562             }
3563         }
3564     }
3565 
3566     /**
3567      * Returns the component name setting the global proxy.
3568      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
3569      *         if no admin has set the proxy.
3570      * @hide
3571      */
getGlobalProxyAdmin()3572     public @Nullable ComponentName getGlobalProxyAdmin() {
3573         if (mService != null) {
3574             try {
3575                 return mService.getGlobalProxyAdmin(myUserId());
3576             } catch (RemoteException e) {
3577                 throw e.rethrowFromSystemServer();
3578             }
3579         }
3580         return null;
3581     }
3582 
3583     /**
3584      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3585      * indicating that encryption is not supported.
3586      */
3587     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
3588 
3589     /**
3590      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3591      * indicating that encryption is supported, but is not currently active.
3592      */
3593     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
3594 
3595     /**
3596      * Result code for {@link #getStorageEncryptionStatus}:
3597      * indicating that encryption is not currently active, but is currently
3598      * being activated.  This is only reported by devices that support
3599      * encryption of data and only when the storage is currently
3600      * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
3601      * to become encrypted will never return this value.
3602      */
3603     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
3604 
3605     /**
3606      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3607      * indicating that encryption is active.
3608      * <p>
3609      * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3610      */
3611     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
3612 
3613     /**
3614      * Result code for {@link #getStorageEncryptionStatus}:
3615      * indicating that encryption is active, but an encryption key has not
3616      * been set by the user.
3617      */
3618     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
3619 
3620     /**
3621      * Result code for {@link #getStorageEncryptionStatus}:
3622      * indicating that encryption is active and the encryption key is tied to the user or profile.
3623      * <p>
3624      * This value is only returned to apps targeting API level 24 and above. For apps targeting
3625      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
3626      * encryption key is specific to the user or profile.
3627      */
3628     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
3629 
3630     /**
3631      * Activity action: begin the process of encrypting data on the device.  This activity should
3632      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
3633      * After resuming from this activity, use {@link #getStorageEncryption}
3634      * to check encryption status.  However, on some devices this activity may never return, as
3635      * it may trigger a reboot and in some cases a complete data wipe of the device.
3636      */
3637     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3638     public static final String ACTION_START_ENCRYPTION
3639             = "android.app.action.START_ENCRYPTION";
3640 
3641     /**
3642      * Broadcast action: notify managed provisioning that new managed user is created.
3643      *
3644      * @hide
3645      */
3646     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3647     public static final String ACTION_MANAGED_USER_CREATED =
3648             "android.app.action.MANAGED_USER_CREATED";
3649 
3650     /**
3651      * Widgets are enabled in keyguard
3652      */
3653     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
3654 
3655     /**
3656      * Disable all keyguard widgets. Has no effect starting from
3657      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
3658      * on Android versions lower than 5.0.
3659      */
3660     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
3661 
3662     /**
3663      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
3664      */
3665     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
3666 
3667     /**
3668      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3669      */
3670     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
3671 
3672     /**
3673      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3674      */
3675     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
3676 
3677     /**
3678      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
3679      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
3680      * whitelist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
3681      * used in conjuction to set trust-agent-specific configurations.
3682      */
3683     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
3684 
3685     /**
3686      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
3687      */
3688     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
3689 
3690     /**
3691      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
3692      */
3693     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
3694 
3695     /**
3696      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
3697      */
3698     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
3699 
3700     /**
3701      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
3702      */
3703     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
3704 
3705     /**
3706      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
3707      */
3708     public static final int KEYGUARD_DISABLE_BIOMETRICS =
3709             DevicePolicyManager.KEYGUARD_DISABLE_FACE
3710             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
3711             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
3712 
3713 
3714     /**
3715      * Disable all current and future keyguard customizations.
3716      */
3717     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
3718 
3719     /**
3720      * Keyguard features that when set on a managed profile that doesn't have its own challenge will
3721      * affect the profile's parent user. These can also be set on the managed profile's parent
3722      * {@link DevicePolicyManager} instance.
3723      *
3724      * @hide
3725      */
3726     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
3727             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
3728             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
3729 
3730     /**
3731      * Called by an application that is administering the device to request that the storage system
3732      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
3733      * <p>
3734      * When multiple device administrators attempt to control device encryption, the most secure,
3735      * supported setting will always be used. If any device administrator requests device
3736      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
3737      * device encryption while another device administrator has enabled it, the call to disable will
3738      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
3739      * <p>
3740      * This policy controls encryption of the secure (application data) storage area. Data written
3741      * to other storage areas may or may not be encrypted, and this policy does not require or
3742      * control the encryption of any other storage areas. There is one exception: If
3743      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
3744      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
3745      * written to disk within the encrypted storage area.
3746      * <p>
3747      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
3748      * to create a device PIN or Password. In this case, the storage is encrypted, but the
3749      * encryption key may not be fully secured. For maximum security, the administrator should also
3750      * require (and check for) a pattern, PIN, or password.
3751      *
3752      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3753      * @param encrypt true to request encryption, false to release any previous request
3754      * @return the new total request status (for all active admins), or {@link
3755      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
3756      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
3757      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
3758      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
3759      *         state.
3760      *
3761      * @throws SecurityException if {@code admin} is not an active administrator or does not use
3762      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
3763      */
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)3764     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
3765         throwIfParentInstance("setStorageEncryption");
3766         if (mService != null) {
3767             try {
3768                 return mService.setStorageEncryption(admin, encrypt);
3769             } catch (RemoteException e) {
3770                 throw e.rethrowFromSystemServer();
3771             }
3772         }
3773         return ENCRYPTION_STATUS_UNSUPPORTED;
3774     }
3775 
3776     /**
3777      * Called by an application that is administering the device to
3778      * determine the requested setting for secure storage.
3779      *
3780      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
3781      * this will return the requested encryption setting as an aggregate of all active
3782      * administrators.
3783      * @return true if the admin(s) are requesting encryption, false if not.
3784      */
getStorageEncryption(@ullable ComponentName admin)3785     public boolean getStorageEncryption(@Nullable ComponentName admin) {
3786         throwIfParentInstance("getStorageEncryption");
3787         if (mService != null) {
3788             try {
3789                 return mService.getStorageEncryption(admin, myUserId());
3790             } catch (RemoteException e) {
3791                 throw e.rethrowFromSystemServer();
3792             }
3793         }
3794         return false;
3795     }
3796 
3797     /**
3798      * Called by an application that is administering the device to
3799      * determine the current encryption status of the device.
3800      * <p>
3801      * Depending on the returned status code, the caller may proceed in different
3802      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
3803      * storage system does not support encryption.  If the
3804      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
3805      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
3806      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
3807      * storage system has enabled encryption but no password is set so further action
3808      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
3809      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
3810      * no further action is required.
3811      *
3812      * @return current status of encryption. The value will be one of
3813      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
3814      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
3815      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3816      */
getStorageEncryptionStatus()3817     public int getStorageEncryptionStatus() {
3818         throwIfParentInstance("getStorageEncryptionStatus");
3819         return getStorageEncryptionStatus(myUserId());
3820     }
3821 
3822     /** @hide per-user version */
getStorageEncryptionStatus(int userHandle)3823     public int getStorageEncryptionStatus(int userHandle) {
3824         if (mService != null) {
3825             try {
3826                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
3827             } catch (RemoteException e) {
3828                 throw e.rethrowFromSystemServer();
3829             }
3830         }
3831         return ENCRYPTION_STATUS_UNSUPPORTED;
3832     }
3833 
3834     /**
3835      * Mark a CA certificate as approved by the device user. This means that they have been notified
3836      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
3837      * keep the certificate on the device.
3838      *
3839      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
3840      * this certificate.
3841      *
3842      * @hide
3843      */
approveCaCert(String alias, int userHandle, boolean approval)3844     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
3845         if (mService != null) {
3846             try {
3847                 return mService.approveCaCert(alias, userHandle, approval);
3848             } catch (RemoteException e) {
3849                 throw e.rethrowFromSystemServer();
3850             }
3851         }
3852         return false;
3853     }
3854 
3855     /**
3856      * Check whether a CA certificate has been approved by the device user.
3857      *
3858      * @hide
3859      */
isCaCertApproved(String alias, int userHandle)3860     public boolean isCaCertApproved(String alias, int userHandle) {
3861         if (mService != null) {
3862             try {
3863                 return mService.isCaCertApproved(alias, userHandle);
3864             } catch (RemoteException e) {
3865                 throw e.rethrowFromSystemServer();
3866             }
3867         }
3868         return false;
3869     }
3870 
3871     /**
3872      * Installs the given certificate as a user CA.
3873      *
3874      * The caller must be a profile or device owner on that user, or a delegate package given the
3875      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3876      * security exception will be thrown.
3877      *
3878      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3879      *              {@code null} if calling from a delegated certificate installer.
3880      * @param certBuffer encoded form of the certificate to install.
3881      *
3882      * @return false if the certBuffer cannot be parsed or installation is
3883      *         interrupted, true otherwise.
3884      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3885      *         owner.
3886      * @see #setDelegatedScopes
3887      * @see #DELEGATION_CERT_INSTALL
3888      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)3889     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3890         throwIfParentInstance("installCaCert");
3891         if (mService != null) {
3892             try {
3893                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
3894             } catch (RemoteException e) {
3895                 throw e.rethrowFromSystemServer();
3896             }
3897         }
3898         return false;
3899     }
3900 
3901     /**
3902      * Uninstalls the given certificate from trusted user CAs, if present.
3903      *
3904      * The caller must be a profile or device owner on that user, or a delegate package given the
3905      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3906      * security exception will be thrown.
3907      *
3908      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3909      *              {@code null} if calling from a delegated certificate installer.
3910      * @param certBuffer encoded form of the certificate to remove.
3911      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3912      *         owner.
3913      * @see #setDelegatedScopes
3914      * @see #DELEGATION_CERT_INSTALL
3915      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)3916     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3917         throwIfParentInstance("uninstallCaCert");
3918         if (mService != null) {
3919             try {
3920                 final String alias = getCaCertAlias(certBuffer);
3921                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
3922             } catch (CertificateException e) {
3923                 Log.w(TAG, "Unable to parse certificate", e);
3924             } catch (RemoteException e) {
3925                 throw e.rethrowFromSystemServer();
3926             }
3927         }
3928     }
3929 
3930     /**
3931      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
3932      * If a user has installed any certificates by other means than device policy these will be
3933      * included too.
3934      *
3935      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3936      *              {@code null} if calling from a delegated certificate installer.
3937      * @return a List of byte[] arrays, each encoding one user CA certificate.
3938      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3939      *         owner.
3940      */
getInstalledCaCerts(@ullable ComponentName admin)3941     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
3942         final List<byte[]> certs = new ArrayList<byte[]>();
3943         throwIfParentInstance("getInstalledCaCerts");
3944         if (mService != null) {
3945             try {
3946                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
3947                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
3948                 for (String alias : certStore.userAliases()) {
3949                     try {
3950                         certs.add(certStore.getCertificate(alias).getEncoded());
3951                     } catch (CertificateException ce) {
3952                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
3953                     }
3954                 }
3955             } catch (RemoteException re) {
3956                 throw re.rethrowFromSystemServer();
3957             }
3958         }
3959         return certs;
3960     }
3961 
3962     /**
3963      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
3964      * means other than device policy will also be removed, except for system CA certificates.
3965      *
3966      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3967      *              {@code null} if calling from a delegated certificate installer.
3968      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3969      *         owner.
3970      */
uninstallAllUserCaCerts(@ullable ComponentName admin)3971     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
3972         throwIfParentInstance("uninstallAllUserCaCerts");
3973         if (mService != null) {
3974             try {
3975                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
3976                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
3977             } catch (RemoteException re) {
3978                 throw re.rethrowFromSystemServer();
3979             }
3980         }
3981     }
3982 
3983     /**
3984      * Returns whether this certificate is installed as a trusted CA.
3985      *
3986      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3987      *              {@code null} if calling from a delegated certificate installer.
3988      * @param certBuffer encoded form of the certificate to look up.
3989      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3990      *         owner.
3991      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)3992     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
3993         throwIfParentInstance("hasCaCertInstalled");
3994         if (mService != null) {
3995             try {
3996                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
3997                 return getCaCertAlias(certBuffer) != null;
3998             } catch (RemoteException re) {
3999                 throw re.rethrowFromSystemServer();
4000             } catch (CertificateException ce) {
4001                 Log.w(TAG, "Could not parse certificate", ce);
4002             }
4003         }
4004         return false;
4005     }
4006 
4007     /**
4008      * Called by a device or profile owner, or delegated certificate installer, to install a
4009      * certificate and corresponding private key. All apps within the profile will be able to access
4010      * the certificate and use the private key, given direct user approval.
4011      *
4012      * <p>Access to the installed credentials will not be granted to the caller of this API without
4013      * direct user approval. This is for security - should a certificate installer become
4014      * compromised, certificates it had already installed will be protected.
4015      *
4016      * <p>If the installer must have access to the credentials, call
4017      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
4018      *
4019      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4020      *            {@code null} if calling from a delegated certificate installer.
4021      * @param privKey The private key to install.
4022      * @param cert The certificate to install.
4023      * @param alias The private key alias under which to install the certificate. If a certificate
4024      * with that alias already exists, it will be overwritten.
4025      * @return {@code true} if the keys were installed, {@code false} otherwise.
4026      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4027      *         owner.
4028      * @see #setDelegatedScopes
4029      * @see #DELEGATION_CERT_INSTALL
4030      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)4031     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4032             @NonNull Certificate cert, @NonNull String alias) {
4033         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
4034     }
4035 
4036     /**
4037      * Called by a device or profile owner, or delegated certificate installer, to install a
4038      * certificate chain and corresponding private key for the leaf certificate. All apps within the
4039      * profile will be able to access the certificate chain and use the private key, given direct
4040      * user approval.
4041      *
4042      * <p>The caller of this API may grant itself access to the certificate and private key
4043      * immediately, without user approval. It is a best practice not to request this unless strictly
4044      * necessary since it opens up additional security vulnerabilities.
4045      *
4046      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4047      *        {@code null} if calling from a delegated certificate installer.
4048      * @param privKey The private key to install.
4049      * @param certs The certificate chain to install. The chain should start with the leaf
4050      *        certificate and include the chain of trust in order. This will be returned by
4051      *        {@link android.security.KeyChain#getCertificateChain}.
4052      * @param alias The private key alias under which to install the certificate. If a certificate
4053      *        with that alias already exists, it will be overwritten.
4054      * @param requestAccess {@code true} to request that the calling app be granted access to the
4055      *        credentials immediately. Otherwise, access to the credentials will be gated by user
4056      *        approval.
4057      * @return {@code true} if the keys were installed, {@code false} otherwise.
4058      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4059      *         owner.
4060      * @see android.security.KeyChain#getCertificateChain
4061      * @see #setDelegatedScopes
4062      * @see #DELEGATION_CERT_INSTALL
4063      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)4064     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4065             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
4066         int flags = INSTALLKEY_SET_USER_SELECTABLE;
4067         if (requestAccess) {
4068             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
4069         }
4070         return installKeyPair(admin, privKey, certs, alias, flags);
4071     }
4072 
4073     /**
4074      * Called by a device or profile owner, or delegated certificate installer, to install a
4075      * certificate chain and corresponding private key for the leaf certificate. All apps within the
4076      * profile will be able to access the certificate chain and use the private key, given direct
4077      * user approval (if the user is allowed to select the private key).
4078      *
4079      * <p>The caller of this API may grant itself access to the certificate and private key
4080      * immediately, without user approval. It is a best practice not to request this unless strictly
4081      * necessary since it opens up additional security vulnerabilities.
4082      *
4083      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
4084      * the user to select the key from a dialog.
4085      *
4086      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4087      *        {@code null} if calling from a delegated certificate installer.
4088      * @param privKey The private key to install.
4089      * @param certs The certificate chain to install. The chain should start with the leaf
4090      *        certificate and include the chain of trust in order. This will be returned by
4091      *        {@link android.security.KeyChain#getCertificateChain}.
4092      * @param alias The private key alias under which to install the certificate. If a certificate
4093      *        with that alias already exists, it will be overwritten.
4094      * @param flags Flags to request that the calling app be granted access to the credentials
4095      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
4096      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
4097      * @return {@code true} if the keys were installed, {@code false} otherwise.
4098      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4099      *         owner.
4100      * @see android.security.KeyChain#getCertificateChain
4101      * @see #setDelegatedScopes
4102      * @see #DELEGATION_CERT_INSTALL
4103      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)4104     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4105             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
4106         throwIfParentInstance("installKeyPair");
4107         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
4108                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
4109         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
4110                 == INSTALLKEY_SET_USER_SELECTABLE;
4111         try {
4112             final byte[] pemCert = Credentials.convertToPem(certs[0]);
4113             byte[] pemChain = null;
4114             if (certs.length > 1) {
4115                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
4116             }
4117             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
4118                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
4119             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
4120                     pemChain, alias, requestAccess, isUserSelectable);
4121         } catch (RemoteException e) {
4122             throw e.rethrowFromSystemServer();
4123         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
4124             Log.w(TAG, "Failed to obtain private key material", e);
4125         } catch (CertificateException | IOException e) {
4126             Log.w(TAG, "Could not pem-encode certificate", e);
4127         }
4128         return false;
4129     }
4130 
4131     /**
4132      * Called by a device or profile owner, or delegated certificate installer, to remove a
4133      * certificate and private key pair installed under a given alias.
4134      *
4135      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4136      *        {@code null} if calling from a delegated certificate installer.
4137      * @param alias The private key alias under which the certificate is installed.
4138      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
4139      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4140      *         owner.
4141      * @see #setDelegatedScopes
4142      * @see #DELEGATION_CERT_INSTALL
4143      */
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)4144     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
4145         throwIfParentInstance("removeKeyPair");
4146         try {
4147             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4148         } catch (RemoteException e) {
4149             throw e.rethrowFromSystemServer();
4150         }
4151     }
4152 
4153     /**
4154      * Called by a device or profile owner, or delegated certificate installer, to generate a
4155      * new private/public key pair. If the device supports key generation via secure hardware,
4156      * this method is useful for creating a key in KeyChain that never left the secure hardware.
4157      *
4158      * Access to the key is controlled the same way as in {@link #installKeyPair}.
4159      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4160      *            {@code null} if calling from a delegated certificate installer.
4161      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
4162      * @param keySpec Specification of the key to generate, see
4163      * {@link java.security.KeyPairGenerator}.
4164      * @param idAttestationFlags A bitmask of all the identifiers that should be included in the
4165      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
4166      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), or {@code 0} if no device
4167      *        identification is required in the attestation record.
4168      *        Device owner, profile owner and their delegated certificate installer can use
4169      *        {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device information
4170      *        including manufacturer, model, brand, device and product in the attestation record.
4171      *        Only device owner and their delegated certificate installer can use
4172      *        {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID} to request
4173      *        unique device identifiers to be attested.
4174      *        <p>
4175      *        If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
4176      *        is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
4177      *        <p>
4178      *        If any flag is specified, then an attestation challenge must be included in the
4179      *        {@code keySpec}.
4180      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
4181      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4182      *         owner. If Device ID attestation is requested (using {@link #ID_TYPE_SERIAL},
4183      *         {@link #ID_TYPE_IMEI} or {@link #ID_TYPE_MEID}), the caller must be the Device Owner
4184      *         or the Certificate Installer delegate.
4185      * @throws IllegalArgumentException if the alias in {@code keySpec} is empty, if the
4186      *         algorithm specification in {@code keySpec} is not {@code RSAKeyGenParameterSpec}
4187      *         or {@code ECGenParameterSpec}, or if Device ID attestation was requested but the
4188      *         {@code keySpec} does not contain an attestation challenge.
4189      * @throws UnsupportedOperationException if Device ID attestation was requested but the
4190      *         underlying hardware does not support it.
4191      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
4192      */
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)4193     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
4194             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
4195             @AttestationIdType int idAttestationFlags) {
4196         throwIfParentInstance("generateKeyPair");
4197         try {
4198             final ParcelableKeyGenParameterSpec parcelableSpec =
4199                     new ParcelableKeyGenParameterSpec(keySpec);
4200             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
4201 
4202             // Translate ID attestation flags to values used by AttestationUtils
4203             final boolean success = mService.generateKeyPair(
4204                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
4205                     idAttestationFlags, attestationChain);
4206             if (!success) {
4207                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
4208                 return null;
4209             }
4210 
4211             final String alias = keySpec.getKeystoreAlias();
4212             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
4213             Certificate[] outputChain = null;
4214             try {
4215                 if (AttestationUtils.isChainValid(attestationChain)) {
4216                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
4217                 }
4218             } catch (KeyAttestationException e) {
4219                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
4220                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4221                 return null;
4222             }
4223             return new AttestedKeyPair(keyPair, outputChain);
4224         } catch (RemoteException e) {
4225             throw e.rethrowFromSystemServer();
4226         } catch (KeyChainException e) {
4227             Log.w(TAG, "Failed to generate key", e);
4228         } catch (InterruptedException e) {
4229             Log.w(TAG, "Interrupted while generating key", e);
4230             Thread.currentThread().interrupt();
4231         }
4232         return null;
4233     }
4234 
4235     /**
4236      * Returns {@code true} if the device supports attestation of device identifiers in addition
4237      * to key attestation.
4238      * @return {@code true} if Device ID attestation is supported.
4239      */
isDeviceIdAttestationSupported()4240     public boolean isDeviceIdAttestationSupported() {
4241         PackageManager pm = mContext.getPackageManager();
4242         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
4243     }
4244 
4245     /**
4246      * Called by a device or profile owner, or delegated certificate installer, to associate
4247      * certificates with a key pair that was generated using {@link #generateKeyPair}, and
4248      * set whether the key is available for the user to choose in the certificate selection
4249      * prompt.
4250      *
4251      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4252      *            {@code null} if calling from a delegated certificate installer.
4253      * @param alias The private key alias under which to install the certificate. The {@code alias}
4254      *        should denote an existing private key. If a certificate with that alias already
4255      *        exists, it will be overwritten.
4256      * @param certs The certificate chain to install. The chain should start with the leaf
4257      *        certificate and include the chain of trust in order. This will be returned by
4258      *        {@link android.security.KeyChain#getCertificateChain}.
4259      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
4260      *        certificate selection prompt, {@code false} to indicate that this key can only be
4261      *        granted access by implementing
4262      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
4263      * @return {@code true} if the provided {@code alias} exists and the certificates has been
4264      *        successfully associated with it, {@code false} otherwise.
4265      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4266      *         owner, or {@code admin} is null but the calling application is not a delegated
4267      *         certificate installer.
4268      */
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)4269     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
4270             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
4271         throwIfParentInstance("setKeyPairCertificate");
4272         try {
4273             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
4274             byte[] pemChain = null;
4275             if (certs.size() > 1) {
4276                 pemChain = Credentials.convertToPem(
4277                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
4278             }
4279             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
4280                     pemChain, isUserSelectable);
4281         } catch (RemoteException e) {
4282             throw e.rethrowFromSystemServer();
4283         } catch (CertificateException | IOException e) {
4284             Log.w(TAG, "Could not pem-encode certificate", e);
4285         }
4286         return false;
4287     }
4288 
4289 
4290     /**
4291      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
4292      * doesn't exist.
4293      */
getCaCertAlias(byte[] certBuffer)4294     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
4295         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4296         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
4297                               new ByteArrayInputStream(certBuffer));
4298         return new TrustedCertificateStore().getCertificateAlias(cert);
4299     }
4300 
4301     /**
4302      * Called by a profile owner or device owner to grant access to privileged certificate
4303      * manipulation APIs to a third-party certificate installer app. Granted APIs include
4304      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
4305      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
4306      * <p>
4307      * Delegated certificate installer is a per-user state. The delegated access is persistent until
4308      * it is later cleared by calling this method with a null value or uninstallling the certificate
4309      * installer.
4310      * <p>
4311      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
4312      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
4313      * supplied certificate installer package must be installed when calling this API, otherwise an
4314      * {@link IllegalArgumentException} will be thrown.
4315      *
4316      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4317      * @param installerPackage The package name of the certificate installer which will be given
4318      *            access. If {@code null} is given the current package will be cleared.
4319      * @throws SecurityException if {@code admin} is not a device or a profile owner.
4320      *
4321      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
4322      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
4323      */
4324     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)4325     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
4326             installerPackage) throws SecurityException {
4327         throwIfParentInstance("setCertInstallerPackage");
4328         if (mService != null) {
4329             try {
4330                 mService.setCertInstallerPackage(admin, installerPackage);
4331             } catch (RemoteException e) {
4332                 throw e.rethrowFromSystemServer();
4333             }
4334         }
4335     }
4336 
4337     /**
4338      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
4339      * or {@code null} if none is set. If there are multiple delegates this function will return one
4340      * of them.
4341      *
4342      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4343      * @return The package name of the current delegated certificate installer, or {@code null} if
4344      *         none is set.
4345      * @throws SecurityException if {@code admin} is not a device or a profile owner.
4346      *
4347      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
4348      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
4349      */
4350     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)4351     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
4352             throws SecurityException {
4353         throwIfParentInstance("getCertInstallerPackage");
4354         if (mService != null) {
4355             try {
4356                 return mService.getCertInstallerPackage(admin);
4357             } catch (RemoteException e) {
4358                 throw e.rethrowFromSystemServer();
4359             }
4360         }
4361         return null;
4362     }
4363 
4364     /**
4365      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
4366      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
4367      * constants.
4368      * <p>
4369      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
4370      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
4371      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
4372      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
4373      * <p>
4374      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
4375      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
4376      * {@code delegatePackage}.
4377      *
4378      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4379      * @param delegatePackage The package name of the app which will be given access.
4380      * @param scopes The groups of privileged APIs whose access should be granted to
4381      *            {@code delegatedPackage}.
4382      * @throws SecurityException if {@code admin} is not a device or a profile owner.
4383      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)4384      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
4385             @NonNull List<String> scopes) {
4386         throwIfParentInstance("setDelegatedScopes");
4387         if (mService != null) {
4388             try {
4389                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
4390             } catch (RemoteException e) {
4391                 throw e.rethrowFromSystemServer();
4392             }
4393         }
4394     }
4395 
4396     /**
4397      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
4398      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
4399      * passing {@code null} for {@code admin} and their own package name as
4400      * {@code delegatedPackage}.
4401      *
4402      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4403      *            {@code null} if the caller is {@code delegatedPackage}.
4404      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
4405      * @return A list containing the scopes given to {@code delegatedPackage}.
4406      * @throws SecurityException if {@code admin} is not a device or a profile owner.
4407      */
4408      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)4409      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
4410              @NonNull String delegatedPackage) {
4411          throwIfParentInstance("getDelegatedScopes");
4412          if (mService != null) {
4413              try {
4414                  return mService.getDelegatedScopes(admin, delegatedPackage);
4415              } catch (RemoteException e) {
4416                  throw e.rethrowFromSystemServer();
4417              }
4418          }
4419          return null;
4420     }
4421 
4422     /**
4423      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
4424      * granted a delegation scope.
4425      *
4426      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4427      * @param delegationScope The scope whose delegates should be retrieved.
4428      * @return A list of package names of the current delegated packages for
4429                {@code delegationScope}.
4430      * @throws SecurityException if {@code admin} is not a device or a profile owner.
4431      */
4432      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)4433      public List<String> getDelegatePackages(@NonNull ComponentName admin,
4434              @NonNull String delegationScope) {
4435         throwIfParentInstance("getDelegatePackages");
4436         if (mService != null) {
4437             try {
4438                 return mService.getDelegatePackages(admin, delegationScope);
4439             } catch (RemoteException e) {
4440                 throw e.rethrowFromSystemServer();
4441             }
4442         }
4443         return null;
4444     }
4445 
4446     /**
4447      * Called by a device or profile owner to configure an always-on VPN connection through a
4448      * specific application for the current user. This connection is automatically granted and
4449      * persisted after a reboot.
4450      * <p>
4451      * To support the always-on feature, an app must
4452      * <ul>
4453      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
4454      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
4455      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
4456      *     <li><i>not</i> explicitly opt out of the feature through
4457      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
4458      * </ul>
4459      * The call will fail if called with the package name of an unsupported VPN app.
4460      *
4461      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
4462      *        remove an existing always-on VPN configuration.
4463      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
4464      *        {@code false} otherwise. This carries the risk that any failure of the VPN provider
4465      *        could break networking for all apps. This has no effect when clearing.
4466      * @throws SecurityException if {@code admin} is not a device or a profile owner.
4467      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
4468      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
4469      *         set as always-on, or if always-on VPN is not available.
4470      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)4471     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
4472             boolean lockdownEnabled)
4473             throws NameNotFoundException, UnsupportedOperationException {
4474         throwIfParentInstance("setAlwaysOnVpnPackage");
4475         if (mService != null) {
4476             try {
4477                 if (!mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled)) {
4478                     throw new NameNotFoundException(vpnPackage);
4479                 }
4480             } catch (RemoteException e) {
4481                 throw e.rethrowFromSystemServer();
4482             }
4483         }
4484     }
4485 
4486     /**
4487      * Called by a device or profile owner to read the name of the package administering an
4488      * always-on VPN connection for the current user. If there is no such package, or the always-on
4489      * VPN is provided by the system instead of by an application, {@code null} will be returned.
4490      *
4491      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
4492      *         is set.
4493      * @throws SecurityException if {@code admin} is not a device or a profile owner.
4494      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)4495     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
4496         throwIfParentInstance("getAlwaysOnVpnPackage");
4497         if (mService != null) {
4498             try {
4499                 return mService.getAlwaysOnVpnPackage(admin);
4500             } catch (RemoteException e) {
4501                 throw e.rethrowFromSystemServer();
4502             }
4503         }
4504         return null;
4505     }
4506 
4507     /**
4508      * Called by an application that is administering the device to disable all cameras on the
4509      * device, for this user. After setting this, no applications running as this user will be able
4510      * to access any cameras on the device.
4511      * <p>
4512      * If the caller is device owner, then the restriction will be applied to all users.
4513      * <p>
4514      * The calling device admin must have requested
4515      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
4516      * not, a security exception will be thrown.
4517      *
4518      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4519      * @param disabled Whether or not the camera should be disabled.
4520      * @throws SecurityException if {@code admin} is not an active administrator or does not use
4521      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
4522      */
setCameraDisabled(@onNull ComponentName admin, boolean disabled)4523     public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
4524         throwIfParentInstance("setCameraDisabled");
4525         if (mService != null) {
4526             try {
4527                 mService.setCameraDisabled(admin, disabled);
4528             } catch (RemoteException e) {
4529                 throw e.rethrowFromSystemServer();
4530             }
4531         }
4532     }
4533 
4534     /**
4535      * Determine whether or not the device's cameras have been disabled for this user,
4536      * either by the calling admin, if specified, or all admins.
4537      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4538      * have disabled the camera
4539      */
getCameraDisabled(@ullable ComponentName admin)4540     public boolean getCameraDisabled(@Nullable ComponentName admin) {
4541         throwIfParentInstance("getCameraDisabled");
4542         return getCameraDisabled(admin, myUserId());
4543     }
4544 
4545     /** @hide per-user version */
getCameraDisabled(@ullable ComponentName admin, int userHandle)4546     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
4547         if (mService != null) {
4548             try {
4549                 return mService.getCameraDisabled(admin, userHandle);
4550             } catch (RemoteException e) {
4551                 throw e.rethrowFromSystemServer();
4552             }
4553         }
4554         return false;
4555     }
4556 
4557     /**
4558      * Called by a device owner to request a bugreport.
4559      * <p>
4560      * If the device contains secondary users or profiles, they must be affiliated with the device.
4561      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
4562      *
4563      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4564      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
4565      *         wasn't triggered because a previous bugreport operation is still active (either the
4566      *         bugreport is still running or waiting for the user to share or decline)
4567      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
4568      *         profile or secondary user that is not affiliated with the device.
4569      * @see #isAffiliatedUser
4570      */
requestBugreport(@onNull ComponentName admin)4571     public boolean requestBugreport(@NonNull ComponentName admin) {
4572         throwIfParentInstance("requestBugreport");
4573         if (mService != null) {
4574             try {
4575                 return mService.requestBugreport(admin);
4576             } catch (RemoteException e) {
4577                 throw e.rethrowFromSystemServer();
4578             }
4579         }
4580         return false;
4581     }
4582 
4583     /**
4584      * Determine whether or not creating a guest user has been disabled for the device
4585      *
4586      * @hide
4587      */
getGuestUserDisabled(@ullable ComponentName admin)4588     public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
4589         // Currently guest users can always be created if multi-user is enabled
4590         // TODO introduce a policy for guest user creation
4591         return false;
4592     }
4593 
4594     /**
4595      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
4596      * screen capture also prevents the content from being shown on display devices that do not have
4597      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
4598      * secure surfaces and secure displays.
4599      * <p>
4600      * The calling device admin must be a device or profile owner. If it is not, a security
4601      * exception will be thrown.
4602      * <p>
4603      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
4604      * assist requests for all activities of the relevant user.
4605      *
4606      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4607      * @param disabled Whether screen capture is disabled or not.
4608      * @throws SecurityException if {@code admin} is not a device or profile owner.
4609      */
setScreenCaptureDisabled(@onNull ComponentName admin, boolean disabled)4610     public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
4611         throwIfParentInstance("setScreenCaptureDisabled");
4612         if (mService != null) {
4613             try {
4614                 mService.setScreenCaptureDisabled(admin, disabled);
4615             } catch (RemoteException e) {
4616                 throw e.rethrowFromSystemServer();
4617             }
4618         }
4619     }
4620 
4621     /**
4622      * Determine whether or not screen capture has been disabled by the calling
4623      * admin, if specified, or all admins.
4624      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4625      * have disabled screen capture.
4626      */
getScreenCaptureDisabled(@ullable ComponentName admin)4627     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
4628         throwIfParentInstance("getScreenCaptureDisabled");
4629         return getScreenCaptureDisabled(admin, myUserId());
4630     }
4631 
4632     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)4633     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
4634         if (mService != null) {
4635             try {
4636                 return mService.getScreenCaptureDisabled(admin, userHandle);
4637             } catch (RemoteException e) {
4638                 throw e.rethrowFromSystemServer();
4639             }
4640         }
4641         return false;
4642     }
4643 
4644     /**
4645      * Called by a device or profile owner to set whether auto time is required. If auto time is
4646      * required, no user will be able set the date and time and network date and time will be used.
4647      * <p>
4648      * Note: if auto time is required the user can still manually set the time zone.
4649      * <p>
4650      * The calling device admin must be a device or profile owner. If it is not, a security
4651      * exception will be thrown.
4652      *
4653      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4654      * @param required Whether auto time is set required or not.
4655      * @throws SecurityException if {@code admin} is not a device owner.
4656      */
setAutoTimeRequired(@onNull ComponentName admin, boolean required)4657     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
4658         throwIfParentInstance("setAutoTimeRequired");
4659         if (mService != null) {
4660             try {
4661                 mService.setAutoTimeRequired(admin, required);
4662             } catch (RemoteException e) {
4663                 throw e.rethrowFromSystemServer();
4664             }
4665         }
4666     }
4667 
4668     /**
4669      * @return true if auto time is required.
4670      */
getAutoTimeRequired()4671     public boolean getAutoTimeRequired() {
4672         throwIfParentInstance("getAutoTimeRequired");
4673         if (mService != null) {
4674             try {
4675                 return mService.getAutoTimeRequired();
4676             } catch (RemoteException e) {
4677                 throw e.rethrowFromSystemServer();
4678             }
4679         }
4680         return false;
4681     }
4682 
4683     /**
4684      * Called by a device owner to set whether all users created on the device should be ephemeral.
4685      * <p>
4686      * The system user is exempt from this policy - it is never ephemeral.
4687      * <p>
4688      * The calling device admin must be the device owner. If it is not, a security exception will be
4689      * thrown.
4690      *
4691      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4692      * @param forceEphemeralUsers If true, all the existing users will be deleted and all
4693      *            subsequently created users will be ephemeral.
4694      * @throws SecurityException if {@code admin} is not a device owner.
4695      * @hide
4696      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)4697     public void setForceEphemeralUsers(
4698             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
4699         throwIfParentInstance("setForceEphemeralUsers");
4700         if (mService != null) {
4701             try {
4702                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
4703             } catch (RemoteException e) {
4704                 throw e.rethrowFromSystemServer();
4705             }
4706         }
4707     }
4708 
4709     /**
4710      * @return true if all users are created ephemeral.
4711      * @throws SecurityException if {@code admin} is not a device owner.
4712      * @hide
4713      */
getForceEphemeralUsers(@onNull ComponentName admin)4714     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
4715         throwIfParentInstance("getForceEphemeralUsers");
4716         if (mService != null) {
4717             try {
4718                 return mService.getForceEphemeralUsers(admin);
4719             } catch (RemoteException e) {
4720                 throw e.rethrowFromSystemServer();
4721             }
4722         }
4723         return false;
4724     }
4725 
4726     /**
4727      * Called by an application that is administering the device to disable keyguard customizations,
4728      * such as widgets. After setting this, keyguard features will be disabled according to the
4729      * provided feature list.
4730      * <p>
4731      * The calling device admin must have requested
4732      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
4733      * if it has not, a security exception will be thrown.
4734      * <p>
4735      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
4736      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
4737      * profile owner of a managed profile can set:
4738      * <ul>
4739      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
4740      * is no separate challenge set on the managed profile.
4741      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
4742      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
4743      * there is one, or the parent user otherwise.
4744      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
4745      * by applications in the managed profile.
4746      * </ul>
4747      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
4748      * {@link #KEYGUARD_DISABLE_FACE} and {@link #KEYGUARD_DISABLE_IRIS} can also be
4749      * set on the {@link DevicePolicyManager} instance returned by
4750      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4751      * profile.
4752      * <p>
4753      * Requests to disable other features on a managed profile will be ignored.
4754      * <p>
4755      * The admin can check which features have been disabled by calling
4756      * {@link #getKeyguardDisabledFeatures(ComponentName)}
4757      *
4758      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4759      * @param which The disabled features flag which can be either
4760      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
4761      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
4762      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
4763      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
4764      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
4765      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
4766      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
4767      *            {@link #KEYGUARD_DISABLE_FACE},
4768      *            {@link #KEYGUARD_DISABLE_IRIS}.
4769      * @throws SecurityException if {@code admin} is not an active administrator or does not user
4770      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
4771      */
setKeyguardDisabledFeatures(@onNull ComponentName admin, int which)4772     public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
4773         if (mService != null) {
4774             try {
4775                 mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
4776             } catch (RemoteException e) {
4777                 throw e.rethrowFromSystemServer();
4778             }
4779         }
4780     }
4781 
4782     /**
4783      * Determine whether or not features have been disabled in keyguard either by the calling
4784      * admin, if specified, or all admins that set restrictions on this user and its participating
4785      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
4786      *
4787      * <p>This method can be called on the {@link DevicePolicyManager} instance
4788      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4789      * restrictions on the parent profile.
4790      *
4791      * @param admin The name of the admin component to check, or {@code null} to check whether any
4792      * admins have disabled features in keyguard.
4793      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
4794      * for a list.
4795      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)4796     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
4797         return getKeyguardDisabledFeatures(admin, myUserId());
4798     }
4799 
4800     /** @hide per-user version */
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)4801     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
4802         if (mService != null) {
4803             try {
4804                 return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
4805             } catch (RemoteException e) {
4806                 throw e.rethrowFromSystemServer();
4807             }
4808         }
4809         return KEYGUARD_DISABLE_FEATURES_NONE;
4810     }
4811 
4812     /**
4813      * @hide
4814      */
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)4815     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
4816             int userHandle) {
4817         if (mService != null) {
4818             try {
4819                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
4820             } catch (RemoteException e) {
4821                 throw e.rethrowFromSystemServer();
4822             }
4823         }
4824     }
4825 
4826     /**
4827      * @hide
4828      */
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)4829     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
4830         setActiveAdmin(policyReceiver, refreshing, myUserId());
4831     }
4832 
4833     /**
4834      * @hide
4835      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)4836     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
4837         if (mService != null) {
4838             try {
4839                 mService.getRemoveWarning(admin, result, myUserId());
4840             } catch (RemoteException e) {
4841                 throw e.rethrowFromSystemServer();
4842             }
4843         }
4844     }
4845 
4846     /**
4847      * @hide
4848      */
setActivePasswordState(PasswordMetrics metrics, int userHandle)4849     public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
4850         if (mService != null) {
4851             try {
4852                 mService.setActivePasswordState(metrics, userHandle);
4853             } catch (RemoteException e) {
4854                 throw e.rethrowFromSystemServer();
4855             }
4856         }
4857     }
4858 
4859     /**
4860      * @hide
4861      */
reportPasswordChanged(@serIdInt int userId)4862     public void reportPasswordChanged(@UserIdInt int userId) {
4863         if (mService != null) {
4864             try {
4865                 mService.reportPasswordChanged(userId);
4866             } catch (RemoteException e) {
4867                 throw e.rethrowFromSystemServer();
4868             }
4869         }
4870     }
4871 
4872     /**
4873      * @hide
4874      */
reportFailedPasswordAttempt(int userHandle)4875     public void reportFailedPasswordAttempt(int userHandle) {
4876         if (mService != null) {
4877             try {
4878                 mService.reportFailedPasswordAttempt(userHandle);
4879             } catch (RemoteException e) {
4880                 throw e.rethrowFromSystemServer();
4881             }
4882         }
4883     }
4884 
4885     /**
4886      * @hide
4887      */
reportSuccessfulPasswordAttempt(int userHandle)4888     public void reportSuccessfulPasswordAttempt(int userHandle) {
4889         if (mService != null) {
4890             try {
4891                 mService.reportSuccessfulPasswordAttempt(userHandle);
4892             } catch (RemoteException e) {
4893                 throw e.rethrowFromSystemServer();
4894             }
4895         }
4896     }
4897 
4898     /**
4899      * @hide
4900      */
reportFailedFingerprintAttempt(int userHandle)4901     public void reportFailedFingerprintAttempt(int userHandle) {
4902         if (mService != null) {
4903             try {
4904                 mService.reportFailedFingerprintAttempt(userHandle);
4905             } catch (RemoteException e) {
4906                 throw e.rethrowFromSystemServer();
4907             }
4908         }
4909     }
4910 
4911     /**
4912      * @hide
4913      */
reportSuccessfulFingerprintAttempt(int userHandle)4914     public void reportSuccessfulFingerprintAttempt(int userHandle) {
4915         if (mService != null) {
4916             try {
4917                 mService.reportSuccessfulFingerprintAttempt(userHandle);
4918             } catch (RemoteException e) {
4919                 throw e.rethrowFromSystemServer();
4920             }
4921         }
4922     }
4923 
4924     /**
4925      * Should be called when keyguard has been dismissed.
4926      * @hide
4927      */
reportKeyguardDismissed(int userHandle)4928     public void reportKeyguardDismissed(int userHandle) {
4929         if (mService != null) {
4930             try {
4931                 mService.reportKeyguardDismissed(userHandle);
4932             } catch (RemoteException e) {
4933                 throw e.rethrowFromSystemServer();
4934             }
4935         }
4936     }
4937 
4938     /**
4939      * Should be called when keyguard view has been shown to the user.
4940      * @hide
4941      */
reportKeyguardSecured(int userHandle)4942     public void reportKeyguardSecured(int userHandle) {
4943         if (mService != null) {
4944             try {
4945                 mService.reportKeyguardSecured(userHandle);
4946             } catch (RemoteException e) {
4947                 throw e.rethrowFromSystemServer();
4948             }
4949         }
4950     }
4951 
4952     /**
4953      * @hide
4954      * Sets the given package as the device owner.
4955      * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
4956      * @param who the component name to be registered as device owner.
4957      * @return whether the package was successfully registered as the device owner.
4958      * @throws IllegalArgumentException if the package name is null or invalid
4959      * @throws IllegalStateException If the preconditions mentioned are not met.
4960      */
setDeviceOwner(ComponentName who)4961     public boolean setDeviceOwner(ComponentName who) {
4962         return setDeviceOwner(who, null);
4963     }
4964 
4965     /**
4966      * @hide
4967      */
setDeviceOwner(ComponentName who, int userId)4968     public boolean setDeviceOwner(ComponentName who, int userId)  {
4969         return setDeviceOwner(who, null, userId);
4970     }
4971 
4972     /**
4973      * @hide
4974      */
setDeviceOwner(ComponentName who, String ownerName)4975     public boolean setDeviceOwner(ComponentName who, String ownerName) {
4976         return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
4977     }
4978 
4979     /**
4980      * @hide
4981      * Sets the given package as the device owner. The package must already be installed. There
4982      * must not already be a device owner.
4983      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
4984      * this method.
4985      * Calling this after the setup phase of the primary user has completed is allowed only if
4986      * the caller is the shell uid, and there are no additional users and no accounts.
4987      * @param who the component name to be registered as device owner.
4988      * @param ownerName the human readable name of the institution that owns this device.
4989      * @param userId ID of the user on which the device owner runs.
4990      * @return whether the package was successfully registered as the device owner.
4991      * @throws IllegalArgumentException if the package name is null or invalid
4992      * @throws IllegalStateException If the preconditions mentioned are not met.
4993      */
setDeviceOwner(ComponentName who, String ownerName, int userId)4994     public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
4995             throws IllegalArgumentException, IllegalStateException {
4996         if (mService != null) {
4997             try {
4998                 return mService.setDeviceOwner(who, ownerName, userId);
4999             } catch (RemoteException re) {
5000                 throw re.rethrowFromSystemServer();
5001             }
5002         }
5003         return false;
5004     }
5005 
5006     /**
5007      * Used to determine if a particular package has been registered as a Device Owner app.
5008      * A device owner app is a special device admin that cannot be deactivated by the user, once
5009      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
5010      * package is currently registered as the device owner app, pass in the package name from
5011      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
5012      * admin apps that want to check whether they are also registered as the device owner app. The
5013      * exact mechanism by which a device admin app is registered as a device owner app is defined by
5014      * the setup process.
5015      * @param packageName the package name of the app, to compare with the registered device owner
5016      * app, if any.
5017      * @return whether or not the package is registered as the device owner app.
5018      */
isDeviceOwnerApp(String packageName)5019     public boolean isDeviceOwnerApp(String packageName) {
5020         throwIfParentInstance("isDeviceOwnerApp");
5021         return isDeviceOwnerAppOnCallingUser(packageName);
5022     }
5023 
5024     /**
5025      * @return true if a package is registered as device owner, only when it's running on the
5026      * calling user.
5027      *
5028      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
5029      * @hide
5030      */
isDeviceOwnerAppOnCallingUser(String packageName)5031     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
5032         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
5033     }
5034 
5035     /**
5036      * @return true if a package is registered as device owner, even if it's running on a different
5037      * user.
5038      *
5039      * <p>Requires the MANAGE_USERS permission.
5040      *
5041      * @hide
5042      */
isDeviceOwnerAppOnAnyUser(String packageName)5043     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
5044         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
5045     }
5046 
5047     /**
5048      * @return device owner component name, only when it's running on the calling user.
5049      *
5050      * @hide
5051      */
getDeviceOwnerComponentOnCallingUser()5052     public ComponentName getDeviceOwnerComponentOnCallingUser() {
5053         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
5054     }
5055 
5056     /**
5057      * @return device owner component name, even if it's running on a different user.
5058      *
5059      * @hide
5060      */
5061     @SystemApi
5062     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerComponentOnAnyUser()5063     public ComponentName getDeviceOwnerComponentOnAnyUser() {
5064         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
5065     }
5066 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)5067     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
5068         if (packageName == null) {
5069             return false;
5070         }
5071         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
5072         if (deviceOwner == null) {
5073             return false;
5074         }
5075         return packageName.equals(deviceOwner.getPackageName());
5076     }
5077 
getDeviceOwnerComponentInner(boolean callingUserOnly)5078     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
5079         if (mService != null) {
5080             try {
5081                 return mService.getDeviceOwnerComponent(callingUserOnly);
5082             } catch (RemoteException re) {
5083                 throw re.rethrowFromSystemServer();
5084             }
5085         }
5086         return null;
5087     }
5088 
5089     /**
5090      * @return ID of the user who runs device owner, or {@link UserHandle#USER_NULL} if there's
5091      * no device owner.
5092      *
5093      * <p>Requires the MANAGE_USERS permission.
5094      *
5095      * @hide
5096      */
getDeviceOwnerUserId()5097     public int getDeviceOwnerUserId() {
5098         if (mService != null) {
5099             try {
5100                 return mService.getDeviceOwnerUserId();
5101             } catch (RemoteException re) {
5102                 throw re.rethrowFromSystemServer();
5103             }
5104         }
5105         return UserHandle.USER_NULL;
5106     }
5107 
5108     /**
5109      * Clears the current device owner. The caller must be the device owner. This function should be
5110      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
5111      * a part of device setup, before it completes.
5112      * <p>
5113      * While some policies previously set by the device owner will be cleared by this method, it is
5114      * a best-effort process and some other policies will still remain in place after the device
5115      * owner is cleared.
5116      *
5117      * @param packageName The package name of the device owner.
5118      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
5119      *             does not own the current device owner component.
5120      *
5121      * @deprecated This method is expected to be used for testing purposes only. The device owner
5122      * will lose control of the device and its data after calling it. In order to protect any
5123      * sensitive data that remains on the device, it is advised that the device owner factory resets
5124      * the device instead of calling this method. See {@link #wipeData(int)}.
5125      */
5126     @Deprecated
clearDeviceOwnerApp(String packageName)5127     public void clearDeviceOwnerApp(String packageName) {
5128         throwIfParentInstance("clearDeviceOwnerApp");
5129         if (mService != null) {
5130             try {
5131                 mService.clearDeviceOwner(packageName);
5132             } catch (RemoteException re) {
5133                 throw re.rethrowFromSystemServer();
5134             }
5135         }
5136     }
5137 
5138     /**
5139      * Returns the device owner package name, only if it's running on the calling user.
5140      *
5141      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
5142      *
5143      * @hide
5144      */
5145     @SystemApi
5146     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()5147     public @Nullable String getDeviceOwner() {
5148         throwIfParentInstance("getDeviceOwner");
5149         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
5150         return name != null ? name.getPackageName() : null;
5151     }
5152 
5153     /**
5154      * Called by the system to find out whether the device is managed by a Device Owner.
5155      *
5156      * @return whether the device is managed by a Device Owner.
5157      * @throws SecurityException if the caller is not the device owner, does not hold the
5158      *         MANAGE_USERS permission and is not the system.
5159      *
5160      * @hide
5161      */
5162     @SystemApi
5163     @TestApi
5164     @SuppressLint("Doclava125")
isDeviceManaged()5165     public boolean isDeviceManaged() {
5166         try {
5167             return mService.hasDeviceOwner();
5168         } catch (RemoteException re) {
5169             throw re.rethrowFromSystemServer();
5170         }
5171     }
5172 
5173     /**
5174      * Returns the device owner name.  Note this method *will* return the device owner
5175      * name when it's running on a different user.
5176      *
5177      * @hide
5178      */
5179     @SystemApi
5180     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerNameOnAnyUser()5181     public String getDeviceOwnerNameOnAnyUser() {
5182         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
5183         if (mService != null) {
5184             try {
5185                 return mService.getDeviceOwnerName();
5186             } catch (RemoteException re) {
5187                 throw re.rethrowFromSystemServer();
5188             }
5189         }
5190         return null;
5191     }
5192 
5193     /**
5194      * @hide
5195      * @deprecated Do not use
5196      * @removed
5197      */
5198     @Deprecated
5199     @SystemApi
5200     @SuppressLint("Doclava125")
getDeviceInitializerApp()5201     public @Nullable String getDeviceInitializerApp() {
5202         return null;
5203     }
5204 
5205     /**
5206      * @hide
5207      * @deprecated Do not use
5208      * @removed
5209      */
5210     @Deprecated
5211     @SystemApi
5212     @SuppressLint("Doclava125")
getDeviceInitializerComponent()5213     public @Nullable ComponentName getDeviceInitializerComponent() {
5214         return null;
5215     }
5216 
5217     /**
5218      * @hide
5219      * @deprecated Use #ACTION_SET_PROFILE_OWNER
5220      * Sets the given component as an active admin and registers the package as the profile
5221      * owner for this user. The package must already be installed and there shouldn't be
5222      * an existing profile owner registered for this user. Also, this method must be called
5223      * before the user setup has been completed.
5224      * <p>
5225      * This method can only be called by system apps that hold MANAGE_USERS permission and
5226      * MANAGE_DEVICE_ADMINS permission.
5227      * @param admin The component to register as an active admin and profile owner.
5228      * @param ownerName The user-visible name of the entity that is managing this user.
5229      * @return whether the admin was successfully registered as the profile owner.
5230      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
5231      *         the user has already been set up.
5232      */
5233     @Deprecated
5234     @SystemApi
5235     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName)5236     public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
5237             throws IllegalArgumentException {
5238         throwIfParentInstance("setActiveProfileOwner");
5239         if (mService != null) {
5240             try {
5241                 final int myUserId = myUserId();
5242                 mService.setActiveAdmin(admin, false, myUserId);
5243                 return mService.setProfileOwner(admin, ownerName, myUserId);
5244             } catch (RemoteException re) {
5245                 throw re.rethrowFromSystemServer();
5246             }
5247         }
5248         return false;
5249     }
5250 
5251     /**
5252      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
5253      * a SecurityException will be thrown. This method is not available to managed profile owners.
5254      * <p>
5255      * While some policies previously set by the profile owner will be cleared by this method, it is
5256      * a best-effort process and some other policies will still remain in place after the profile
5257      * owner is cleared.
5258      *
5259      * @param admin The component to remove as the profile owner.
5260      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
5261      * being called from a managed profile.
5262      *
5263      * @deprecated This method is expected to be used for testing purposes only. The profile owner
5264      * will lose control of the user and its data after calling it. In order to protect any
5265      * sensitive data that remains on this user, it is advised that the profile owner deletes it
5266      * instead of calling this method. See {@link #wipeData(int)}.
5267      */
5268     @Deprecated
clearProfileOwner(@onNull ComponentName admin)5269     public void clearProfileOwner(@NonNull ComponentName admin) {
5270         throwIfParentInstance("clearProfileOwner");
5271         if (mService != null) {
5272             try {
5273                 mService.clearProfileOwner(admin);
5274             } catch (RemoteException re) {
5275                 throw re.rethrowFromSystemServer();
5276             }
5277         }
5278     }
5279 
5280     /**
5281      * @hide
5282      * Checks whether the user was already setup.
5283      */
hasUserSetupCompleted()5284     public boolean hasUserSetupCompleted() {
5285         if (mService != null) {
5286             try {
5287                 return mService.hasUserSetupCompleted();
5288             } catch (RemoteException re) {
5289                 throw re.rethrowFromSystemServer();
5290             }
5291         }
5292         return true;
5293     }
5294 
5295     /**
5296      * @hide
5297      * Sets the given component as the profile owner of the given user profile. The package must
5298      * already be installed. There must not already be a profile owner for this user.
5299      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
5300      * this method.
5301      * Calling this after the setup phase of the specified user has completed is allowed only if:
5302      * - the caller is SYSTEM_UID.
5303      * - or the caller is the shell uid, and there are no accounts on the specified user.
5304      * @param admin the component name to be registered as profile owner.
5305      * @param ownerName the human readable name of the organisation associated with this DPM.
5306      * @param userHandle the userId to set the profile owner for.
5307      * @return whether the component was successfully registered as the profile owner.
5308      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
5309      * preconditions mentioned are not met.
5310      */
setProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName, int userHandle)5311     public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
5312             int userHandle) throws IllegalArgumentException {
5313         if (mService != null) {
5314             try {
5315                 if (ownerName == null) {
5316                     ownerName = "";
5317                 }
5318                 return mService.setProfileOwner(admin, ownerName, userHandle);
5319             } catch (RemoteException re) {
5320                 throw re.rethrowFromSystemServer();
5321             }
5322         }
5323         return false;
5324     }
5325 
5326     /**
5327      * Sets the device owner information to be shown on the lock screen.
5328      * <p>
5329      * If the device owner information is {@code null} or empty then the device owner info is
5330      * cleared and the user owner info is shown on the lock screen if it is set.
5331      * <p>
5332      * If the device owner information contains only whitespaces then the message on the lock screen
5333      * will be blank and the user will not be allowed to change it.
5334      * <p>
5335      * If the device owner information needs to be localized, it is the responsibility of the
5336      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
5337      * and set a new version of this string accordingly.
5338      *
5339      * @param admin The name of the admin component to check.
5340      * @param info Device owner information which will be displayed instead of the user owner info.
5341      * @throws SecurityException if {@code admin} is not a device owner.
5342      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)5343     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
5344         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
5345         if (mService != null) {
5346             try {
5347                 mService.setDeviceOwnerLockScreenInfo(admin, info);
5348             } catch (RemoteException re) {
5349                 throw re.rethrowFromSystemServer();
5350             }
5351         }
5352     }
5353 
5354     /**
5355      * @return The device owner information. If it is not set returns {@code null}.
5356      */
getDeviceOwnerLockScreenInfo()5357     public CharSequence getDeviceOwnerLockScreenInfo() {
5358         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
5359         if (mService != null) {
5360             try {
5361                 return mService.getDeviceOwnerLockScreenInfo();
5362             } catch (RemoteException re) {
5363                 throw re.rethrowFromSystemServer();
5364             }
5365         }
5366         return null;
5367     }
5368 
5369     /**
5370      * Called by device or profile owners to suspend packages for this user. This function can be
5371      * called by a device owner, profile owner, or by a delegate given the
5372      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
5373      * <p>
5374      * A suspended package will not be able to start activities. Its notifications will be hidden,
5375      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
5376      * device.
5377      * <p>
5378      * The package must already be installed. If the package is uninstalled while suspended the
5379      * package will no longer be suspended. The admin can block this by using
5380      * {@link #setUninstallBlocked}.
5381      *
5382      * @param admin The name of the admin component to check, or {@code null} if the caller is a
5383      *            package access delegate.
5384      * @param packageNames The package names to suspend or unsuspend.
5385      * @param suspended If set to {@code true} than the packages will be suspended, if set to
5386      *            {@code false} the packages will be unsuspended.
5387      * @return an array of package names for which the suspended status is not set as requested in
5388      *         this method.
5389      * @throws SecurityException if {@code admin} is not a device or profile owner.
5390      * @see #setDelegatedScopes
5391      * @see #DELEGATION_PACKAGE_ACCESS
5392      */
setPackagesSuspended(@onNull ComponentName admin, @NonNull String[] packageNames, boolean suspended)5393     public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
5394             @NonNull String[] packageNames, boolean suspended) {
5395         throwIfParentInstance("setPackagesSuspended");
5396         if (mService != null) {
5397             try {
5398                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
5399                         suspended);
5400             } catch (RemoteException re) {
5401                 throw re.rethrowFromSystemServer();
5402             }
5403         }
5404         return packageNames;
5405     }
5406 
5407     /**
5408      * Determine if a package is suspended. This function can be called by a device owner, profile
5409      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
5410      * {@link #setDelegatedScopes}.
5411      *
5412      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5413      *            {@code null} if the caller is a package access delegate.
5414      * @param packageName The name of the package to retrieve the suspended status of.
5415      * @return {@code true} if the package is suspended or {@code false} if the package is not
5416      *         suspended, could not be found or an error occurred.
5417      * @throws SecurityException if {@code admin} is not a device or profile owner.
5418      * @throws NameNotFoundException if the package could not be found.
5419      * @see #setDelegatedScopes
5420      * @see #DELEGATION_PACKAGE_ACCESS
5421      */
isPackageSuspended(@onNull ComponentName admin, String packageName)5422     public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
5423             throws NameNotFoundException {
5424         throwIfParentInstance("isPackageSuspended");
5425         if (mService != null) {
5426             try {
5427                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
5428             } catch (RemoteException e) {
5429                 throw e.rethrowFromSystemServer();
5430             } catch (IllegalArgumentException ex) {
5431                 throw new NameNotFoundException(packageName);
5432             }
5433         }
5434         return false;
5435     }
5436 
5437     /**
5438      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
5439      * be used. Only the profile owner can call this.
5440      *
5441      * @see #isProfileOwnerApp
5442      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5443      * @throws SecurityException if {@code admin} is not a profile owner.
5444      */
setProfileEnabled(@onNull ComponentName admin)5445     public void setProfileEnabled(@NonNull ComponentName admin) {
5446         throwIfParentInstance("setProfileEnabled");
5447         if (mService != null) {
5448             try {
5449                 mService.setProfileEnabled(admin);
5450             } catch (RemoteException e) {
5451                 throw e.rethrowFromSystemServer();
5452             }
5453         }
5454     }
5455 
5456     /**
5457      * Sets the name of the profile. In the device owner case it sets the name of the user which it
5458      * is called from. Only a profile owner or device owner can call this. If this is never called
5459      * by the profile or device owner, the name will be set to default values.
5460      *
5461      * @see #isProfileOwnerApp
5462      * @see #isDeviceOwnerApp
5463      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
5464      * @param profileName The name of the profile.
5465      * @throws SecurityException if {@code admin} is not a device or profile owner.
5466      */
setProfileName(@onNull ComponentName admin, String profileName)5467     public void setProfileName(@NonNull ComponentName admin, String profileName) {
5468         throwIfParentInstance("setProfileName");
5469         if (mService != null) {
5470             try {
5471                 mService.setProfileName(admin, profileName);
5472             } catch (RemoteException e) {
5473                 throw e.rethrowFromSystemServer();
5474             }
5475         }
5476     }
5477 
5478     /**
5479      * Used to determine if a particular package is registered as the profile owner for the
5480      * user. A profile owner is a special device admin that has additional privileges
5481      * within the profile.
5482      *
5483      * @param packageName The package name of the app to compare with the registered profile owner.
5484      * @return Whether or not the package is registered as the profile owner.
5485      */
isProfileOwnerApp(String packageName)5486     public boolean isProfileOwnerApp(String packageName) {
5487         throwIfParentInstance("isProfileOwnerApp");
5488         if (mService != null) {
5489             try {
5490                 ComponentName profileOwner = mService.getProfileOwner(myUserId());
5491                 return profileOwner != null
5492                         && profileOwner.getPackageName().equals(packageName);
5493             } catch (RemoteException re) {
5494                 throw re.rethrowFromSystemServer();
5495             }
5496         }
5497         return false;
5498     }
5499 
5500     /**
5501      * @hide
5502      * @return the packageName of the owner of the given user profile or {@code null} if no profile
5503      * owner has been set for that user.
5504      * @throws IllegalArgumentException if the userId is invalid.
5505      */
5506     @SystemApi
getProfileOwner()5507     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
5508         throwIfParentInstance("getProfileOwner");
5509         return getProfileOwnerAsUser(mContext.getUserId());
5510     }
5511 
5512     /**
5513      * @see #getProfileOwner()
5514      * @hide
5515      */
getProfileOwnerAsUser(final int userId)5516     public @Nullable ComponentName getProfileOwnerAsUser(final int userId)
5517             throws IllegalArgumentException {
5518         if (mService != null) {
5519             try {
5520                 return mService.getProfileOwner(userId);
5521             } catch (RemoteException re) {
5522                 throw re.rethrowFromSystemServer();
5523             }
5524         }
5525         return null;
5526     }
5527 
5528     /**
5529      * @hide
5530      * @return the human readable name of the organisation associated with this DPM or {@code null}
5531      *         if one is not set.
5532      * @throws IllegalArgumentException if the userId is invalid.
5533      */
getProfileOwnerName()5534     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
5535         if (mService != null) {
5536             try {
5537                 return mService.getProfileOwnerName(mContext.getUserId());
5538             } catch (RemoteException re) {
5539                 throw re.rethrowFromSystemServer();
5540             }
5541         }
5542         return null;
5543     }
5544 
5545     /**
5546      * @hide
5547      * @param userId The user for whom to fetch the profile owner name, if any.
5548      * @return the human readable name of the organisation associated with this profile owner or
5549      *         null if one is not set.
5550      * @throws IllegalArgumentException if the userId is invalid.
5551      */
5552     @SystemApi
5553     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getProfileOwnerNameAsUser(int userId)5554     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
5555         throwIfParentInstance("getProfileOwnerNameAsUser");
5556         if (mService != null) {
5557             try {
5558                 return mService.getProfileOwnerName(userId);
5559             } catch (RemoteException re) {
5560                 throw re.rethrowFromSystemServer();
5561             }
5562         }
5563         return null;
5564     }
5565 
5566     /**
5567      * Called by a profile owner or device owner to set a default activity that the system selects
5568      * to handle intents that match the given {@link IntentFilter}. This activity will remain the
5569      * default intent handler even if the set of potential event handlers for the intent filter
5570      * changes and if the intent preferences are reset.
5571      * <p>
5572      * Note that the caller should still declare the activity in the manifest, the API just sets
5573      * the activity to be the default one to handle the given intent filter.
5574      * <p>
5575      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
5576      * When the activity is (re)installed, it is automatically reset as default intent handler for
5577      * the filter.
5578      * <p>
5579      * The calling device admin must be a profile owner or device owner. If it is not, a security
5580      * exception will be thrown.
5581      *
5582      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5583      * @param filter The IntentFilter for which a default handler is added.
5584      * @param activity The Activity that is added as default intent handler.
5585      * @throws SecurityException if {@code admin} is not a device or profile owner.
5586      */
addPersistentPreferredActivity(@onNull ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)5587     public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
5588             @NonNull ComponentName activity) {
5589         throwIfParentInstance("addPersistentPreferredActivity");
5590         if (mService != null) {
5591             try {
5592                 mService.addPersistentPreferredActivity(admin, filter, activity);
5593             } catch (RemoteException e) {
5594                 throw e.rethrowFromSystemServer();
5595             }
5596         }
5597     }
5598 
5599     /**
5600      * Called by a profile owner or device owner to remove all persistent intent handler preferences
5601      * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
5602      * <p>
5603      * The calling device admin must be a profile owner. If it is not, a security exception will be
5604      * thrown.
5605      *
5606      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5607      * @param packageName The name of the package for which preferences are removed.
5608      * @throws SecurityException if {@code admin} is not a device or profile owner.
5609      */
clearPackagePersistentPreferredActivities(@onNull ComponentName admin, String packageName)5610     public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
5611             String packageName) {
5612         throwIfParentInstance("clearPackagePersistentPreferredActivities");
5613         if (mService != null) {
5614             try {
5615                 mService.clearPackagePersistentPreferredActivities(admin, packageName);
5616             } catch (RemoteException e) {
5617                 throw e.rethrowFromSystemServer();
5618             }
5619         }
5620     }
5621 
5622     /**
5623      * Called by a device owner to set the default SMS application.
5624      * <p>
5625      * The calling device admin must be a device owner. If it is not, a security exception will be
5626      * thrown.
5627      *
5628      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5629      * @param packageName The name of the package to set as the default SMS application.
5630      * @throws SecurityException if {@code admin} is not a device owner.
5631      *
5632      * @hide
5633      */
setDefaultSmsApplication(@onNull ComponentName admin, String packageName)5634     public void setDefaultSmsApplication(@NonNull ComponentName admin, String packageName) {
5635         throwIfParentInstance("setDefaultSmsApplication");
5636         if (mService != null) {
5637             try {
5638                 mService.setDefaultSmsApplication(admin, packageName);
5639             } catch (RemoteException e) {
5640                 throw e.rethrowFromSystemServer();
5641             }
5642         }
5643     }
5644 
5645     /**
5646      * Called by a profile owner or device owner to grant permission to a package to manage
5647      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
5648      * {@link #getApplicationRestrictions}.
5649      * <p>
5650      * This permission is persistent until it is later cleared by calling this method with a
5651      * {@code null} value or uninstalling the managing package.
5652      * <p>
5653      * The supplied application restriction managing package must be installed when calling this
5654      * API, otherwise an {@link NameNotFoundException} will be thrown.
5655      *
5656      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5657      * @param packageName The package name which will be given access to application restrictions
5658      *            APIs. If {@code null} is given the current package will be cleared.
5659      * @throws SecurityException if {@code admin} is not a device or profile owner.
5660      * @throws NameNotFoundException if {@code packageName} is not found
5661      *
5662      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5663      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5664      */
5665     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)5666     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
5667             @Nullable String packageName) throws NameNotFoundException {
5668         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
5669         if (mService != null) {
5670             try {
5671                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
5672                     throw new NameNotFoundException(packageName);
5673                 }
5674             } catch (RemoteException e) {
5675                 throw e.rethrowFromSystemServer();
5676             }
5677         }
5678     }
5679 
5680     /**
5681      * Called by a profile owner or device owner to retrieve the application restrictions managing
5682      * package for the current user, or {@code null} if none is set. If there are multiple
5683      * delegates this function will return one of them.
5684      *
5685      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5686      * @return The package name allowed to manage application restrictions on the current user, or
5687      *         {@code null} if none is set.
5688      * @throws SecurityException if {@code admin} is not a device or profile owner.
5689      *
5690      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5691      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5692      */
5693     @Deprecated
5694     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)5695     public String getApplicationRestrictionsManagingPackage(
5696             @NonNull ComponentName admin) {
5697         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
5698         if (mService != null) {
5699             try {
5700                 return mService.getApplicationRestrictionsManagingPackage(admin);
5701             } catch (RemoteException e) {
5702                 throw e.rethrowFromSystemServer();
5703             }
5704         }
5705         return null;
5706     }
5707 
5708     /**
5709      * Called by any application to find out whether it has been granted permission via
5710      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
5711      * for the calling user.
5712      *
5713      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
5714      * that method.
5715      *
5716      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
5717      * instead.
5718      */
5719     @Deprecated
isCallerApplicationRestrictionsManagingPackage()5720     public boolean isCallerApplicationRestrictionsManagingPackage() {
5721         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
5722         if (mService != null) {
5723             try {
5724                 return mService.isCallerApplicationRestrictionsManagingPackage(
5725                         mContext.getPackageName());
5726             } catch (RemoteException e) {
5727                 throw e.rethrowFromSystemServer();
5728             }
5729         }
5730         return false;
5731     }
5732 
5733     /**
5734      * Sets the application restrictions for a given target application running in the calling user.
5735      * <p>
5736      * The caller must be a profile or device owner on that user, or the package allowed to manage
5737      * application restrictions via {@link #setDelegatedScopes} with the
5738      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
5739      * <p>
5740      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
5741      * <ul>
5742      * <li>{@code boolean}
5743      * <li>{@code int}
5744      * <li>{@code String} or {@code String[]}
5745      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
5746      * </ul>
5747      * <p>
5748      * If the restrictions are not available yet, but may be applied in the near future, the caller
5749      * can notify the target application of that by adding
5750      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
5751      * <p>
5752      * The application restrictions are only made visible to the target application via
5753      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
5754      * owner, and the application restrictions managing package via
5755      * {@link #getApplicationRestrictions}.
5756      *
5757      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
5758      *
5759      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5760      *            {@code null} if called by the application restrictions managing package.
5761      * @param packageName The name of the package to update restricted settings for.
5762      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
5763      *            set of active restrictions.
5764      * @throws SecurityException if {@code admin} is not a device or profile owner.
5765      * @see #setDelegatedScopes
5766      * @see #DELEGATION_APP_RESTRICTIONS
5767      * @see UserManager#KEY_RESTRICTIONS_PENDING
5768      */
5769     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)5770     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
5771             Bundle settings) {
5772         throwIfParentInstance("setApplicationRestrictions");
5773         if (mService != null) {
5774             try {
5775                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
5776                         settings);
5777             } catch (RemoteException e) {
5778                 throw e.rethrowFromSystemServer();
5779             }
5780         }
5781     }
5782 
5783     /**
5784      * Sets a list of configuration features to enable for a trust agent component. This is meant to
5785      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
5786      * agents but those enabled by this function call. If flag
5787      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
5788      * <p>
5789      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
5790      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
5791      * configuration as set by this function call. In particular: if any admin sets
5792      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
5793      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
5794      * will receive the list of configurations from all admins who set
5795      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
5796      * behavior. The exact meaning of aggregation is trust-agent-specific.
5797      * <p>
5798      * The calling device admin must have requested
5799      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
5800      * if not, a security exception will be thrown.
5801      * <p>
5802      * This method can be called on the {@link DevicePolicyManager} instance returned by
5803      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
5804      * the parent profile.
5805      *
5806      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5807      * @param target Component name of the agent to be configured.
5808      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
5809      *        documentation of the specific trust agent to determine the interpretation of this
5810      *        bundle.
5811      * @throws SecurityException if {@code admin} is not an active administrator or does not use
5812      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
5813      */
setTrustAgentConfiguration(@onNull ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)5814     public void setTrustAgentConfiguration(@NonNull ComponentName admin,
5815             @NonNull ComponentName target, PersistableBundle configuration) {
5816         if (mService != null) {
5817             try {
5818                 mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
5819             } catch (RemoteException e) {
5820                 throw e.rethrowFromSystemServer();
5821             }
5822         }
5823     }
5824 
5825     /**
5826      * Gets configuration for the given trust agent based on aggregating all calls to
5827      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
5828      * all device admins.
5829      * <p>
5830      * This method can be called on the {@link DevicePolicyManager} instance returned by
5831      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
5832      * on the parent profile.
5833      *
5834      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
5835      * this function returns a list of configurations for all admins that declare
5836      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
5837      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
5838      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
5839      * for this {@param agent} or calls it with a null configuration, null is returned.
5840      * @param agent Which component to get enabled features for.
5841      * @return configuration for the given trust agent.
5842      */
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)5843     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5844             @Nullable ComponentName admin, @NonNull ComponentName agent) {
5845         return getTrustAgentConfiguration(admin, agent, myUserId());
5846     }
5847 
5848     /** @hide per-user version */
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)5849     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5850             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
5851         if (mService != null) {
5852             try {
5853                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
5854                         mParentInstance);
5855             } catch (RemoteException e) {
5856                 throw e.rethrowFromSystemServer();
5857             }
5858         }
5859         return new ArrayList<PersistableBundle>(); // empty list
5860     }
5861 
5862     /**
5863      * Called by a profile owner of a managed profile to set whether caller-Id information from the
5864      * managed profile will be shown in the parent profile, for incoming calls.
5865      * <p>
5866      * The calling device admin must be a profile owner. If it is not, a security exception will be
5867      * thrown.
5868      *
5869      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5870      * @param disabled If true caller-Id information in the managed profile is not displayed.
5871      * @throws SecurityException if {@code admin} is not a profile owner.
5872      */
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)5873     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
5874         throwIfParentInstance("setCrossProfileCallerIdDisabled");
5875         if (mService != null) {
5876             try {
5877                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
5878             } catch (RemoteException e) {
5879                 throw e.rethrowFromSystemServer();
5880             }
5881         }
5882     }
5883 
5884     /**
5885      * Called by a profile owner of a managed profile to determine whether or not caller-Id
5886      * information has been disabled.
5887      * <p>
5888      * The calling device admin must be a profile owner. If it is not, a security exception will be
5889      * thrown.
5890      *
5891      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5892      * @throws SecurityException if {@code admin} is not a profile owner.
5893      */
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)5894     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
5895         throwIfParentInstance("getCrossProfileCallerIdDisabled");
5896         if (mService != null) {
5897             try {
5898                 return mService.getCrossProfileCallerIdDisabled(admin);
5899             } catch (RemoteException e) {
5900                 throw e.rethrowFromSystemServer();
5901             }
5902         }
5903         return false;
5904     }
5905 
5906     /**
5907      * Determine whether or not caller-Id information has been disabled.
5908      *
5909      * @param userHandle The user for whom to check the caller-id permission
5910      * @hide
5911      */
getCrossProfileCallerIdDisabled(UserHandle userHandle)5912     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
5913         if (mService != null) {
5914             try {
5915                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
5916             } catch (RemoteException e) {
5917                 throw e.rethrowFromSystemServer();
5918             }
5919         }
5920         return false;
5921     }
5922 
5923     /**
5924      * Called by a profile owner of a managed profile to set whether contacts search from the
5925      * managed profile will be shown in the parent profile, for incoming calls.
5926      * <p>
5927      * The calling device admin must be a profile owner. If it is not, a security exception will be
5928      * thrown.
5929      *
5930      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5931      * @param disabled If true contacts search in the managed profile is not displayed.
5932      * @throws SecurityException if {@code admin} is not a profile owner.
5933      */
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)5934     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
5935             boolean disabled) {
5936         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
5937         if (mService != null) {
5938             try {
5939                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
5940             } catch (RemoteException e) {
5941                 throw e.rethrowFromSystemServer();
5942             }
5943         }
5944     }
5945 
5946     /**
5947      * Called by a profile owner of a managed profile to determine whether or not contacts search
5948      * has been disabled.
5949      * <p>
5950      * The calling device admin must be a profile owner. If it is not, a security exception will be
5951      * thrown.
5952      *
5953      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5954      * @throws SecurityException if {@code admin} is not a profile owner.
5955      */
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)5956     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
5957         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
5958         if (mService != null) {
5959             try {
5960                 return mService.getCrossProfileContactsSearchDisabled(admin);
5961             } catch (RemoteException e) {
5962                 throw e.rethrowFromSystemServer();
5963             }
5964         }
5965         return false;
5966     }
5967 
5968 
5969     /**
5970      * Determine whether or not contacts search has been disabled.
5971      *
5972      * @param userHandle The user for whom to check the contacts search permission
5973      * @hide
5974      */
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)5975     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
5976         if (mService != null) {
5977             try {
5978                 return mService
5979                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
5980             } catch (RemoteException e) {
5981                 throw e.rethrowFromSystemServer();
5982             }
5983         }
5984         return false;
5985     }
5986 
5987     /**
5988      * Start Quick Contact on the managed profile for the user, if the policy allows.
5989      *
5990      * @hide
5991      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)5992     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5993             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
5994         if (mService != null) {
5995             try {
5996                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
5997                         isContactIdIgnored, directoryId, originalIntent);
5998             } catch (RemoteException e) {
5999                 throw e.rethrowFromSystemServer();
6000             }
6001         }
6002     }
6003 
6004     /**
6005      * Start Quick Contact on the managed profile for the user, if the policy allows.
6006      * @hide
6007      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)6008     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
6009             Intent originalIntent) {
6010         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
6011                 originalIntent);
6012     }
6013 
6014     /**
6015      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
6016      * enterprise contacts.
6017      * <p>
6018      * The calling device admin must be a profile owner. If it is not, a security exception will be
6019      * thrown.
6020      * <p>
6021      * This API works on managed profile only.
6022      *
6023      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6024      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
6025      * @throws SecurityException if {@code admin} is not a profile owner.
6026      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)6027     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
6028         throwIfParentInstance("setBluetoothContactSharingDisabled");
6029         if (mService != null) {
6030             try {
6031                 mService.setBluetoothContactSharingDisabled(admin, disabled);
6032             } catch (RemoteException e) {
6033                 throw e.rethrowFromSystemServer();
6034             }
6035         }
6036     }
6037 
6038     /**
6039      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
6040      * cannot access enterprise contacts.
6041      * <p>
6042      * The calling device admin must be a profile owner. If it is not, a security exception will be
6043      * thrown.
6044      * <p>
6045      * This API works on managed profile only.
6046      *
6047      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6048      * @throws SecurityException if {@code admin} is not a profile owner.
6049      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)6050     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
6051         throwIfParentInstance("getBluetoothContactSharingDisabled");
6052         if (mService != null) {
6053             try {
6054                 return mService.getBluetoothContactSharingDisabled(admin);
6055             } catch (RemoteException e) {
6056                 throw e.rethrowFromSystemServer();
6057             }
6058         }
6059         return true;
6060     }
6061 
6062     /**
6063      * Determine whether or not Bluetooth devices cannot access contacts.
6064      * <p>
6065      * This API works on managed profile UserHandle only.
6066      *
6067      * @param userHandle The user for whom to check the caller-id permission
6068      * @hide
6069      */
getBluetoothContactSharingDisabled(UserHandle userHandle)6070     public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
6071         if (mService != null) {
6072             try {
6073                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
6074                         .getIdentifier());
6075             } catch (RemoteException e) {
6076                 throw e.rethrowFromSystemServer();
6077             }
6078         }
6079         return true;
6080     }
6081 
6082     /**
6083      * Called by the profile owner of a managed profile so that some intents sent in the managed
6084      * profile can also be resolved in the parent, or vice versa. Only activity intents are
6085      * supported.
6086      *
6087      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6088      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
6089      *            other profile
6090      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
6091      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
6092      * @throws SecurityException if {@code admin} is not a device or profile owner.
6093      */
addCrossProfileIntentFilter(@onNull ComponentName admin, IntentFilter filter, int flags)6094     public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
6095         throwIfParentInstance("addCrossProfileIntentFilter");
6096         if (mService != null) {
6097             try {
6098                 mService.addCrossProfileIntentFilter(admin, filter, flags);
6099             } catch (RemoteException e) {
6100                 throw e.rethrowFromSystemServer();
6101             }
6102         }
6103     }
6104 
6105     /**
6106      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
6107      * that go from the managed profile to the parent, or from the parent to the managed profile.
6108      * Only removes those that have been set by the profile owner.
6109      * <p>
6110      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
6111      * the profile is created, some of them ensure the proper functioning of the profile, while
6112      * others enable sharing of data from the parent to the managed profile for user convenience.
6113      * These default intent filters are not cleared when this API is called. If the default cross
6114      * profile data sharing is not desired, they can be disabled with
6115      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
6116      *
6117      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6118      * @throws SecurityException if {@code admin} is not a profile owner.
6119      */
clearCrossProfileIntentFilters(@onNull ComponentName admin)6120     public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
6121         throwIfParentInstance("clearCrossProfileIntentFilters");
6122         if (mService != null) {
6123             try {
6124                 mService.clearCrossProfileIntentFilters(admin);
6125             } catch (RemoteException e) {
6126                 throw e.rethrowFromSystemServer();
6127             }
6128         }
6129     }
6130 
6131     /**
6132      * Called by a profile or device owner to set the permitted
6133      * {@link android.accessibilityservice.AccessibilityService}. When set by
6134      * a device owner or profile owner the restriction applies to all profiles of the user the
6135      * device owner or profile owner is an admin for. By default, the user can use any accessibility
6136      * service. When zero or more packages have been added, accessibility services that are not in
6137      * the list and not part of the system can not be enabled by the user.
6138      * <p>
6139      * Calling with a null value for the list disables the restriction so that all services can be
6140      * used, calling with an empty list only allows the built-in system services. Any non-system
6141      * accessibility service that's currently enabled must be included in the list.
6142      * <p>
6143      * System accessibility services are always available to the user the list can't modify this.
6144      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6145      * @param packageNames List of accessibility service package names.
6146      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
6147      *         contain every enabled non-system accessibility service.
6148      * @throws SecurityException if {@code admin} is not a device or profile owner.
6149      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)6150     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
6151             List<String> packageNames) {
6152         throwIfParentInstance("setPermittedAccessibilityServices");
6153         if (mService != null) {
6154             try {
6155                 return mService.setPermittedAccessibilityServices(admin, packageNames);
6156             } catch (RemoteException e) {
6157                 throw e.rethrowFromSystemServer();
6158             }
6159         }
6160         return false;
6161     }
6162 
6163     /**
6164      * Returns the list of permitted accessibility services set by this device or profile owner.
6165      * <p>
6166      * An empty list means no accessibility services except system services are allowed. Null means
6167      * all accessibility services are allowed.
6168      *
6169      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6170      * @return List of accessiblity service package names.
6171      * @throws SecurityException if {@code admin} is not a device or profile owner.
6172      */
getPermittedAccessibilityServices(@onNull ComponentName admin)6173     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
6174         throwIfParentInstance("getPermittedAccessibilityServices");
6175         if (mService != null) {
6176             try {
6177                 return mService.getPermittedAccessibilityServices(admin);
6178             } catch (RemoteException e) {
6179                 throw e.rethrowFromSystemServer();
6180             }
6181         }
6182         return null;
6183     }
6184 
6185     /**
6186      * Called by the system to check if a specific accessibility service is disabled by admin.
6187      *
6188      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6189      * @param packageName Accessibility service package name that needs to be checked.
6190      * @param userHandle user id the admin is running as.
6191      * @return true if the accessibility service is permitted, otherwise false.
6192      *
6193      * @hide
6194      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)6195     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
6196             @NonNull String packageName, int userHandle) {
6197         if (mService != null) {
6198             try {
6199                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
6200                         userHandle);
6201             } catch (RemoteException e) {
6202                 throw e.rethrowFromSystemServer();
6203             }
6204         }
6205         return false;
6206     }
6207 
6208     /**
6209      * Returns the list of accessibility services permitted by the device or profiles
6210      * owners of this user.
6211      *
6212      * <p>Null means all accessibility services are allowed, if a non-null list is returned
6213      * it will contain the intersection of the permitted lists for any device or profile
6214      * owners that apply to this user. It will also include any system accessibility services.
6215      *
6216      * @param userId which user to check for.
6217      * @return List of accessiblity service package names.
6218      * @hide
6219      */
6220      @SystemApi
6221      @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedAccessibilityServices(int userId)6222      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
6223         throwIfParentInstance("getPermittedAccessibilityServices");
6224         if (mService != null) {
6225             try {
6226                 return mService.getPermittedAccessibilityServicesForUser(userId);
6227             } catch (RemoteException e) {
6228                 throw e.rethrowFromSystemServer();
6229             }
6230         }
6231         return null;
6232      }
6233 
6234     /**
6235      * Called by a profile or device owner to set the permitted input methods services. When set by
6236      * a device owner or profile owner the restriction applies to all profiles of the user the
6237      * device owner or profile owner is an admin for. By default, the user can use any input method.
6238      * When zero or more packages have been added, input method that are not in the list and not
6239      * part of the system can not be enabled by the user. This method will fail if it is called for
6240      * a admin that is not for the foreground user or a profile of the foreground user. Any
6241      * non-system input method service that's currently enabled must be included in the list.
6242      * <p>
6243      * Calling with a null value for the list disables the restriction so that all input methods can
6244      * be used, calling with an empty list disables all but the system's own input methods.
6245      * <p>
6246      * System input methods are always available to the user this method can't modify this.
6247      *
6248      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6249      * @param packageNames List of input method package names.
6250      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
6251      *        contain every enabled non-system input method service.
6252      * @throws SecurityException if {@code admin} is not a device or profile owner.
6253      */
setPermittedInputMethods( @onNull ComponentName admin, List<String> packageNames)6254     public boolean setPermittedInputMethods(
6255             @NonNull ComponentName admin, List<String> packageNames) {
6256         throwIfParentInstance("setPermittedInputMethods");
6257         if (mService != null) {
6258             try {
6259                 return mService.setPermittedInputMethods(admin, packageNames);
6260             } catch (RemoteException e) {
6261                 throw e.rethrowFromSystemServer();
6262             }
6263         }
6264         return false;
6265     }
6266 
6267 
6268     /**
6269      * Returns the list of permitted input methods set by this device or profile owner.
6270      * <p>
6271      * An empty list means no input methods except system input methods are allowed. Null means all
6272      * input methods are allowed.
6273      *
6274      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6275      * @return List of input method package names.
6276      * @throws SecurityException if {@code admin} is not a device or profile owner.
6277      */
getPermittedInputMethods(@onNull ComponentName admin)6278     public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
6279         throwIfParentInstance("getPermittedInputMethods");
6280         if (mService != null) {
6281             try {
6282                 return mService.getPermittedInputMethods(admin);
6283             } catch (RemoteException e) {
6284                 throw e.rethrowFromSystemServer();
6285             }
6286         }
6287         return null;
6288     }
6289 
6290     /**
6291      * Called by the system to check if a specific input method is disabled by admin.
6292      *
6293      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6294      * @param packageName Input method package name that needs to be checked.
6295      * @param userHandle user id the admin is running as.
6296      * @return true if the input method is permitted, otherwise false.
6297      *
6298      * @hide
6299      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)6300     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
6301             @NonNull String packageName, int userHandle) {
6302         if (mService != null) {
6303             try {
6304                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
6305             } catch (RemoteException e) {
6306                 throw e.rethrowFromSystemServer();
6307             }
6308         }
6309         return false;
6310     }
6311 
6312     /**
6313      * Returns the list of input methods permitted by the device or profiles
6314      * owners of the current user.  (*Not* calling user, due to a limitation in InputMethodManager.)
6315      *
6316      * <p>Null means all input methods are allowed, if a non-null list is returned
6317      * it will contain the intersection of the permitted lists for any device or profile
6318      * owners that apply to this user. It will also include any system input methods.
6319      *
6320      * @return List of input method package names.
6321      * @hide
6322      */
6323     @SystemApi
6324     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedInputMethodsForCurrentUser()6325     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
6326         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
6327         if (mService != null) {
6328             try {
6329                 return mService.getPermittedInputMethodsForCurrentUser();
6330             } catch (RemoteException e) {
6331                 throw e.rethrowFromSystemServer();
6332             }
6333         }
6334         return null;
6335     }
6336 
6337     /**
6338      * Called by a profile owner of a managed profile to set the packages that are allowed to use
6339      * a {@link android.service.notification.NotificationListenerService} in the primary user to
6340      * see notifications from the managed profile. By default all packages are permitted by this
6341      * policy. When zero or more packages have been added, notification listeners installed on the
6342      * primary user that are not in the list and are not part of the system won't receive events
6343      * for managed profile notifications.
6344      * <p>
6345      * Calling with a {@code null} value for the list disables the restriction so that all
6346      * notification listener services be used. Calling with an empty list disables all but the
6347      * system's own notification listeners. System notification listener services are always
6348      * available to the user.
6349      * <p>
6350      * If a device or profile owner want to stop notification listeners in their user from seeing
6351      * that user's notifications they should prevent that service from running instead (e.g. via
6352      * {@link #setApplicationHidden(ComponentName, String, boolean)})
6353      *
6354      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6355      * @param packageList List of package names to whitelist
6356      * @return true if setting the restriction succeeded. It will fail if called outside a managed
6357      * profile
6358      * @throws SecurityException if {@code admin} is not a profile owner.
6359      *
6360      * @see android.service.notification.NotificationListenerService
6361      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)6362     public boolean setPermittedCrossProfileNotificationListeners(
6363             @NonNull ComponentName admin, @Nullable List<String> packageList) {
6364         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
6365         if (mService != null) {
6366             try {
6367                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
6368             } catch (RemoteException e) {
6369                 throw e.rethrowFromSystemServer();
6370             }
6371         }
6372         return false;
6373     }
6374 
6375     /**
6376      * Returns the list of packages installed on the primary user that allowed to use a
6377      * {@link android.service.notification.NotificationListenerService} to receive
6378      * notifications from this managed profile, as set by the profile owner.
6379      * <p>
6380      * An empty list means no notification listener services except system ones are allowed.
6381      * A {@code null} return value indicates that all notification listeners are allowed.
6382      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)6383     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
6384             @NonNull ComponentName admin) {
6385         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
6386         if (mService != null) {
6387             try {
6388                 return mService.getPermittedCrossProfileNotificationListeners(admin);
6389             } catch (RemoteException e) {
6390                 throw e.rethrowFromSystemServer();
6391             }
6392         }
6393         return null;
6394     }
6395 
6396     /**
6397      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
6398      * receive events for notifications from the given user id. Can only be called by the system uid
6399      *
6400      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
6401      *
6402      * @hide
6403      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)6404     public boolean isNotificationListenerServicePermitted(
6405             @NonNull String packageName, @UserIdInt int userId) {
6406         if (mService != null) {
6407             try {
6408                 return mService.isNotificationListenerServicePermitted(packageName, userId);
6409             } catch (RemoteException e) {
6410                 throw e.rethrowFromSystemServer();
6411             }
6412         }
6413         return true;
6414     }
6415 
6416     /**
6417      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
6418      * function can be called by a device owner or by a delegate given the
6419      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
6420      * <p>
6421      * Please note that packages returned in this method are not automatically pre-cached.
6422      *
6423      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6424      *            {@code null} if the caller is a keep uninstalled packages delegate.
6425      * @return List of package names to keep cached.
6426      * @see #setDelegatedScopes
6427      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
6428      */
getKeepUninstalledPackages(@ullable ComponentName admin)6429     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
6430         throwIfParentInstance("getKeepUninstalledPackages");
6431         if (mService != null) {
6432             try {
6433                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
6434             } catch (RemoteException e) {
6435                 throw e.rethrowFromSystemServer();
6436             }
6437         }
6438         return null;
6439     }
6440 
6441     /**
6442      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
6443      * function can be called by a device owner or by a delegate given the
6444      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
6445      *
6446      * <p>Please note that setting this policy does not imply that specified apps will be
6447      * automatically pre-cached.</p>
6448      *
6449      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6450      *            {@code null} if the caller is a keep uninstalled packages delegate.
6451      * @param packageNames List of package names to keep cached.
6452      * @throws SecurityException if {@code admin} is not a device owner.
6453      * @see #setDelegatedScopes
6454      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
6455      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)6456     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
6457             @NonNull List<String> packageNames) {
6458         throwIfParentInstance("setKeepUninstalledPackages");
6459         if (mService != null) {
6460             try {
6461                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
6462             } catch (RemoteException e) {
6463                 throw e.rethrowFromSystemServer();
6464             }
6465         }
6466     }
6467 
6468     /**
6469      * Called by a device owner to create a user with the specified name. The UserHandle returned
6470      * by this method should not be persisted as user handles are recycled as users are removed and
6471      * created. If you need to persist an identifier for this user, use
6472      * {@link UserManager#getSerialNumberForUser}.
6473      *
6474      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6475      * @param name the user's name
6476      * @see UserHandle
6477      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6478      *         user could not be created.
6479      *
6480      * @deprecated From {@link android.os.Build.VERSION_CODES#M}
6481      * @removed From {@link android.os.Build.VERSION_CODES#N}
6482      */
6483     @Deprecated
createUser(@onNull ComponentName admin, String name)6484     public @Nullable UserHandle createUser(@NonNull ComponentName admin, String name) {
6485         return null;
6486     }
6487 
6488     /**
6489      * Called by a device owner to create a user with the specified name. The UserHandle returned
6490      * by this method should not be persisted as user handles are recycled as users are removed and
6491      * created. If you need to persist an identifier for this user, use
6492      * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
6493      * immediately.
6494      *
6495      * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
6496      * as registered as an active admin on the new user.  The profile owner package will be
6497      * installed on the new user if it already is installed on the device.
6498      *
6499      * <p>If the optionalInitializeData is not null, then the extras will be passed to the
6500      * profileOwnerComponent when onEnable is called.
6501      *
6502      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6503      * @param name the user's name
6504      * @param ownerName the human readable name of the organisation associated with this DPM.
6505      * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
6506      *      the user.
6507      * @param adminExtras Extras that will be passed to onEnable of the admin receiver
6508      *      on the new user.
6509      * @see UserHandle
6510      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6511      *         user could not be created.
6512      *
6513      * @deprecated From {@link android.os.Build.VERSION_CODES#M}
6514      * @removed From {@link android.os.Build.VERSION_CODES#N}
6515      */
6516     @Deprecated
createAndInitializeUser(@onNull ComponentName admin, String name, String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras)6517     public @Nullable UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
6518             String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
6519         return null;
6520     }
6521 
6522     /**
6523       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
6524       */
6525     public static final int SKIP_SETUP_WIZARD = 0x0001;
6526 
6527     /**
6528      * Flag used by {@link #createAndManageUser} to specify that the user should be created
6529      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
6530      * device.
6531      */
6532     public static final int MAKE_USER_EPHEMERAL = 0x0002;
6533 
6534     /**
6535      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
6536      * demo user.
6537      * @hide
6538      */
6539     public static final int MAKE_USER_DEMO = 0x0004;
6540 
6541     /**
6542      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
6543      * the disabling of system apps during provisioning.
6544      */
6545     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
6546 
6547     /**
6548      * @hide
6549      */
6550     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
6551             SKIP_SETUP_WIZARD,
6552             MAKE_USER_EPHEMERAL,
6553             MAKE_USER_DEMO,
6554             LEAVE_ALL_SYSTEM_APPS_ENABLED
6555     })
6556     @Retention(RetentionPolicy.SOURCE)
6557     public @interface CreateAndManageUserFlags {}
6558 
6559 
6560     /**
6561      * Called by a device owner to create a user with the specified name and a given component of
6562      * the calling package as profile owner. The UserHandle returned by this method should not be
6563      * persisted as user handles are recycled as users are removed and created. If you need to
6564      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
6565      * user will not be started in the background.
6566      * <p>
6567      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
6568      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
6569      * be registered as an active admin on the new user. The profile owner package will be installed
6570      * on the new user.
6571      * <p>
6572      * If the adminExtras are not null, they will be stored on the device until the user is started
6573      * for the first time. Then the extras will be passed to the admin when onEnable is called.
6574      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
6575      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
6576      * returning {@code null} on failure.
6577      *
6578      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6579      * @param name The user's name.
6580      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
6581      *            same package as admin, otherwise no user is created and an
6582      *            IllegalArgumentException is thrown.
6583      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
6584      *            user.
6585      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
6586      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
6587      * @see UserHandle
6588      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6589      *         user could not be created.
6590      * @throws SecurityException if {@code admin} is not a device owner.
6591      * @throws UserOperationException if the user could not be created and the calling app is
6592      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
6593      * {@link android.os.Build.VERSION_CODES#P}.
6594      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)6595     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
6596             @NonNull String name,
6597             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
6598             @CreateAndManageUserFlags int flags) {
6599         throwIfParentInstance("createAndManageUser");
6600         try {
6601             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
6602         } catch (ServiceSpecificException e) {
6603             throw new UserOperationException(e.getMessage(), e.errorCode);
6604         } catch (RemoteException re) {
6605             throw re.rethrowFromSystemServer();
6606         }
6607     }
6608 
6609     /**
6610      * Called by a device owner to remove a user/profile and all associated data. The primary user
6611      * can not be removed.
6612      *
6613      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6614      * @param userHandle the user to remove.
6615      * @return {@code true} if the user was removed, {@code false} otherwise.
6616      * @throws SecurityException if {@code admin} is not a device owner.
6617      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)6618     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6619         throwIfParentInstance("removeUser");
6620         try {
6621             return mService.removeUser(admin, userHandle);
6622         } catch (RemoteException re) {
6623             throw re.rethrowFromSystemServer();
6624         }
6625     }
6626 
6627     /**
6628      * Called by a device owner to switch the specified secondary user to the foreground.
6629      *
6630      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6631      * @param userHandle the user to switch to; null will switch to primary.
6632      * @return {@code true} if the switch was successful, {@code false} otherwise.
6633      * @throws SecurityException if {@code admin} is not a device owner.
6634      * @see Intent#ACTION_USER_FOREGROUND
6635      * @see #getSecondaryUsers(ComponentName)
6636      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)6637     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
6638         throwIfParentInstance("switchUser");
6639         try {
6640             return mService.switchUser(admin, userHandle);
6641         } catch (RemoteException re) {
6642             throw re.rethrowFromSystemServer();
6643         }
6644     }
6645 
6646     /**
6647      * Called by a device owner to start the specified secondary user in background.
6648      *
6649      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6650      * @param userHandle the user to be started in background.
6651      * @return one of the following result codes:
6652      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
6653      * {@link UserManager#USER_OPERATION_SUCCESS},
6654      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
6655      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
6656      * @throws SecurityException if {@code admin} is not a device owner.
6657      * @see #getSecondaryUsers(ComponentName)
6658      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)6659     public @UserOperationResult int startUserInBackground(
6660             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6661         throwIfParentInstance("startUserInBackground");
6662         try {
6663             return mService.startUserInBackground(admin, userHandle);
6664         } catch (RemoteException re) {
6665             throw re.rethrowFromSystemServer();
6666         }
6667     }
6668 
6669     /**
6670      * Called by a device owner to stop the specified secondary user.
6671      *
6672      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6673      * @param userHandle the user to be stopped.
6674      * @return one of the following result codes:
6675      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
6676      * {@link UserManager#USER_OPERATION_SUCCESS},
6677      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
6678      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
6679      * @throws SecurityException if {@code admin} is not a device owner.
6680      * @see #getSecondaryUsers(ComponentName)
6681      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)6682     public @UserOperationResult int stopUser(
6683             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6684         throwIfParentInstance("stopUser");
6685         try {
6686             return mService.stopUser(admin, userHandle);
6687         } catch (RemoteException re) {
6688             throw re.rethrowFromSystemServer();
6689         }
6690     }
6691 
6692     /**
6693      * Called by a profile owner of secondary user that is affiliated with the device to stop the
6694      * calling user and switch back to primary.
6695      *
6696      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6697      * @return one of the following result codes:
6698      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
6699      * {@link UserManager#USER_OPERATION_SUCCESS},
6700      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
6701      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
6702      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
6703      * @see #getSecondaryUsers(ComponentName)
6704      */
logoutUser(@onNull ComponentName admin)6705     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
6706         throwIfParentInstance("logoutUser");
6707         try {
6708             return mService.logoutUser(admin);
6709         } catch (RemoteException re) {
6710             throw re.rethrowFromSystemServer();
6711         }
6712     }
6713 
6714     /**
6715      * Called by a device owner to list all secondary users on the device. Managed profiles are not
6716      * considered as secondary users.
6717      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
6718      * and {@link #stopUser}.
6719      *
6720      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6721      * @return list of other {@link UserHandle}s on the device.
6722      * @throws SecurityException if {@code admin} is not a device owner.
6723      * @see #removeUser(ComponentName, UserHandle)
6724      * @see #switchUser(ComponentName, UserHandle)
6725      * @see #startUserInBackground(ComponentName, UserHandle)
6726      * @see #stopUser(ComponentName, UserHandle)
6727      */
getSecondaryUsers(@onNull ComponentName admin)6728     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
6729         throwIfParentInstance("getSecondaryUsers");
6730         try {
6731             return mService.getSecondaryUsers(admin);
6732         } catch (RemoteException re) {
6733             throw re.rethrowFromSystemServer();
6734         }
6735     }
6736 
6737     /**
6738      * Checks if the profile owner is running in an ephemeral user.
6739      *
6740      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6741      * @return whether the profile owner is running in an ephemeral user.
6742      */
isEphemeralUser(@onNull ComponentName admin)6743     public boolean isEphemeralUser(@NonNull ComponentName admin) {
6744         throwIfParentInstance("isEphemeralUser");
6745         try {
6746             return mService.isEphemeralUser(admin);
6747         } catch (RemoteException re) {
6748             throw re.rethrowFromSystemServer();
6749         }
6750     }
6751 
6752     /**
6753      * Retrieves the application restrictions for a given target application running in the calling
6754      * user.
6755      * <p>
6756      * The caller must be a profile or device owner on that user, or the package allowed to manage
6757      * application restrictions via {@link #setDelegatedScopes} with the
6758      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
6759      *
6760      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
6761      *
6762      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6763      *            {@code null} if called by the application restrictions managing package.
6764      * @param packageName The name of the package to fetch restricted settings of.
6765      * @return {@link Bundle} of settings corresponding to what was set last time
6766      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
6767      *         {@link Bundle} if no restrictions have been set.
6768      * @throws SecurityException if {@code admin} is not a device or profile owner.
6769      * @see #setDelegatedScopes
6770      * @see #DELEGATION_APP_RESTRICTIONS
6771      */
6772     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)6773     public @NonNull Bundle getApplicationRestrictions(
6774             @Nullable ComponentName admin, String packageName) {
6775         throwIfParentInstance("getApplicationRestrictions");
6776         if (mService != null) {
6777             try {
6778                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
6779                         packageName);
6780             } catch (RemoteException e) {
6781                 throw e.rethrowFromSystemServer();
6782             }
6783         }
6784         return null;
6785     }
6786 
6787     /**
6788      * Called by a profile or device owner to set a user restriction specified by the key.
6789      * <p>
6790      * The calling device admin must be a profile or device owner; if it is not, a security
6791      * exception will be thrown.
6792      *
6793      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6794      * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6795      *            for the list of keys.
6796      * @throws SecurityException if {@code admin} is not a device or profile owner.
6797      */
addUserRestriction(@onNull ComponentName admin, String key)6798     public void addUserRestriction(@NonNull ComponentName admin, String key) {
6799         throwIfParentInstance("addUserRestriction");
6800         if (mService != null) {
6801             try {
6802                 mService.setUserRestriction(admin, key, true);
6803             } catch (RemoteException e) {
6804                 throw e.rethrowFromSystemServer();
6805             }
6806         }
6807     }
6808 
6809     /**
6810      * Called by a profile or device owner to clear a user restriction specified by the key.
6811      * <p>
6812      * The calling device admin must be a profile or device owner; if it is not, a security
6813      * exception will be thrown.
6814      *
6815      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6816      * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6817      *            for the list of keys.
6818      * @throws SecurityException if {@code admin} is not a device or profile owner.
6819      */
clearUserRestriction(@onNull ComponentName admin, String key)6820     public void clearUserRestriction(@NonNull ComponentName admin, String key) {
6821         throwIfParentInstance("clearUserRestriction");
6822         if (mService != null) {
6823             try {
6824                 mService.setUserRestriction(admin, key, false);
6825             } catch (RemoteException e) {
6826                 throw e.rethrowFromSystemServer();
6827             }
6828         }
6829     }
6830 
6831     /**
6832      * Called by a profile or device owner to get user restrictions set with
6833      * {@link #addUserRestriction(ComponentName, String)}.
6834      * <p>
6835      * The target user may have more restrictions set by the system or other device owner / profile
6836      * owner. To get all the user restrictions currently set, use
6837      * {@link UserManager#getUserRestrictions()}.
6838      *
6839      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6840      * @throws SecurityException if {@code admin} is not a device or profile owner.
6841      */
getUserRestrictions(@onNull ComponentName admin)6842     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
6843         throwIfParentInstance("getUserRestrictions");
6844         Bundle ret = null;
6845         if (mService != null) {
6846             try {
6847                 ret = mService.getUserRestrictions(admin);
6848             } catch (RemoteException e) {
6849                 throw e.rethrowFromSystemServer();
6850             }
6851         }
6852         return ret == null ? new Bundle() : ret;
6853     }
6854 
6855     /**
6856      * Called by any app to display a support dialog when a feature was disabled by an admin.
6857      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
6858      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
6859      * was disabled by an admin, and include a link for more information. The default content of
6860      * the dialog can be changed by the restricting admin via
6861      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
6862      * set (i.e. the feature is available), then the return value will be {@code null}.
6863      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
6864      *            user restriction from {@link UserManager}, e.g.
6865      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
6866      *            {@link #POLICY_DISABLE_CAMERA}, {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
6867      * @return Intent An intent to be used to start the dialog-activity if the restriction is
6868      *            set by an admin, or null if the restriction does not exist or no admin set it.
6869      */
createAdminSupportIntent(@onNull String restriction)6870     public Intent createAdminSupportIntent(@NonNull String restriction) {
6871         throwIfParentInstance("createAdminSupportIntent");
6872         if (mService != null) {
6873             try {
6874                 return mService.createAdminSupportIntent(restriction);
6875             } catch (RemoteException e) {
6876                 throw e.rethrowFromSystemServer();
6877             }
6878         }
6879         return null;
6880     }
6881 
6882     /**
6883      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
6884      * actual package file remain. This function can be called by a device owner, profile owner, or
6885      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6886      * {@link #setDelegatedScopes}.
6887      *
6888      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6889      *            {@code null} if the caller is a package access delegate.
6890      * @param packageName The name of the package to hide or unhide.
6891      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
6892      *            unhidden.
6893      * @return boolean Whether the hidden setting of the package was successfully updated.
6894      * @throws SecurityException if {@code admin} is not a device or profile owner.
6895      * @see #setDelegatedScopes
6896      * @see #DELEGATION_PACKAGE_ACCESS
6897      */
setApplicationHidden(@onNull ComponentName admin, String packageName, boolean hidden)6898     public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
6899             boolean hidden) {
6900         throwIfParentInstance("setApplicationHidden");
6901         if (mService != null) {
6902             try {
6903                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
6904                         hidden);
6905             } catch (RemoteException e) {
6906                 throw e.rethrowFromSystemServer();
6907             }
6908         }
6909         return false;
6910     }
6911 
6912     /**
6913      * Determine if a package is hidden. This function can be called by a device owner, profile
6914      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6915      * {@link #setDelegatedScopes}.
6916      *
6917      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6918      *            {@code null} if the caller is a package access delegate.
6919      * @param packageName The name of the package to retrieve the hidden status of.
6920      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
6921      * @throws SecurityException if {@code admin} is not a device or profile owner.
6922      * @see #setDelegatedScopes
6923      * @see #DELEGATION_PACKAGE_ACCESS
6924      */
isApplicationHidden(@onNull ComponentName admin, String packageName)6925     public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
6926         throwIfParentInstance("isApplicationHidden");
6927         if (mService != null) {
6928             try {
6929                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName);
6930             } catch (RemoteException e) {
6931                 throw e.rethrowFromSystemServer();
6932             }
6933         }
6934         return false;
6935     }
6936 
6937     /**
6938      * Re-enable a system app that was disabled by default when the user was initialized. This
6939      * function can be called by a device owner, profile owner, or by a delegate given the
6940      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6941      *
6942      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6943      *            {@code null} if the caller is an enable system app delegate.
6944      * @param packageName The package to be re-enabled in the calling profile.
6945      * @throws SecurityException if {@code admin} is not a device or profile owner.
6946      * @see #setDelegatedScopes
6947      * @see #DELEGATION_PACKAGE_ACCESS
6948      */
enableSystemApp(@onNull ComponentName admin, String packageName)6949     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
6950         throwIfParentInstance("enableSystemApp");
6951         if (mService != null) {
6952             try {
6953                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
6954             } catch (RemoteException e) {
6955                 throw e.rethrowFromSystemServer();
6956             }
6957         }
6958     }
6959 
6960     /**
6961      * Re-enable system apps by intent that were disabled by default when the user was initialized.
6962      * This function can be called by a device owner, profile owner, or by a delegate given the
6963      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6964      *
6965      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6966      *            {@code null} if the caller is an enable system app delegate.
6967      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
6968      *            intent will be re-enabled in the calling profile.
6969      * @return int The number of activities that matched the intent and were installed.
6970      * @throws SecurityException if {@code admin} is not a device or profile owner.
6971      * @see #setDelegatedScopes
6972      * @see #DELEGATION_PACKAGE_ACCESS
6973      */
enableSystemApp(@onNull ComponentName admin, Intent intent)6974     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
6975         throwIfParentInstance("enableSystemApp");
6976         if (mService != null) {
6977             try {
6978                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
6979             } catch (RemoteException e) {
6980                 throw e.rethrowFromSystemServer();
6981             }
6982         }
6983         return 0;
6984     }
6985 
6986     /**
6987      * Install an existing package that has been installed in another user, or has been kept after
6988      * removal via {@link #setKeepUninstalledPackages}.
6989      * This function can be called by a device owner, profile owner or a delegate given
6990      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
6991      * When called in a secondary user or managed profile, the user/profile must be affiliated with
6992      * the device. See {@link #isAffiliatedUser}.
6993      *
6994      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6995      * @param packageName The package to be installed in the calling profile.
6996      * @return {@code true} if the app is installed; {@code false} otherwise.
6997      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
6998      * an affiliated user or profile.
6999      * @see #setKeepUninstalledPackages
7000      * @see #setDelegatedScopes
7001      * @see #isAffiliatedUser
7002      * @see #DELEGATION_PACKAGE_ACCESS
7003      */
installExistingPackage(@onNull ComponentName admin, String packageName)7004     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
7005         throwIfParentInstance("installExistingPackage");
7006         if (mService != null) {
7007             try {
7008                 return mService.installExistingPackage(admin, mContext.getPackageName(),
7009                         packageName);
7010             } catch (RemoteException e) {
7011                 throw e.rethrowFromSystemServer();
7012             }
7013         }
7014         return false;
7015     }
7016 
7017     /**
7018      * Called by a device owner or profile owner to disable account management for a specific type
7019      * of account.
7020      * <p>
7021      * The calling device admin must be a device owner or profile owner. If it is not, a security
7022      * exception will be thrown.
7023      * <p>
7024      * When account management is disabled for an account type, adding or removing an account of
7025      * that type will not be possible.
7026      * <p>
7027      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
7028      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
7029      * management for a specific type is disabled.
7030      *
7031      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7032      * @param accountType For which account management is disabled or enabled.
7033      * @param disabled The boolean indicating that account management will be disabled (true) or
7034      *            enabled (false).
7035      * @throws SecurityException if {@code admin} is not a device or profile owner.
7036      */
setAccountManagementDisabled(@onNull ComponentName admin, String accountType, boolean disabled)7037     public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
7038             boolean disabled) {
7039         throwIfParentInstance("setAccountManagementDisabled");
7040         if (mService != null) {
7041             try {
7042                 mService.setAccountManagementDisabled(admin, accountType, disabled);
7043             } catch (RemoteException e) {
7044                 throw e.rethrowFromSystemServer();
7045             }
7046         }
7047     }
7048 
7049     /**
7050      * Gets the array of accounts for which account management is disabled by the profile owner.
7051      *
7052      * <p> Account management can be disabled/enabled by calling
7053      * {@link #setAccountManagementDisabled}.
7054      *
7055      * @return a list of account types for which account management has been disabled.
7056      *
7057      * @see #setAccountManagementDisabled
7058      */
getAccountTypesWithManagementDisabled()7059     public @Nullable String[] getAccountTypesWithManagementDisabled() {
7060         throwIfParentInstance("getAccountTypesWithManagementDisabled");
7061         return getAccountTypesWithManagementDisabledAsUser(myUserId());
7062     }
7063 
7064     /**
7065      * @see #getAccountTypesWithManagementDisabled()
7066      * @hide
7067      */
getAccountTypesWithManagementDisabledAsUser(int userId)7068     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7069         if (mService != null) {
7070             try {
7071                 return mService.getAccountTypesWithManagementDisabledAsUser(userId);
7072             } catch (RemoteException e) {
7073                 throw e.rethrowFromSystemServer();
7074             }
7075         }
7076 
7077         return null;
7078     }
7079 
7080     /**
7081      * Sets which packages may enter lock task mode.
7082      * <p>
7083      * Any packages that share uid with an allowed package will also be allowed to activate lock
7084      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
7085      * package list results in locked tasks belonging to those packages to be finished.
7086      * <p>
7087      * This function can only be called by the device owner, a profile owner of an affiliated user
7088      * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
7089      * Any package set via this method will be cleared if the user becomes unaffiliated.
7090      *
7091      * @param packages The list of packages allowed to enter lock task mode
7092      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7093      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7094      * affiliated user or profile, or the profile owner when no device owner is set.
7095      * @see #isAffiliatedUser
7096      * @see Activity#startLockTask()
7097      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
7098      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
7099      * @see UserManager#DISALLOW_CREATE_WINDOWS
7100      */
setLockTaskPackages(@onNull ComponentName admin, @NonNull String[] packages)7101     public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
7102             throws SecurityException {
7103         throwIfParentInstance("setLockTaskPackages");
7104         if (mService != null) {
7105             try {
7106                 mService.setLockTaskPackages(admin, packages);
7107             } catch (RemoteException e) {
7108                 throw e.rethrowFromSystemServer();
7109             }
7110         }
7111     }
7112 
7113     /**
7114      * Returns the list of packages allowed to start the lock task mode.
7115      *
7116      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7117      * affiliated user or profile, or the profile owner when no device owner is set.
7118      * @see #isAffiliatedUser
7119      * @see #setLockTaskPackages
7120      */
getLockTaskPackages(@onNull ComponentName admin)7121     public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
7122         throwIfParentInstance("getLockTaskPackages");
7123         if (mService != null) {
7124             try {
7125                 return mService.getLockTaskPackages(admin);
7126             } catch (RemoteException e) {
7127                 throw e.rethrowFromSystemServer();
7128             }
7129         }
7130         return new String[0];
7131     }
7132 
7133     /**
7134      * This function lets the caller know whether the given component is allowed to start the
7135      * lock task mode.
7136      * @param pkg The package to check
7137      */
isLockTaskPermitted(String pkg)7138     public boolean isLockTaskPermitted(String pkg) {
7139         throwIfParentInstance("isLockTaskPermitted");
7140         if (mService != null) {
7141             try {
7142                 return mService.isLockTaskPermitted(pkg);
7143             } catch (RemoteException e) {
7144                 throw e.rethrowFromSystemServer();
7145             }
7146         }
7147         return false;
7148     }
7149 
7150     /**
7151      * Sets which system features are enabled when the device runs in lock task mode. This method
7152      * doesn't affect the features when lock task mode is inactive. Any system features not included
7153      * in {@code flags} are implicitly disabled when calling this method. By default, only
7154      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled—all the other features are disabled. To
7155      * disable the global actions dialog, call this method omitting
7156      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
7157      *
7158      * <p>This method can only be called by the device owner, a profile owner of an affiliated
7159      * user or profile, or the profile owner when no device owner is set. See
7160      * {@link #isAffiliatedUser}.
7161      * Any features set using this method are cleared if the user becomes unaffiliated.
7162      *
7163      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7164      * @param flags The system features enabled during lock task mode.
7165      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7166      * affiliated user or profile, or the profile owner when no device owner is set.
7167      * @see #isAffiliatedUser
7168      **/
setLockTaskFeatures(@onNull ComponentName admin, @LockTaskFeature int flags)7169     public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
7170         throwIfParentInstance("setLockTaskFeatures");
7171         if (mService != null) {
7172             try {
7173                 mService.setLockTaskFeatures(admin, flags);
7174             } catch (RemoteException e) {
7175                 throw e.rethrowFromSystemServer();
7176             }
7177         }
7178     }
7179 
7180     /**
7181      * Gets which system features are enabled for LockTask mode.
7182      *
7183      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7184      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
7185      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7186      * affiliated user or profile, or the profile owner when no device owner is set.
7187      * @see #isAffiliatedUser
7188      * @see #setLockTaskFeatures
7189      */
getLockTaskFeatures(@onNull ComponentName admin)7190     public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
7191         throwIfParentInstance("getLockTaskFeatures");
7192         if (mService != null) {
7193             try {
7194                 return mService.getLockTaskFeatures(admin);
7195             } catch (RemoteException e) {
7196                 throw e.rethrowFromSystemServer();
7197             }
7198         }
7199         return 0;
7200     }
7201 
7202     /**
7203      * Called by device owner to update {@link android.provider.Settings.Global} settings.
7204      * Validation that the value of the setting is in the correct form for the setting type should
7205      * be performed by the caller.
7206      * <p>
7207      * The settings that can be updated with this method are:
7208      * <ul>
7209      * <li>{@link android.provider.Settings.Global#ADB_ENABLED}</li>
7210      * <li>{@link android.provider.Settings.Global#AUTO_TIME}</li>
7211      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE}</li>
7212      * <li>{@link android.provider.Settings.Global#DATA_ROAMING}</li>
7213      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
7214      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}</li>
7215      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
7216      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
7217      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
7218      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
7219      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
7220      * </ul>
7221      * <p>
7222      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
7223      * <ul>
7224      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
7225      * {@link android.bluetooth.BluetoothAdapter#enable()} and
7226      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
7227      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
7228      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
7229      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
7230      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
7231      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
7232      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
7233      * </ul>
7234      *
7235      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7236      * @param setting The name of the setting to update.
7237      * @param value The value to update the setting to.
7238      * @throws SecurityException if {@code admin} is not a device owner.
7239      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)7240     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
7241         throwIfParentInstance("setGlobalSetting");
7242         if (mService != null) {
7243             try {
7244                 mService.setGlobalSetting(admin, setting, value);
7245             } catch (RemoteException e) {
7246                 throw e.rethrowFromSystemServer();
7247             }
7248         }
7249     }
7250 
7251     /** @hide */
7252     @StringDef({
7253             Settings.System.SCREEN_BRIGHTNESS_MODE,
7254             Settings.System.SCREEN_BRIGHTNESS,
7255             Settings.System.SCREEN_OFF_TIMEOUT
7256     })
7257     @Retention(RetentionPolicy.SOURCE)
7258     public @interface SystemSettingsWhitelist {}
7259 
7260     /**
7261      * Called by a device or profile owner to update {@link android.provider.Settings.System}
7262      * settings. Validation that the value of the setting is in the correct form for the setting
7263      * type should be performed by the caller.
7264      * <p>
7265      * The settings that can be updated by a device owner or profile owner of secondary user with
7266      * this method are:
7267      * <ul>
7268      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
7269      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
7270      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
7271      * </ul>
7272      * <p>
7273      *
7274      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
7275      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7276      * @param setting The name of the setting to update.
7277      * @param value The value to update the setting to.
7278      * @throws SecurityException if {@code admin} is not a device or profile owner.
7279      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)7280     public void setSystemSetting(@NonNull ComponentName admin,
7281             @NonNull @SystemSettingsWhitelist String setting, String value) {
7282         throwIfParentInstance("setSystemSetting");
7283         if (mService != null) {
7284             try {
7285                 mService.setSystemSetting(admin, setting, value);
7286             } catch (RemoteException e) {
7287                 throw e.rethrowFromSystemServer();
7288             }
7289         }
7290     }
7291 
7292     /**
7293      * Called by device owner to set the system wall clock time. This only takes effect if called
7294      * when {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false} will be
7295      * returned.
7296      *
7297      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
7298      * @param millis time in milliseconds since the Epoch
7299      * @return {@code true} if set time succeeded, {@code false} otherwise.
7300      * @throws SecurityException if {@code admin} is not a device owner.
7301      */
setTime(@onNull ComponentName admin, long millis)7302     public boolean setTime(@NonNull ComponentName admin, long millis) {
7303         throwIfParentInstance("setTime");
7304         if (mService != null) {
7305             try {
7306                 return mService.setTime(admin, millis);
7307             } catch (RemoteException e) {
7308                 throw e.rethrowFromSystemServer();
7309             }
7310         }
7311         return false;
7312     }
7313 
7314     /**
7315      * Called by device owner to set the system's persistent default time zone. This only takes
7316      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE} is 0, otherwise
7317      * {@code false} will be returned.
7318      *
7319      * @see android.app.AlarmManager#setTimeZone(String)
7320      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
7321      * @param timeZone one of the Olson ids from the list returned by
7322      *     {@link java.util.TimeZone#getAvailableIDs}
7323      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
7324      * @throws SecurityException if {@code admin} is not a device owner.
7325      */
setTimeZone(@onNull ComponentName admin, String timeZone)7326     public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
7327         throwIfParentInstance("setTimeZone");
7328         if (mService != null) {
7329             try {
7330                 return mService.setTimeZone(admin, timeZone);
7331             } catch (RemoteException e) {
7332                 throw e.rethrowFromSystemServer();
7333             }
7334         }
7335         return false;
7336     }
7337 
7338     /**
7339      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
7340      * settings. Validation that the value of the setting is in the correct form for the setting
7341      * type should be performed by the caller.
7342      * <p>
7343      * The settings that can be updated by a profile or device owner with this method are:
7344      * <ul>
7345      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
7346      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
7347      * </ul>
7348      * <p>
7349      * A device owner can additionally update the following settings:
7350      * <ul>
7351      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}</li>
7352      * </ul>
7353      *
7354      * <strong>Note: Starting from Android O, apps should no longer call this method with the
7355      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
7356      * deprecated. Instead, device owners or profile owners should use the restriction
7357      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
7358      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
7359      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
7360      * an {@link UnsupportedOperationException} is thrown.
7361      * </strong>
7362      *
7363      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7364      * @param setting The name of the setting to update.
7365      * @param value The value to update the setting to.
7366      * @throws SecurityException if {@code admin} is not a device or profile owner.
7367      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)7368     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
7369         throwIfParentInstance("setSecureSetting");
7370         if (mService != null) {
7371             try {
7372                 mService.setSecureSetting(admin, setting, value);
7373             } catch (RemoteException e) {
7374                 throw e.rethrowFromSystemServer();
7375             }
7376         }
7377     }
7378 
7379     /**
7380      * Designates a specific service component as the provider for making permission requests of a
7381      * local or remote administrator of the user.
7382      * <p/>
7383      * Only a profile owner can designate the restrictions provider.
7384      *
7385      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7386      * @param provider The component name of the service that implements
7387      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
7388      *            provider previously assigned.
7389      * @throws SecurityException if {@code admin} is not a device or profile owner.
7390      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)7391     public void setRestrictionsProvider(@NonNull ComponentName admin,
7392             @Nullable ComponentName provider) {
7393         throwIfParentInstance("setRestrictionsProvider");
7394         if (mService != null) {
7395             try {
7396                 mService.setRestrictionsProvider(admin, provider);
7397             } catch (RemoteException re) {
7398                 throw re.rethrowFromSystemServer();
7399             }
7400         }
7401     }
7402 
7403     /**
7404      * Called by profile or device owners to set the master volume mute on or off.
7405      * This has no effect when set on a managed profile.
7406      *
7407      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7408      * @param on {@code true} to mute master volume, {@code false} to turn mute off.
7409      * @throws SecurityException if {@code admin} is not a device or profile owner.
7410      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)7411     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
7412         throwIfParentInstance("setMasterVolumeMuted");
7413         if (mService != null) {
7414             try {
7415                 mService.setMasterVolumeMuted(admin, on);
7416             } catch (RemoteException re) {
7417                 throw re.rethrowFromSystemServer();
7418             }
7419         }
7420     }
7421 
7422     /**
7423      * Called by profile or device owners to check whether the master volume mute is on or off.
7424      *
7425      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7426      * @return {@code true} if master volume is muted, {@code false} if it's not.
7427      * @throws SecurityException if {@code admin} is not a device or profile owner.
7428      */
isMasterVolumeMuted(@onNull ComponentName admin)7429     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
7430         throwIfParentInstance("isMasterVolumeMuted");
7431         if (mService != null) {
7432             try {
7433                 return mService.isMasterVolumeMuted(admin);
7434             } catch (RemoteException re) {
7435                 throw re.rethrowFromSystemServer();
7436             }
7437         }
7438         return false;
7439     }
7440 
7441     /**
7442      * Change whether a user can uninstall a package. This function can be called by a device owner,
7443      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
7444      * {@link #setDelegatedScopes}.
7445      *
7446      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7447      *             {@code null} if the caller is a block uninstall delegate.
7448      * @param packageName package to change.
7449      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
7450      * @throws SecurityException if {@code admin} is not a device or profile owner.
7451      * @see #setDelegatedScopes
7452      * @see #DELEGATION_BLOCK_UNINSTALL
7453      */
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)7454     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
7455             boolean uninstallBlocked) {
7456         throwIfParentInstance("setUninstallBlocked");
7457         if (mService != null) {
7458             try {
7459                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
7460                     uninstallBlocked);
7461             } catch (RemoteException re) {
7462                 throw re.rethrowFromSystemServer();
7463             }
7464         }
7465     }
7466 
7467     /**
7468      * Check whether the user has been blocked by device policy from uninstalling a package.
7469      * Requires the caller to be the profile owner if checking a specific admin's policy.
7470      * <p>
7471      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
7472      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
7473      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
7474      * will cause a NullPointerException to be raised.
7475      *
7476      * @param admin The name of the admin component whose blocking policy will be checked, or
7477      *            {@code null} to check whether any admin has blocked the uninstallation.
7478      * @param packageName package to check.
7479      * @return true if uninstallation is blocked.
7480      * @throws SecurityException if {@code admin} is not a device or profile owner.
7481      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)7482     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
7483         throwIfParentInstance("isUninstallBlocked");
7484         if (mService != null) {
7485             try {
7486                 return mService.isUninstallBlocked(admin, packageName);
7487             } catch (RemoteException re) {
7488                 throw re.rethrowFromSystemServer();
7489             }
7490         }
7491         return false;
7492     }
7493 
7494     /**
7495      * Called by the profile owner of a managed profile to enable widget providers from a given
7496      * package to be available in the parent profile. As a result the user will be able to add
7497      * widgets from the white-listed package running under the profile to a widget host which runs
7498      * under the parent profile, for example the home screen. Note that a package may have zero or
7499      * more provider components, where each component provides a different widget type.
7500      * <p>
7501      * <strong>Note:</strong> By default no widget provider package is white-listed.
7502      *
7503      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7504      * @param packageName The package from which widget providers are white-listed.
7505      * @return Whether the package was added.
7506      * @throws SecurityException if {@code admin} is not a profile owner.
7507      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
7508      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
7509      */
addCrossProfileWidgetProvider(@onNull ComponentName admin, String packageName)7510     public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
7511         throwIfParentInstance("addCrossProfileWidgetProvider");
7512         if (mService != null) {
7513             try {
7514                 return mService.addCrossProfileWidgetProvider(admin, packageName);
7515             } catch (RemoteException re) {
7516                 throw re.rethrowFromSystemServer();
7517             }
7518         }
7519         return false;
7520     }
7521 
7522     /**
7523      * Called by the profile owner of a managed profile to disable widget providers from a given
7524      * package to be available in the parent profile. For this method to take effect the package
7525      * should have been added via
7526      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
7527      * <p>
7528      * <strong>Note:</strong> By default no widget provider package is white-listed.
7529      *
7530      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7531      * @param packageName The package from which widget providers are no longer white-listed.
7532      * @return Whether the package was removed.
7533      * @throws SecurityException if {@code admin} is not a profile owner.
7534      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
7535      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
7536      */
removeCrossProfileWidgetProvider( @onNull ComponentName admin, String packageName)7537     public boolean removeCrossProfileWidgetProvider(
7538             @NonNull ComponentName admin, String packageName) {
7539         throwIfParentInstance("removeCrossProfileWidgetProvider");
7540         if (mService != null) {
7541             try {
7542                 return mService.removeCrossProfileWidgetProvider(admin, packageName);
7543             } catch (RemoteException re) {
7544                 throw re.rethrowFromSystemServer();
7545             }
7546         }
7547         return false;
7548     }
7549 
7550     /**
7551      * Called by the profile owner of a managed profile to query providers from which packages are
7552      * available in the parent profile.
7553      *
7554      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7555      * @return The white-listed package list.
7556      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
7557      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
7558      * @throws SecurityException if {@code admin} is not a profile owner.
7559      */
getCrossProfileWidgetProviders(@onNull ComponentName admin)7560     public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
7561         throwIfParentInstance("getCrossProfileWidgetProviders");
7562         if (mService != null) {
7563             try {
7564                 List<String> providers = mService.getCrossProfileWidgetProviders(admin);
7565                 if (providers != null) {
7566                     return providers;
7567                 }
7568             } catch (RemoteException re) {
7569                 throw re.rethrowFromSystemServer();
7570             }
7571         }
7572         return Collections.emptyList();
7573     }
7574 
7575     /**
7576      * Called by profile or device owners to set the user's photo.
7577      *
7578      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7579      * @param icon the bitmap to set as the photo.
7580      * @throws SecurityException if {@code admin} is not a device or profile owner.
7581      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)7582     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
7583         throwIfParentInstance("setUserIcon");
7584         try {
7585             mService.setUserIcon(admin, icon);
7586         } catch (RemoteException re) {
7587             throw re.rethrowFromSystemServer();
7588         }
7589     }
7590 
7591     /**
7592      * Called by device owners to set a local system update policy. When a new policy is set,
7593      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
7594      * <p>
7595      * If the supplied system update policy has freeze periods set but the freeze periods do not
7596      * meet 90-day maximum length or 60-day minimum separation requirement set out in
7597      * {@link SystemUpdatePolicy#setFreezePeriods},
7598      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
7599      * keeps a record of freeze periods the device experienced previously, and combines them with
7600      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
7601      * separation constraints. As a result, freeze periods that passed validation during
7602      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
7603      * the freeze period history. If this is causing issues during development,
7604      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
7605      *
7606      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
7607      *            components in the device owner package can set system update policies and the most
7608      *            recent policy takes effect.
7609      * @param policy the new policy, or {@code null} to clear the current policy.
7610      * @throws SecurityException if {@code admin} is not a device owner.
7611      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
7612      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
7613      *             meet the requirement.
7614      * @see SystemUpdatePolicy
7615      * @see SystemUpdatePolicy#setFreezePeriods(List)
7616      */
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)7617     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
7618         throwIfParentInstance("setSystemUpdatePolicy");
7619         if (mService != null) {
7620             try {
7621                 mService.setSystemUpdatePolicy(admin, policy);
7622             } catch (RemoteException re) {
7623                 throw re.rethrowFromSystemServer();
7624             }
7625         }
7626     }
7627 
7628     /**
7629      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
7630      *
7631      * @return The current policy object, or {@code null} if no policy is set.
7632      */
getSystemUpdatePolicy()7633     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
7634         throwIfParentInstance("getSystemUpdatePolicy");
7635         if (mService != null) {
7636             try {
7637                 return mService.getSystemUpdatePolicy();
7638             } catch (RemoteException re) {
7639                 throw re.rethrowFromSystemServer();
7640             }
7641         }
7642         return null;
7643     }
7644 
7645     /**
7646      * Reset record of previous system update freeze period the device went through.
7647      * Only callable by ADB.
7648      * @hide
7649      */
clearSystemUpdatePolicyFreezePeriodRecord()7650     public void clearSystemUpdatePolicyFreezePeriodRecord() {
7651         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
7652         if (mService == null) {
7653             return;
7654         }
7655         try {
7656             mService.clearSystemUpdatePolicyFreezePeriodRecord();
7657         } catch (RemoteException re) {
7658             throw re.rethrowFromSystemServer();
7659         }
7660     }
7661 
7662     /**
7663      * Called by a device owner or profile owner of secondary users that is affiliated with the
7664      * device to disable the keyguard altogether.
7665      * <p>
7666      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
7667      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
7668      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
7669      * disabled.
7670      *
7671      * <p>
7672      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
7673      * keyguard if it is currently shown.
7674      *
7675      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7676      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
7677      * @return {@code false} if attempting to disable the keyguard while a lock password was in
7678      *         place. {@code true} otherwise.
7679      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
7680      * secondary user that is affiliated with the device.
7681      * @see #isAffiliatedUser
7682      * @see #getSecondaryUsers
7683      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)7684     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
7685         throwIfParentInstance("setKeyguardDisabled");
7686         try {
7687             return mService.setKeyguardDisabled(admin, disabled);
7688         } catch (RemoteException re) {
7689             throw re.rethrowFromSystemServer();
7690         }
7691     }
7692 
7693     /**
7694      * Called by device owner or profile owner of secondary users  that is affiliated with the
7695      * device to disable the status bar. Disabling the status bar blocks notifications, quick
7696      * settings and other screen overlays that allow escaping from a single use device.
7697      * <p>
7698      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
7699      * status bar in LockTask mode can be configured with
7700      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
7701      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
7702      * mode.
7703      *
7704      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7705      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
7706      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
7707      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
7708      * secondary user that is affiliated with the device.
7709      * @see #isAffiliatedUser
7710      * @see #getSecondaryUsers
7711      */
setStatusBarDisabled(@onNull ComponentName admin, boolean disabled)7712     public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
7713         throwIfParentInstance("setStatusBarDisabled");
7714         try {
7715             return mService.setStatusBarDisabled(admin, disabled);
7716         } catch (RemoteException re) {
7717             throw re.rethrowFromSystemServer();
7718         }
7719     }
7720 
7721     /**
7722      * Called by the system update service to notify device and profile owners of pending system
7723      * updates.
7724      *
7725      * This method should only be used when it is unknown whether the pending system
7726      * update is a security patch. Otherwise, use
7727      * {@link #notifyPendingSystemUpdate(long, boolean)}.
7728      *
7729      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
7730      *         indicating when the current pending update was first available. {@code -1} if no
7731      *         update is available.
7732      * @see #notifyPendingSystemUpdate(long, boolean)
7733      * @hide
7734      */
7735     @SystemApi
7736     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)7737     public void notifyPendingSystemUpdate(long updateReceivedTime) {
7738         throwIfParentInstance("notifyPendingSystemUpdate");
7739         if (mService != null) {
7740             try {
7741                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
7742             } catch (RemoteException re) {
7743                 throw re.rethrowFromSystemServer();
7744             }
7745         }
7746     }
7747 
7748     /**
7749      * Called by the system update service to notify device and profile owners of pending system
7750      * updates.
7751      *
7752      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
7753      * when it is known whether the pending system update is a security patch.
7754      *
7755      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
7756      *         indicating when the current pending update was first available. {@code -1} if no
7757      *         update is available.
7758      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
7759      *         {@code false} if not.
7760      * @see #notifyPendingSystemUpdate(long)
7761      * @hide
7762      */
7763     @SystemApi
7764     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)7765     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
7766         throwIfParentInstance("notifyPendingSystemUpdate");
7767         if (mService != null) {
7768             try {
7769                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
7770                         isSecurityPatch));
7771             } catch (RemoteException re) {
7772                 throw re.rethrowFromSystemServer();
7773             }
7774         }
7775     }
7776 
7777     /**
7778      * Called by device or profile owners to get information about a pending system update.
7779      *
7780      * @param admin Which profile or device owner this request is associated with.
7781      * @return Information about a pending system update or {@code null} if no update pending.
7782      * @throws SecurityException if {@code admin} is not a device or profile owner.
7783      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
7784      */
getPendingSystemUpdate(@onNull ComponentName admin)7785     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
7786         throwIfParentInstance("getPendingSystemUpdate");
7787         try {
7788             return mService.getPendingSystemUpdate(admin);
7789         } catch (RemoteException re) {
7790             throw re.rethrowFromSystemServer();
7791         }
7792     }
7793 
7794     /**
7795      * Set the default response for future runtime permission requests by applications. This
7796      * function can be called by a device owner, profile owner, or by a delegate given the
7797      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7798      * The policy can allow for normal operation which prompts the user to grant a permission, or
7799      * can allow automatic granting or denying of runtime permission requests by an application.
7800      * This also applies to new permissions declared by app updates. When a permission is denied or
7801      * granted this way, the effect is equivalent to setting the permission * grant state via
7802      * {@link #setPermissionGrantState}.
7803      * <p/>
7804      * As this policy only acts on runtime permission requests, it only applies to applications
7805      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
7806      *
7807      * @param admin Which profile or device owner this request is associated with.
7808      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
7809      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
7810      * @throws SecurityException if {@code admin} is not a device or profile owner.
7811      * @see #setPermissionGrantState
7812      * @see #setDelegatedScopes
7813      * @see #DELEGATION_PERMISSION_GRANT
7814      */
setPermissionPolicy(@onNull ComponentName admin, int policy)7815     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
7816         throwIfParentInstance("setPermissionPolicy");
7817         try {
7818             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
7819         } catch (RemoteException re) {
7820             throw re.rethrowFromSystemServer();
7821         }
7822     }
7823 
7824     /**
7825      * Returns the current runtime permission policy set by the device or profile owner. The
7826      * default is {@link #PERMISSION_POLICY_PROMPT}.
7827      *
7828      * @param admin Which profile or device owner this request is associated with.
7829      * @return the current policy for future permission requests.
7830      */
getPermissionPolicy(ComponentName admin)7831     public int getPermissionPolicy(ComponentName admin) {
7832         throwIfParentInstance("getPermissionPolicy");
7833         try {
7834             return mService.getPermissionPolicy(admin);
7835         } catch (RemoteException re) {
7836             throw re.rethrowFromSystemServer();
7837         }
7838     }
7839 
7840     /**
7841      * Sets the grant state of a runtime permission for a specific application. The state can be
7842      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
7843      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
7844      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
7845      * the permission is granted and the user cannot manage it through the UI. This method can only
7846      * be called by a profile owner, device owner, or a delegate given the
7847      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7848      * <p/>
7849      * Note that user cannot manage other permissions in the affected group through the UI
7850      * either and their granted state will be kept as the current value. Thus, it's recommended that
7851      * you set the grant state of all the permissions in the affected group.
7852      * <p/>
7853      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
7854      * the permission. It retains the previous grant, if any.
7855      * <p/>
7856      * Permissions can be granted or revoked only for applications built with a
7857      * {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
7858      *
7859      * @param admin Which profile or device owner this request is associated with.
7860      * @param packageName The application to grant or revoke a permission to.
7861      * @param permission The permission to grant or revoke.
7862      * @param grantState The permission grant state which is one of
7863      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
7864      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
7865      * @return whether the permission was successfully granted or revoked.
7866      * @throws SecurityException if {@code admin} is not a device or profile owner.
7867      * @see #PERMISSION_GRANT_STATE_DENIED
7868      * @see #PERMISSION_GRANT_STATE_DEFAULT
7869      * @see #PERMISSION_GRANT_STATE_GRANTED
7870      * @see #setDelegatedScopes
7871      * @see #DELEGATION_PERMISSION_GRANT
7872      */
setPermissionGrantState(@onNull ComponentName admin, String packageName, String permission, int grantState)7873     public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName,
7874             String permission, int grantState) {
7875         throwIfParentInstance("setPermissionGrantState");
7876         try {
7877             return mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
7878                     permission, grantState);
7879         } catch (RemoteException re) {
7880             throw re.rethrowFromSystemServer();
7881         }
7882     }
7883 
7884     /**
7885      * Returns the current grant state of a runtime permission for a specific application. This
7886      * function can be called by a device owner, profile owner, or by a delegate given the
7887      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7888      *
7889      * @param admin Which profile or device owner this request is associated with, or {@code null}
7890      *            if the caller is a permission grant delegate.
7891      * @param packageName The application to check the grant state for.
7892      * @param permission The permission to check for.
7893      * @return the current grant state specified by device policy. If the profile or device owner
7894      *         has not set a grant state, the return value is
7895      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
7896      *         permission is currently granted for the package.
7897      *         <p/>
7898      *         If a grant state was set by the profile or device owner, then the return value will
7899      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
7900      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
7901      *         currently denied or granted.
7902      * @throws SecurityException if {@code admin} is not a device or profile owner.
7903      * @see #setPermissionGrantState(ComponentName, String, String, int)
7904      * @see PackageManager#checkPermission(String, String)
7905      * @see #setDelegatedScopes
7906      * @see #DELEGATION_PERMISSION_GRANT
7907      */
getPermissionGrantState(@ullable ComponentName admin, String packageName, String permission)7908     public int getPermissionGrantState(@Nullable ComponentName admin, String packageName,
7909             String permission) {
7910         throwIfParentInstance("getPermissionGrantState");
7911         try {
7912             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
7913                     permission);
7914         } catch (RemoteException re) {
7915             throw re.rethrowFromSystemServer();
7916         }
7917     }
7918 
7919     /**
7920      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
7921      * or device, setting itself as the device or profile owner.
7922      *
7923      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7924      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
7925      * @return whether provisioning a managed profile or device is possible.
7926      * @throws IllegalArgumentException if the supplied action is not valid.
7927      */
isProvisioningAllowed(@onNull String action)7928     public boolean isProvisioningAllowed(@NonNull String action) {
7929         throwIfParentInstance("isProvisioningAllowed");
7930         try {
7931             return mService.isProvisioningAllowed(action, mContext.getPackageName());
7932         } catch (RemoteException re) {
7933             throw re.rethrowFromSystemServer();
7934         }
7935     }
7936 
7937     /**
7938      * Checks whether it is possible to initiate provisioning a managed device,
7939      * profile or user, setting the given package as owner.
7940      *
7941      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7942      *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
7943      *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
7944      *        {@link #ACTION_PROVISION_MANAGED_USER}
7945      * @param packageName The package of the component that would be set as device, user, or profile
7946      *        owner.
7947      * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
7948      * @hide
7949      */
checkProvisioningPreCondition( String action, @NonNull String packageName)7950     public @ProvisioningPreCondition int checkProvisioningPreCondition(
7951             String action, @NonNull String packageName) {
7952         try {
7953             return mService.checkProvisioningPreCondition(action, packageName);
7954         } catch (RemoteException re) {
7955             throw re.rethrowFromSystemServer();
7956         }
7957     }
7958 
7959     /**
7960      * Return if this user is a managed profile of another user. An admin can become the profile
7961      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
7962      * user with {@link #createAndManageUser}
7963      * @param admin Which profile owner this request is associated with.
7964      * @return if this user is a managed profile of another user.
7965      */
isManagedProfile(@onNull ComponentName admin)7966     public boolean isManagedProfile(@NonNull ComponentName admin) {
7967         throwIfParentInstance("isManagedProfile");
7968         try {
7969             return mService.isManagedProfile(admin);
7970         } catch (RemoteException re) {
7971             throw re.rethrowFromSystemServer();
7972         }
7973     }
7974 
7975     /**
7976      * @hide
7977      * Return if this user is a system-only user. An admin can manage a device from a system only
7978      * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
7979      * @param admin Which device owner this request is associated with.
7980      * @return if this user is a system-only user.
7981      */
isSystemOnlyUser(@onNull ComponentName admin)7982     public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
7983         try {
7984             return mService.isSystemOnlyUser(admin);
7985         } catch (RemoteException re) {
7986             throw re.rethrowFromSystemServer();
7987         }
7988     }
7989 
7990     /**
7991      * Called by device owner to get the MAC address of the Wi-Fi device.
7992      *
7993      * @param admin Which device owner this request is associated with.
7994      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
7995      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
7996      *         <p>
7997      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
7998      * @throws SecurityException if {@code admin} is not a device owner.
7999      */
getWifiMacAddress(@onNull ComponentName admin)8000     public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
8001         throwIfParentInstance("getWifiMacAddress");
8002         try {
8003             return mService.getWifiMacAddress(admin);
8004         } catch (RemoteException re) {
8005             throw re.rethrowFromSystemServer();
8006         }
8007     }
8008 
8009     /**
8010      * Called by device owner to reboot the device. If there is an ongoing call on the device,
8011      * throws an {@link IllegalStateException}.
8012      * @param admin Which device owner the request is associated with.
8013      * @throws IllegalStateException if device has an ongoing call.
8014      * @throws SecurityException if {@code admin} is not a device owner.
8015      * @see TelephonyManager#CALL_STATE_IDLE
8016      */
reboot(@onNull ComponentName admin)8017     public void reboot(@NonNull ComponentName admin) {
8018         throwIfParentInstance("reboot");
8019         try {
8020             mService.reboot(admin);
8021         } catch (RemoteException re) {
8022             throw re.rethrowFromSystemServer();
8023         }
8024     }
8025 
8026     /**
8027      * Called by a device admin to set the short support message. This will be displayed to the user
8028      * in settings screens where funtionality has been disabled by the admin. The message should be
8029      * limited to a short statement such as "This setting is disabled by your administrator. Contact
8030      * someone@example.com for support." If the message is longer than 200 characters it may be
8031      * truncated.
8032      * <p>
8033      * If the short support message needs to be localized, it is the responsibility of the
8034      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
8035      * and set a new version of this string accordingly.
8036      *
8037      * @see #setLongSupportMessage
8038      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8039      * @param message Short message to be displayed to the user in settings or null to clear the
8040      *            existing message.
8041      * @throws SecurityException if {@code admin} is not an active administrator.
8042      */
setShortSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)8043     public void setShortSupportMessage(@NonNull ComponentName admin,
8044             @Nullable CharSequence message) {
8045         throwIfParentInstance("setShortSupportMessage");
8046         if (mService != null) {
8047             try {
8048                 mService.setShortSupportMessage(admin, message);
8049             } catch (RemoteException e) {
8050                 throw e.rethrowFromSystemServer();
8051             }
8052         }
8053     }
8054 
8055     /**
8056      * Called by a device admin to get the short support message.
8057      *
8058      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8059      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
8060      *         null if no message has been set.
8061      * @throws SecurityException if {@code admin} is not an active administrator.
8062      */
getShortSupportMessage(@onNull ComponentName admin)8063     public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
8064         throwIfParentInstance("getShortSupportMessage");
8065         if (mService != null) {
8066             try {
8067                 return mService.getShortSupportMessage(admin);
8068             } catch (RemoteException e) {
8069                 throw e.rethrowFromSystemServer();
8070             }
8071         }
8072         return null;
8073     }
8074 
8075     /**
8076      * Called by a device admin to set the long support message. This will be displayed to the user
8077      * in the device administators settings screen.
8078      * <p>
8079      * If the long support message needs to be localized, it is the responsibility of the
8080      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
8081      * and set a new version of this string accordingly.
8082      *
8083      * @see #setShortSupportMessage
8084      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8085      * @param message Long message to be displayed to the user in settings or null to clear the
8086      *            existing message.
8087      * @throws SecurityException if {@code admin} is not an active administrator.
8088      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)8089     public void setLongSupportMessage(@NonNull ComponentName admin,
8090             @Nullable CharSequence message) {
8091         throwIfParentInstance("setLongSupportMessage");
8092         if (mService != null) {
8093             try {
8094                 mService.setLongSupportMessage(admin, message);
8095             } catch (RemoteException e) {
8096                 throw e.rethrowFromSystemServer();
8097             }
8098         }
8099     }
8100 
8101     /**
8102      * Called by a device admin to get the long support message.
8103      *
8104      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8105      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
8106      *         null if no message has been set.
8107      * @throws SecurityException if {@code admin} is not an active administrator.
8108      */
getLongSupportMessage(@onNull ComponentName admin)8109     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
8110         throwIfParentInstance("getLongSupportMessage");
8111         if (mService != null) {
8112             try {
8113                 return mService.getLongSupportMessage(admin);
8114             } catch (RemoteException e) {
8115                 throw e.rethrowFromSystemServer();
8116             }
8117         }
8118         return null;
8119     }
8120 
8121     /**
8122      * Called by the system to get the short support message.
8123      *
8124      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8125      * @param userHandle user id the admin is running as.
8126      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
8127      *
8128      * @hide
8129      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)8130     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
8131             int userHandle) {
8132         if (mService != null) {
8133             try {
8134                 return mService.getShortSupportMessageForUser(admin, userHandle);
8135             } catch (RemoteException e) {
8136                 throw e.rethrowFromSystemServer();
8137             }
8138         }
8139         return null;
8140     }
8141 
8142 
8143     /**
8144      * Called by the system to get the long support message.
8145      *
8146      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8147      * @param userHandle user id the admin is running as.
8148      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
8149      *
8150      * @hide
8151      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)8152     public @Nullable CharSequence getLongSupportMessageForUser(
8153             @NonNull ComponentName admin, int userHandle) {
8154         if (mService != null) {
8155             try {
8156                 return mService.getLongSupportMessageForUser(admin, userHandle);
8157             } catch (RemoteException e) {
8158                 throw e.rethrowFromSystemServer();
8159             }
8160         }
8161         return null;
8162     }
8163 
8164     /**
8165      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
8166      * whose calls act on the parent profile.
8167      *
8168      * <p>The following methods are supported for the parent instance, all other methods will
8169      * throw a SecurityException when called on the parent instance:
8170      * <ul>
8171      * <li>{@link #getPasswordQuality}</li>
8172      * <li>{@link #setPasswordQuality}</li>
8173      * <li>{@link #getPasswordMinimumLength}</li>
8174      * <li>{@link #setPasswordMinimumLength}</li>
8175      * <li>{@link #getPasswordMinimumUpperCase}</li>
8176      * <li>{@link #setPasswordMinimumUpperCase}</li>
8177      * <li>{@link #getPasswordMinimumLowerCase}</li>
8178      * <li>{@link #setPasswordMinimumLowerCase}</li>
8179      * <li>{@link #getPasswordMinimumLetters}</li>
8180      * <li>{@link #setPasswordMinimumLetters}</li>
8181      * <li>{@link #getPasswordMinimumNumeric}</li>
8182      * <li>{@link #setPasswordMinimumNumeric}</li>
8183      * <li>{@link #getPasswordMinimumSymbols}</li>
8184      * <li>{@link #setPasswordMinimumSymbols}</li>
8185      * <li>{@link #getPasswordMinimumNonLetter}</li>
8186      * <li>{@link #setPasswordMinimumNonLetter}</li>
8187      * <li>{@link #getPasswordHistoryLength}</li>
8188      * <li>{@link #setPasswordHistoryLength}</li>
8189      * <li>{@link #getPasswordExpirationTimeout}</li>
8190      * <li>{@link #setPasswordExpirationTimeout}</li>
8191      * <li>{@link #getPasswordExpiration}</li>
8192      * <li>{@link #getPasswordMaximumLength}</li>
8193      * <li>{@link #isActivePasswordSufficient}</li>
8194      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
8195      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
8196      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
8197      * <li>{@link #getMaximumTimeToLock}</li>
8198      * <li>{@link #setMaximumTimeToLock}</li>
8199      * <li>{@link #lockNow}</li>
8200      * <li>{@link #getKeyguardDisabledFeatures}</li>
8201      * <li>{@link #setKeyguardDisabledFeatures}</li>
8202      * <li>{@link #getTrustAgentConfiguration}</li>
8203      * <li>{@link #setTrustAgentConfiguration}</li>
8204      * <li>{@link #getRequiredStrongAuthTimeout}</li>
8205      * <li>{@link #setRequiredStrongAuthTimeout}</li>
8206      * </ul>
8207      *
8208      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
8209      * @throws SecurityException if {@code admin} is not a profile owner.
8210      */
getParentProfileInstance(@onNull ComponentName admin)8211     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
8212         throwIfParentInstance("getParentProfileInstance");
8213         try {
8214             if (!mService.isManagedProfile(admin)) {
8215                 throw new SecurityException("The current user does not have a parent profile.");
8216             }
8217             return new DevicePolicyManager(mContext, mService, true);
8218         } catch (RemoteException e) {
8219             throw e.rethrowFromSystemServer();
8220         }
8221     }
8222 
8223     /**
8224      * Called by device owner to control the security logging feature.
8225      *
8226      * <p> Security logs contain various information intended for security auditing purposes.
8227      * See {@link SecurityEvent} for details.
8228      *
8229      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
8230      * are unaffiliated secondary users or profiles on the device, regardless of whether the
8231      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
8232      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
8233      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
8234      *
8235      * @param admin Which device owner this request is associated with.
8236      * @param enabled whether security logging should be enabled or not.
8237      * @throws SecurityException if {@code admin} is not a device owner.
8238      * @see #setAffiliationIds
8239      * @see #retrieveSecurityLogs
8240      */
setSecurityLoggingEnabled(@onNull ComponentName admin, boolean enabled)8241     public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
8242         throwIfParentInstance("setSecurityLoggingEnabled");
8243         try {
8244             mService.setSecurityLoggingEnabled(admin, enabled);
8245         } catch (RemoteException re) {
8246             throw re.rethrowFromSystemServer();
8247         }
8248     }
8249 
8250     /**
8251      * Return whether security logging is enabled or not by the device owner.
8252      *
8253      * <p>Can only be called by the device owner, otherwise a {@link SecurityException} will be
8254      * thrown.
8255      *
8256      * @param admin Which device owner this request is associated with.
8257      * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
8258      * @throws SecurityException if {@code admin} is not a device owner.
8259      */
isSecurityLoggingEnabled(@ullable ComponentName admin)8260     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
8261         throwIfParentInstance("isSecurityLoggingEnabled");
8262         try {
8263             return mService.isSecurityLoggingEnabled(admin);
8264         } catch (RemoteException re) {
8265             throw re.rethrowFromSystemServer();
8266         }
8267     }
8268 
8269     /**
8270      * Called by device owner to retrieve all new security logging entries since the last call to
8271      * this API after device boots.
8272      *
8273      * <p> Access to the logs is rate limited and it will only return new logs after the device
8274      * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
8275      *
8276      * <p>If there is any other user or profile on the device, it must be affiliated with the
8277      * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8278      *
8279      * @param admin Which device owner this request is associated with.
8280      * @return the new batch of security logs which is a list of {@link SecurityEvent},
8281      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
8282      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8283      * profile or secondary user that is not affiliated with the device.
8284      * @see #isAffiliatedUser
8285      * @see DeviceAdminReceiver#onSecurityLogsAvailable
8286      */
retrieveSecurityLogs(@onNull ComponentName admin)8287     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
8288         throwIfParentInstance("retrieveSecurityLogs");
8289         try {
8290             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
8291             if (list != null) {
8292                 return list.getList();
8293             } else {
8294                 // Rate limit exceeded.
8295                 return null;
8296             }
8297         } catch (RemoteException re) {
8298             throw re.rethrowFromSystemServer();
8299         }
8300     }
8301 
8302     /**
8303      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
8304      * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
8305      * @hide
8306      */
forceSecurityLogs()8307     public long forceSecurityLogs() {
8308         if (mService == null) {
8309             return 0;
8310         }
8311         try {
8312             return mService.forceSecurityLogs();
8313         } catch (RemoteException re) {
8314             throw re.rethrowFromSystemServer();
8315         }
8316     }
8317 
8318     /**
8319      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
8320      * profile.
8321      *
8322      * @hide
8323      */
getParentProfileInstance(UserInfo uInfo)8324     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
8325         mContext.checkSelfPermission(
8326                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
8327         if (!uInfo.isManagedProfile()) {
8328             throw new SecurityException("The user " + uInfo.id
8329                     + " does not have a parent profile.");
8330         }
8331         return new DevicePolicyManager(mContext, mService, true);
8332     }
8333 
8334     /**
8335      * Called by a device or profile owner to restrict packages from using metered data.
8336      *
8337      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
8338      * @param packageNames the list of package names to be restricted.
8339      * @return a list of package names which could not be restricted.
8340      * @throws SecurityException if {@code admin} is not a device or profile owner.
8341      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)8342     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
8343             @NonNull List<String> packageNames) {
8344         throwIfParentInstance("setMeteredDataDisabled");
8345         if (mService != null) {
8346             try {
8347                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
8348             } catch (RemoteException re) {
8349                 throw re.rethrowFromSystemServer();
8350             }
8351         }
8352         return packageNames;
8353     }
8354 
8355     /**
8356      * Called by a device or profile owner to retrieve the list of packages which are restricted
8357      * by the admin from using metered data.
8358      *
8359      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
8360      * @return the list of restricted package names.
8361      * @throws SecurityException if {@code admin} is not a device or profile owner.
8362      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)8363     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
8364         throwIfParentInstance("getMeteredDataDisabled");
8365         if (mService != null) {
8366             try {
8367                 return mService.getMeteredDataDisabledPackages(admin);
8368             } catch (RemoteException re) {
8369                 throw re.rethrowFromSystemServer();
8370             }
8371         }
8372         return new ArrayList<>();
8373     }
8374 
8375     /**
8376      * Called by the system to check if a package is restricted from using metered data
8377      * by {@param admin}.
8378      *
8379      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
8380      * @param packageName the package whose restricted status is needed.
8381      * @param userId the user to which {@param packageName} belongs.
8382      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
8383      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
8384      * @hide
8385      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)8386     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
8387             String packageName, @UserIdInt int userId) {
8388         throwIfParentInstance("getMeteredDataDisabledForUser");
8389         if (mService != null) {
8390             try {
8391                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
8392             } catch (RemoteException re) {
8393                 throw re.rethrowFromSystemServer();
8394             }
8395         }
8396         return false;
8397     }
8398 
8399     /**
8400      * Called by device owners to retrieve device logs from before the device's last reboot.
8401      * <p>
8402      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
8403      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
8404      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
8405      * about data corruption when parsing. </strong>
8406      *
8407      * <p>If there is any other user or profile on the device, it must be affiliated with the
8408      * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8409      *
8410      * @param admin Which device owner this request is associated with.
8411      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
8412      *         is not supported on the device.
8413      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8414      * profile or secondary user that is not affiliated with the device.
8415      * @see #isAffiliatedUser
8416      * @see #retrieveSecurityLogs
8417      */
retrievePreRebootSecurityLogs( @onNull ComponentName admin)8418     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
8419             @NonNull ComponentName admin) {
8420         throwIfParentInstance("retrievePreRebootSecurityLogs");
8421         try {
8422             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
8423             if (list != null) {
8424                 return list.getList();
8425             } else {
8426                 return null;
8427             }
8428         } catch (RemoteException re) {
8429             throw re.rethrowFromSystemServer();
8430         }
8431     }
8432 
8433     /**
8434      * Called by a profile owner of a managed profile to set the color used for customization. This
8435      * color is used as background color of the confirm credentials screen for that user. The
8436      * default color is teal (#00796B).
8437      * <p>
8438      * The confirm credentials screen can be created using
8439      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
8440      *
8441      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8442      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
8443      * @throws SecurityException if {@code admin} is not a profile owner.
8444      */
setOrganizationColor(@onNull ComponentName admin, int color)8445     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
8446         throwIfParentInstance("setOrganizationColor");
8447         try {
8448             // always enforce alpha channel to have 100% opacity
8449             color |= 0xFF000000;
8450             mService.setOrganizationColor(admin, color);
8451         } catch (RemoteException re) {
8452             throw re.rethrowFromSystemServer();
8453         }
8454     }
8455 
8456     /**
8457      * @hide
8458      *
8459      * Sets the color used for customization.
8460      *
8461      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
8462      * @param userId which user to set the color to.
8463      * @RequiresPermission(allOf = {
8464      *       Manifest.permission.MANAGE_USERS,
8465      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
8466      */
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)8467     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
8468         try {
8469             // always enforce alpha channel to have 100% opacity
8470             color |= 0xFF000000;
8471             mService.setOrganizationColorForUser(color, userId);
8472         } catch (RemoteException re) {
8473             throw re.rethrowFromSystemServer();
8474         }
8475     }
8476 
8477     /**
8478      * Called by a profile owner of a managed profile to retrieve the color used for customization.
8479      * This color is used as background color of the confirm credentials screen for that user.
8480      *
8481      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8482      * @return The 24bit (0xRRGGBB) representation of the color to be used.
8483      * @throws SecurityException if {@code admin} is not a profile owner.
8484      */
getOrganizationColor(@onNull ComponentName admin)8485     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
8486         throwIfParentInstance("getOrganizationColor");
8487         try {
8488             return mService.getOrganizationColor(admin);
8489         } catch (RemoteException re) {
8490             throw re.rethrowFromSystemServer();
8491         }
8492     }
8493 
8494     /**
8495      * @hide
8496      * Retrieve the customization color for a given user.
8497      *
8498      * @param userHandle The user id of the user we're interested in.
8499      * @return The 24bit (0xRRGGBB) representation of the color to be used.
8500      */
getOrganizationColorForUser(int userHandle)8501     public @ColorInt int getOrganizationColorForUser(int userHandle) {
8502         try {
8503             return mService.getOrganizationColorForUser(userHandle);
8504         } catch (RemoteException re) {
8505             throw re.rethrowFromSystemServer();
8506         }
8507     }
8508 
8509     /**
8510      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
8511      * the organization under management.
8512      *
8513      * <p>If the organization name needs to be localized, it is the responsibility of the {@link
8514      * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
8515      * a new version of this string accordingly.
8516      *
8517      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8518      * @param title The organization name or {@code null} to clear a previously set name.
8519      * @throws SecurityException if {@code admin} is not a device or profile owner.
8520      */
setOrganizationName(@onNull ComponentName admin, @Nullable CharSequence title)8521     public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
8522         throwIfParentInstance("setOrganizationName");
8523         try {
8524             mService.setOrganizationName(admin, title);
8525         } catch (RemoteException re) {
8526             throw re.rethrowFromSystemServer();
8527         }
8528     }
8529 
8530     /**
8531      * Called by a profile owner of a managed profile to retrieve the name of the organization under
8532      * management.
8533      *
8534      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8535      * @return The organization name or {@code null} if none is set.
8536      * @throws SecurityException if {@code admin} is not a profile owner.
8537      */
getOrganizationName(@onNull ComponentName admin)8538     public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
8539         throwIfParentInstance("getOrganizationName");
8540         try {
8541             return mService.getOrganizationName(admin);
8542         } catch (RemoteException re) {
8543             throw re.rethrowFromSystemServer();
8544         }
8545     }
8546 
8547     /**
8548      * Called by the system to retrieve the name of the organization managing the device.
8549      *
8550      * @return The organization name or {@code null} if none is set.
8551      * @throws SecurityException if the caller is not the device owner, does not hold the
8552      *         MANAGE_USERS permission and is not the system.
8553      *
8554      * @hide
8555      */
8556     @SystemApi
8557     @TestApi
8558     @SuppressLint("Doclava125")
getDeviceOwnerOrganizationName()8559     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
8560         try {
8561             return mService.getDeviceOwnerOrganizationName();
8562         } catch (RemoteException re) {
8563             throw re.rethrowFromSystemServer();
8564         }
8565     }
8566 
8567     /**
8568      * Retrieve the default title message used in the confirm credentials screen for a given user.
8569      *
8570      * @param userHandle The user id of the user we're interested in.
8571      * @return The organization name or {@code null} if none is set.
8572      *
8573      * @hide
8574      */
getOrganizationNameForUser(int userHandle)8575     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
8576         try {
8577             return mService.getOrganizationNameForUser(userHandle);
8578         } catch (RemoteException re) {
8579             throw re.rethrowFromSystemServer();
8580         }
8581     }
8582 
8583     /**
8584      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
8585      *         return {@link #STATE_USER_UNMANAGED}
8586      * @hide
8587      */
8588     @SystemApi
8589     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8590     @UserProvisioningState
getUserProvisioningState()8591     public int getUserProvisioningState() {
8592         throwIfParentInstance("getUserProvisioningState");
8593         if (mService != null) {
8594             try {
8595                 return mService.getUserProvisioningState();
8596             } catch (RemoteException e) {
8597                 throw e.rethrowFromSystemServer();
8598             }
8599         }
8600         return STATE_USER_UNMANAGED;
8601     }
8602 
8603     /**
8604      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
8605      *
8606      * @param state to store
8607      * @param userHandle for user
8608      * @hide
8609      */
setUserProvisioningState(@serProvisioningState int state, int userHandle)8610     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
8611         if (mService != null) {
8612             try {
8613                 mService.setUserProvisioningState(state, userHandle);
8614             } catch (RemoteException e) {
8615                 throw e.rethrowFromSystemServer();
8616             }
8617         }
8618     }
8619 
8620     /**
8621      * Indicates the entity that controls the device or profile owner. Two users/profiles are
8622      * affiliated if the set of ids set by their device or profile owners intersect.
8623      *
8624      * <p>A user/profile that is affiliated with the device owner user is considered to be
8625      * affiliated with the device.
8626      *
8627      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
8628      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user or profile
8629      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
8630      * affiliation ids are set by its profile owner as soon as possible after the user/profile is
8631      * created.
8632      *
8633      * @param admin Which profile or device owner this request is associated with.
8634      * @param ids A set of opaque non-empty affiliation ids.
8635      *
8636      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
8637      * @see #isAffiliatedUser
8638      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)8639     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
8640         throwIfParentInstance("setAffiliationIds");
8641         if (ids == null) {
8642             throw new IllegalArgumentException("ids must not be null");
8643         }
8644         try {
8645             mService.setAffiliationIds(admin, new ArrayList<>(ids));
8646         } catch (RemoteException e) {
8647             throw e.rethrowFromSystemServer();
8648         }
8649     }
8650 
8651     /**
8652      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
8653      * empty set if none have been set.
8654      */
getAffiliationIds(@onNull ComponentName admin)8655     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
8656         throwIfParentInstance("getAffiliationIds");
8657         try {
8658             return new ArraySet<>(mService.getAffiliationIds(admin));
8659         } catch (RemoteException e) {
8660             throw e.rethrowFromSystemServer();
8661         }
8662     }
8663 
8664     /**
8665      * Returns whether this user/profile is affiliated with the device.
8666      * <p>
8667      * By definition, the user that the device owner runs on is always affiliated with the device.
8668      * Any other user/profile is considered affiliated with the device if the set specified by its
8669      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
8670      * @see #setAffiliationIds
8671      */
isAffiliatedUser()8672     public boolean isAffiliatedUser() {
8673         throwIfParentInstance("isAffiliatedUser");
8674         try {
8675             return mService.isAffiliatedUser();
8676         } catch (RemoteException e) {
8677             throw e.rethrowFromSystemServer();
8678         }
8679     }
8680 
8681     /**
8682      * @hide
8683      * Returns whether the uninstall for {@code packageName} for the current user is in queue
8684      * to be started
8685      * @param packageName the package to check for
8686      * @return whether the uninstall intent for {@code packageName} is pending
8687      */
isUninstallInQueue(String packageName)8688     public boolean isUninstallInQueue(String packageName) {
8689         try {
8690             return mService.isUninstallInQueue(packageName);
8691         } catch (RemoteException re) {
8692             throw re.rethrowFromSystemServer();
8693         }
8694     }
8695 
8696     /**
8697      * @hide
8698      * @param packageName the package containing active DAs to be uninstalled
8699      */
uninstallPackageWithActiveAdmins(String packageName)8700     public void uninstallPackageWithActiveAdmins(String packageName) {
8701         try {
8702             mService.uninstallPackageWithActiveAdmins(packageName);
8703         } catch (RemoteException re) {
8704             throw re.rethrowFromSystemServer();
8705         }
8706     }
8707 
8708     /**
8709      * @hide
8710      * Remove a test admin synchronously without sending it a broadcast about being removed.
8711      * If the admin is a profile owner or device owner it will still be removed.
8712      *
8713      * @param userHandle user id to remove the admin for.
8714      * @param admin The administration compononent to remove.
8715      * @throws SecurityException if the caller is not shell / root or the admin package
8716      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
8717      */
forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle)8718     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
8719         try {
8720             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
8721         } catch (RemoteException re) {
8722             throw re.rethrowFromSystemServer();
8723         }
8724     }
8725 
8726     /**
8727      * Returns whether the device has been provisioned.
8728      *
8729      * <p>Not for use by third-party applications.
8730      *
8731      * @hide
8732      */
8733     @SystemApi
8734     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()8735     public boolean isDeviceProvisioned() {
8736         try {
8737             return mService.isDeviceProvisioned();
8738         } catch (RemoteException re) {
8739             throw re.rethrowFromSystemServer();
8740         }
8741     }
8742 
8743     /**
8744       * Writes that the provisioning configuration has been applied.
8745       *
8746       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
8747       * permission.
8748       *
8749       * <p>Not for use by third-party applications.
8750       *
8751       * @hide
8752       */
8753     @SystemApi
8754     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()8755     public void setDeviceProvisioningConfigApplied() {
8756         try {
8757             mService.setDeviceProvisioningConfigApplied();
8758         } catch (RemoteException re) {
8759             throw re.rethrowFromSystemServer();
8760         }
8761     }
8762 
8763     /**
8764      * Returns whether the provisioning configuration has been applied.
8765      *
8766      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
8767      *
8768      * <p>Not for use by third-party applications.
8769      *
8770      * @return whether the provisioning configuration has been applied.
8771      *
8772      * @hide
8773      */
8774     @SystemApi
8775     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()8776     public boolean isDeviceProvisioningConfigApplied() {
8777         try {
8778             return mService.isDeviceProvisioningConfigApplied();
8779         } catch (RemoteException re) {
8780             throw re.rethrowFromSystemServer();
8781         }
8782     }
8783 
8784     /**
8785      * @hide
8786      * Force update user setup completed status. This API has no effect on user build.
8787      * @throws {@link SecurityException} if the caller has no
8788      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
8789      *         not {@link UserHandle#SYSTEM_USER}
8790      */
forceUpdateUserSetupComplete()8791     public void forceUpdateUserSetupComplete() {
8792         try {
8793             mService.forceUpdateUserSetupComplete();
8794         } catch (RemoteException re) {
8795             throw re.rethrowFromSystemServer();
8796         }
8797     }
8798 
throwIfParentInstance(String functionName)8799     private void throwIfParentInstance(String functionName) {
8800         if (mParentInstance) {
8801             throw new SecurityException(functionName + " cannot be called on the parent instance");
8802         }
8803     }
8804 
8805     /**
8806      * Allows the device owner to enable or disable the backup service.
8807      *
8808      * <p> Backup service manages all backup and restore mechanisms on the device. Setting this to
8809      * false will prevent data from being backed up or restored.
8810      *
8811      * <p> Backup service is off by default when device owner is present.
8812      *
8813      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8814      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
8815      * @throws SecurityException if {@code admin} is not a device owner.
8816      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)8817     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
8818         throwIfParentInstance("setBackupServiceEnabled");
8819         try {
8820             mService.setBackupServiceEnabled(admin, enabled);
8821         } catch (RemoteException re) {
8822             throw re.rethrowFromSystemServer();
8823         }
8824     }
8825 
8826     /**
8827      * Return whether the backup service is enabled by the device owner.
8828      *
8829      * <p> Backup service manages all backup and restore mechanisms on the device.
8830      *
8831      * @return {@code true} if backup service is enabled, {@code false} otherwise.
8832      * @see #setBackupServiceEnabled
8833      */
isBackupServiceEnabled(@onNull ComponentName admin)8834     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
8835         throwIfParentInstance("isBackupServiceEnabled");
8836         try {
8837             return mService.isBackupServiceEnabled(admin);
8838         } catch (RemoteException re) {
8839             throw re.rethrowFromSystemServer();
8840         }
8841     }
8842 
8843     /**
8844      * Makes backups mandatory and enforces the usage of the specified backup transport.
8845      *
8846      * <p>When a {@code null} backup transport is specified, backups are made optional again.
8847      * <p>Only device owner can call this method.
8848      * <p>If backups were disabled and a non-null backup transport {@link ComponentName} is
8849      * specified, backups will be enabled.
8850      * <p> If the backup service is disabled after the mandatory backup transport has been set, the
8851      * mandatory backup transport is cleared.
8852      *
8853      * <p>NOTE: The method shouldn't be called on the main thread.
8854      *
8855      * @param admin admin Which {@link DeviceAdminReceiver} this request is associated with.
8856      * @param backupTransportComponent The backup transport layer to be used for mandatory backups.
8857      * @return {@code true} if the backup transport was successfully set; {@code false} otherwise.
8858      * @throws SecurityException if {@code admin} is not a device owner.
8859      * @hide
8860      */
8861     @WorkerThread
setMandatoryBackupTransport( @onNull ComponentName admin, @Nullable ComponentName backupTransportComponent)8862     public boolean setMandatoryBackupTransport(
8863             @NonNull ComponentName admin,
8864             @Nullable ComponentName backupTransportComponent) {
8865         throwIfParentInstance("setMandatoryBackupTransport");
8866         try {
8867             return mService.setMandatoryBackupTransport(admin, backupTransportComponent);
8868         } catch (RemoteException re) {
8869             throw re.rethrowFromSystemServer();
8870         }
8871     }
8872 
8873     /**
8874      * Returns the backup transport which has to be used for backups if backups are mandatory or
8875      * {@code null} if backups are not mandatory.
8876      *
8877      * @return a {@link ComponentName} of the backup transport layer to be used if backups are
8878      *         mandatory or {@code null} if backups are not mandatory.
8879      * @hide
8880      */
getMandatoryBackupTransport()8881     public ComponentName getMandatoryBackupTransport() {
8882         throwIfParentInstance("getMandatoryBackupTransport");
8883         try {
8884             return mService.getMandatoryBackupTransport();
8885         } catch (RemoteException re) {
8886             throw re.rethrowFromSystemServer();
8887         }
8888     }
8889 
8890 
8891     /**
8892      * Called by a device owner to control the network logging feature.
8893      *
8894      * <p> Network logs contain DNS lookup and connect() library call events. The following library
8895      *     functions are recorded while network logging is active:
8896      *     <ul>
8897      *       <li>{@code getaddrinfo()}</li>
8898      *       <li>{@code gethostbyname()}</li>
8899      *       <li>{@code connect()}</li>
8900      *     </ul>
8901      *
8902      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
8903      *     full system call logging; event reporting is enabled by default for all processes but not
8904      *     strongly enforced.
8905      *     Events from applications using alternative implementations of libc, making direct kernel
8906      *     calls, or deliberately obfuscating traffic may not be recorded.
8907      *
8908      * <p> Some common network events may not be reported. For example:
8909      *     <ul>
8910      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
8911      *           an alternative system for name resolution, and so avoid calling
8912      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
8913      *       <li>Applications may use datagram sockets for performance reasons, for example
8914      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
8915      *           socket, so it will not trigger a network event.</li>
8916      *     </ul>
8917      *
8918      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
8919      *     always-on VPN service.
8920      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
8921      *     and {@link android.net.VpnService} for details.
8922      *
8923      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
8924      * are unaffiliated secondary users or profiles on the device, regardless of whether the
8925      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
8926      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
8927      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
8928      *
8929      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8930      * @param enabled whether network logging should be enabled or not.
8931      * @throws SecurityException if {@code admin} is not a device owner.
8932      * @see #setAffiliationIds
8933      * @see #retrieveNetworkLogs
8934      */
setNetworkLoggingEnabled(@onNull ComponentName admin, boolean enabled)8935     public void setNetworkLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
8936         throwIfParentInstance("setNetworkLoggingEnabled");
8937         try {
8938             mService.setNetworkLoggingEnabled(admin, enabled);
8939         } catch (RemoteException re) {
8940             throw re.rethrowFromSystemServer();
8941         }
8942     }
8943 
8944     /**
8945      * Return whether network logging is enabled by a device owner.
8946      *
8947      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
8948      * be {@code null} if the caller has MANAGE_USERS permission.
8949      * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
8950      * @throws SecurityException if {@code admin} is not a device owner and caller has
8951      * no MANAGE_USERS permission
8952      */
isNetworkLoggingEnabled(@ullable ComponentName admin)8953     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
8954         throwIfParentInstance("isNetworkLoggingEnabled");
8955         try {
8956             return mService.isNetworkLoggingEnabled(admin);
8957         } catch (RemoteException re) {
8958             throw re.rethrowFromSystemServer();
8959         }
8960     }
8961 
8962     /**
8963      * Called by device owner to retrieve the most recent batch of network logging events.
8964      * A device owner has to provide a batchToken provided as part of
8965      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
8966      * token of the most recent available batch of logs, {@code null} will be returned.
8967      *
8968      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
8969      *
8970      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
8971      *
8972      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
8973      * after the device device owner has been notified via
8974      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
8975      *
8976      * <p>If a secondary user or profile is created, calling this method will throw a
8977      * {@link SecurityException} until all users become affiliated again. It will also no longer be
8978      * possible to retrieve the network logs batch with the most recent batchToken provided
8979      * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
8980      * {@link DevicePolicyManager#setAffiliationIds}.
8981      *
8982      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8983      * @param batchToken A token of the batch to retrieve
8984      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
8985      *        {@code null} if the batch represented by batchToken is no longer available or if
8986      *        logging is disabled.
8987      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8988      * profile or secondary user that is not affiliated with the device.
8989      * @see #setAffiliationIds
8990      * @see DeviceAdminReceiver#onNetworkLogsAvailable
8991      */
retrieveNetworkLogs(@onNull ComponentName admin, long batchToken)8992     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@NonNull ComponentName admin,
8993             long batchToken) {
8994         throwIfParentInstance("retrieveNetworkLogs");
8995         try {
8996             return mService.retrieveNetworkLogs(admin, batchToken);
8997         } catch (RemoteException re) {
8998             throw re.rethrowFromSystemServer();
8999         }
9000     }
9001 
9002     /**
9003      * Called by a device owner to bind to a service from a profile owner or vice versa.
9004      * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
9005      * device/profile owners are allowed to bind to services of another profile/device owner.
9006      * <p>
9007      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
9008      * Note that the {@link Context} used to obtain this
9009      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
9010      * to bind to the {@link android.app.Service}.
9011      *
9012      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9013      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
9014      *        explicit component name or a package name to match an
9015      *        {@link IntentFilter} published by a service.
9016      * @param conn Receives information as the service is started and stopped in main thread. This
9017      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
9018      * @param flags Operation options for the binding operation. See
9019      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
9020      * @param targetUser Which user to bind to. Must be one of the users returned by
9021      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
9022      *        be thrown.
9023      * @return If you have successfully bound to the service, {@code true} is returned;
9024      *         {@code false} is returned if the connection is not made and you will not
9025      *         receive the service object.
9026      *
9027      * @see Context#bindService(Intent, ServiceConnection, int)
9028      * @see #getBindDeviceAdminTargetUsers(ComponentName)
9029      */
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser)9030     public boolean bindDeviceAdminServiceAsUser(
9031             @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
9032             @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
9033         throwIfParentInstance("bindDeviceAdminServiceAsUser");
9034         // Keep this in sync with ContextImpl.bindServiceCommon.
9035         try {
9036             final IServiceConnection sd = mContext.getServiceDispatcher(
9037                     conn, mContext.getMainThreadHandler(), flags);
9038             serviceIntent.prepareToLeaveProcess(mContext);
9039             return mService.bindDeviceAdminServiceAsUser(admin,
9040                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
9041                     sd, flags, targetUser.getIdentifier());
9042         } catch (RemoteException re) {
9043             throw re.rethrowFromSystemServer();
9044         }
9045     }
9046 
9047     /**
9048      * Returns the list of target users that the calling device or profile owner can use when
9049      * calling {@link #bindDeviceAdminServiceAsUser}.
9050      * <p>
9051      * A device owner can bind to a service from a profile owner and vice versa, provided that:
9052      * <ul>
9053      * <li>Both belong to the same package name.
9054      * <li>Both users are affiliated. See {@link #setAffiliationIds}.
9055      * </ul>
9056      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)9057     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
9058         throwIfParentInstance("getBindDeviceAdminTargetUsers");
9059         try {
9060             return mService.getBindDeviceAdminTargetUsers(admin);
9061         } catch (RemoteException re) {
9062             throw re.rethrowFromSystemServer();
9063         }
9064     }
9065 
9066     /**
9067      * Called by the system to get the time at which the device owner last retrieved security
9068      * logging entries.
9069      *
9070      * @return the time at which the device owner most recently retrieved security logging entries,
9071      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
9072      * @throws SecurityException if the caller is not the device owner, does not hold the
9073      *         MANAGE_USERS permission and is not the system.
9074      *
9075      * @hide
9076      */
9077     @TestApi
getLastSecurityLogRetrievalTime()9078     public long getLastSecurityLogRetrievalTime() {
9079         try {
9080             return mService.getLastSecurityLogRetrievalTime();
9081         } catch (RemoteException re) {
9082             throw re.rethrowFromSystemServer();
9083         }
9084     }
9085 
9086     /**
9087      * Called by the system to get the time at which the device owner last requested a bug report.
9088      *
9089      * @return the time at which the device owner most recently requested a bug report, in
9090      *         milliseconds since epoch; -1 if a bug report was never requested.
9091      * @throws SecurityException if the caller is not the device owner, does not hold the
9092      *         MANAGE_USERS permission and is not the system.
9093      *
9094      * @hide
9095      */
9096     @TestApi
getLastBugReportRequestTime()9097     public long getLastBugReportRequestTime() {
9098         try {
9099             return mService.getLastBugReportRequestTime();
9100         } catch (RemoteException re) {
9101             throw re.rethrowFromSystemServer();
9102         }
9103     }
9104 
9105     /**
9106      * Called by the system to get the time at which the device owner last retrieved network logging
9107      * events.
9108      *
9109      * @return the time at which the device owner most recently retrieved network logging events, in
9110      *         milliseconds since epoch; -1 if network logging events were never retrieved.
9111      * @throws SecurityException if the caller is not the device owner, does not hold the
9112      *         MANAGE_USERS permission and is not the system.
9113      *
9114      * @hide
9115      */
9116     @TestApi
getLastNetworkLogRetrievalTime()9117     public long getLastNetworkLogRetrievalTime() {
9118         try {
9119             return mService.getLastNetworkLogRetrievalTime();
9120         } catch (RemoteException re) {
9121             throw re.rethrowFromSystemServer();
9122         }
9123     }
9124 
9125     /**
9126      * Called by the system to find out whether the current user's IME was set by the device/profile
9127      * owner or the user.
9128      *
9129      * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
9130      *         otherwise.
9131      * @throws SecurityException if the caller is not the device owner/profile owner.
9132      *
9133      * @hide
9134      */
9135     @TestApi
isCurrentInputMethodSetByOwner()9136     public boolean isCurrentInputMethodSetByOwner() {
9137         try {
9138             return mService.isCurrentInputMethodSetByOwner();
9139         } catch (RemoteException re) {
9140             throw re.rethrowFromSystemServer();
9141         }
9142     }
9143 
9144     /**
9145      * Called by the system to get a list of CA certificates that were installed by the device or
9146      * profile owner.
9147      *
9148      * <p> The caller must be the target user's device owner/profile Owner or hold the
9149      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
9150      *
9151      * @param user The user for whom to retrieve information.
9152      * @return list of aliases identifying CA certificates installed by the device or profile owner
9153      * @throws SecurityException if the caller does not have permission to retrieve information
9154      *         about the given user's CA certificates.
9155      *
9156      * @hide
9157      */
9158     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)9159     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
9160         try {
9161             return mService.getOwnerInstalledCaCerts(user).getList();
9162         } catch (RemoteException re) {
9163             throw re.rethrowFromSystemServer();
9164         }
9165     }
9166 
9167     /**
9168      * Called by the device owner or profile owner to clear application user data of a given
9169      * package. The behaviour of this is equivalent to the target application calling
9170      * {@link android.app.ActivityManager#clearApplicationUserData()}.
9171      *
9172      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
9173      * external storage or user dictionary. This data will not be wiped by calling this API.
9174      *
9175      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9176      * @param packageName The name of the package which will have its user data wiped.
9177      * @param executor The executor through which the listener should be invoked.
9178      * @param listener A callback object that will inform the caller when the clearing is done.
9179      * @throws SecurityException if the caller is not the device owner/profile owner.
9180      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)9181     public void clearApplicationUserData(@NonNull ComponentName admin,
9182             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
9183             @NonNull OnClearApplicationUserDataListener listener) {
9184         throwIfParentInstance("clearAppData");
9185         Preconditions.checkNotNull(executor);
9186         Preconditions.checkNotNull(listener);
9187         try {
9188             mService.clearApplicationUserData(admin, packageName,
9189                     new IPackageDataObserver.Stub() {
9190                         public void onRemoveCompleted(String pkg, boolean succeeded) {
9191                             executor.execute(() ->
9192                                     listener.onApplicationUserDataCleared(pkg, succeeded));
9193                         }
9194                     });
9195         } catch (RemoteException re) {
9196             throw re.rethrowFromSystemServer();
9197         }
9198     }
9199 
9200     /**
9201      * Called by a device owner to specify whether logout is enabled for all secondary users. The
9202      * system may show a logout button that stops the user and switches back to the primary user.
9203      *
9204      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9205      * @param enabled whether logout should be enabled or not.
9206      * @throws SecurityException if {@code admin} is not a device owner.
9207      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)9208     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
9209         throwIfParentInstance("setLogoutEnabled");
9210         try {
9211             mService.setLogoutEnabled(admin, enabled);
9212         } catch (RemoteException re) {
9213             throw re.rethrowFromSystemServer();
9214         }
9215     }
9216 
9217     /**
9218      * Returns whether logout is enabled by a device owner.
9219      *
9220      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
9221      */
isLogoutEnabled()9222     public boolean isLogoutEnabled() {
9223         throwIfParentInstance("isLogoutEnabled");
9224         try {
9225             return mService.isLogoutEnabled();
9226         } catch (RemoteException re) {
9227             throw re.rethrowFromSystemServer();
9228         }
9229     }
9230 
9231     /**
9232      * Callback used in {@link #clearApplicationUserData}
9233      * to indicate that the clearing of an application's user data is done.
9234      */
9235     public interface OnClearApplicationUserDataListener {
9236         /**
9237          * Method invoked when clearing the application user data has completed.
9238          *
9239          * @param packageName The name of the package which had its user data cleared.
9240          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
9241          *                  apps and protected system packages.
9242          */
onApplicationUserDataCleared(String packageName, boolean succeeded)9243         void onApplicationUserDataCleared(String packageName, boolean succeeded);
9244     }
9245 
9246     /**
9247      * Returns set of system apps that should be removed during provisioning.
9248      *
9249      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9250      * @param userId ID of the user to be provisioned.
9251      * @param provisioningAction action indicating type of provisioning, should be one of
9252      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
9253      * {@link #ACTION_PROVISION_MANAGED_USER}.
9254      *
9255      * @hide
9256      */
getDisallowedSystemApps(ComponentName admin, int userId, String provisioningAction)9257     public Set<String> getDisallowedSystemApps(ComponentName admin, int userId,
9258             String provisioningAction) {
9259         try {
9260             return new ArraySet<>(
9261                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
9262         } catch (RemoteException re) {
9263             throw re.rethrowFromSystemServer();
9264         }
9265     }
9266 
9267     /**
9268      * Changes the current administrator to another one. All policies from the current
9269      * administrator are migrated to the new administrator. The whole operation is atomic -
9270      * the transfer is either complete or not done at all.
9271      *
9272      * <p>Depending on the current administrator (device owner, profile owner), you have the
9273      * following expected behaviour:
9274      * <ul>
9275      *     <li>A device owner can only be transferred to a new device owner</li>
9276      *     <li>A profile owner can only be transferred to a new profile owner</li>
9277      * </ul>
9278      *
9279      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
9280      * will be received in the
9281      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
9282      * callback of the new administrator.
9283      *
9284      * <p>The transfer has failed if the original administrator is still the corresponding owner
9285      * after calling this method.
9286      *
9287      * <p>The incoming target administrator must have the
9288      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
9289      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
9290      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
9291      * {@link IllegalArgumentException} will be thrown.
9292      *
9293      * @param admin which {@link DeviceAdminReceiver} this request is associated with
9294      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
9295      * @param bundle data to be sent to the new administrator
9296      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
9297      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
9298      * are components in the same package or {@code target} is not an active admin
9299      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)9300     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
9301             @Nullable PersistableBundle bundle) {
9302         throwIfParentInstance("transferOwnership");
9303         try {
9304             mService.transferOwnership(admin, target, bundle);
9305         } catch (RemoteException re) {
9306             throw re.rethrowFromSystemServer();
9307         }
9308     }
9309 
9310     /**
9311      * Called by a device owner to specify the user session start message. This may be displayed
9312      * during a user switch.
9313      * <p>
9314      * The message should be limited to a short statement or it may be truncated.
9315      * <p>
9316      * If the message needs to be localized, it is the responsibility of the
9317      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9318      * and set a new version of this message accordingly.
9319      *
9320      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9321      * @param startUserSessionMessage message for starting user session, or {@code null} to use
9322      * system default message.
9323      * @throws SecurityException if {@code admin} is not a device owner.
9324      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)9325     public void setStartUserSessionMessage(
9326             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
9327         throwIfParentInstance("setStartUserSessionMessage");
9328         try {
9329             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
9330         } catch (RemoteException re) {
9331             throw re.rethrowFromSystemServer();
9332         }
9333     }
9334 
9335     /**
9336      * Called by a device owner to specify the user session end message. This may be displayed
9337      * during a user switch.
9338      * <p>
9339      * The message should be limited to a short statement or it may be truncated.
9340      * <p>
9341      * If the message needs to be localized, it is the responsibility of the
9342      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9343      * and set a new version of this message accordingly.
9344      *
9345      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9346      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
9347      * default message.
9348      * @throws SecurityException if {@code admin} is not a device owner.
9349      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)9350     public void setEndUserSessionMessage(
9351             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
9352         throwIfParentInstance("setEndUserSessionMessage");
9353         try {
9354             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
9355         } catch (RemoteException re) {
9356             throw re.rethrowFromSystemServer();
9357         }
9358     }
9359 
9360     /**
9361      * Returns the user session start message.
9362      *
9363      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9364      * @throws SecurityException if {@code admin} is not a device owner.
9365      */
getStartUserSessionMessage(@onNull ComponentName admin)9366     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
9367         throwIfParentInstance("getStartUserSessionMessage");
9368         try {
9369             return mService.getStartUserSessionMessage(admin);
9370         } catch (RemoteException re) {
9371             throw re.rethrowFromSystemServer();
9372         }
9373     }
9374 
9375     /**
9376      * Returns the user session end message.
9377      *
9378      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9379      * @throws SecurityException if {@code admin} is not a device owner.
9380      */
getEndUserSessionMessage(@onNull ComponentName admin)9381     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
9382         throwIfParentInstance("getEndUserSessionMessage");
9383         try {
9384             return mService.getEndUserSessionMessage(admin);
9385         } catch (RemoteException re) {
9386             throw re.rethrowFromSystemServer();
9387         }
9388     }
9389 
9390     /**
9391      * Called by device owner to add an override APN.
9392      *
9393      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
9394      * override APN. Update the existing conflicted APN with
9395      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
9396      * <p>Two override APNs are considered to conflict when all the following APIs return
9397      * the same values on both override APNs:
9398      * <ul>
9399      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
9400      *   <li>{@link ApnSetting#getApnName()}</li>
9401      *   <li>{@link ApnSetting#getProxyAddress()}</li>
9402      *   <li>{@link ApnSetting#getProxyPort()}</li>
9403      *   <li>{@link ApnSetting#getMmsProxyAddress()}</li>
9404      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
9405      *   <li>{@link ApnSetting#getMmsc()}</li>
9406      *   <li>{@link ApnSetting#isEnabled()}</li>
9407      *   <li>{@link ApnSetting#getMvnoType()}</li>
9408      *   <li>{@link ApnSetting#getProtocol()}</li>
9409      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
9410      * </ul>
9411      *
9412      * @param admin which {@link DeviceAdminReceiver} this request is associated with
9413      * @param apnSetting the override APN to insert
9414      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
9415      *         the database.
9416      * @throws SecurityException if {@code admin} is not a device owner.
9417      *
9418      * @see #setOverrideApnsEnabled(ComponentName, boolean)
9419      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)9420     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
9421         throwIfParentInstance("addOverrideApn");
9422         if (mService != null) {
9423             try {
9424                 return mService.addOverrideApn(admin, apnSetting);
9425             } catch (RemoteException e) {
9426                 throw e.rethrowFromSystemServer();
9427             }
9428         }
9429         return -1;
9430     }
9431 
9432     /**
9433      * Called by device owner to update an override APN.
9434      *
9435      * <p>This method may returns {@code false} if there is no override APN with the given
9436      * {@code apnId}.
9437      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
9438      * existing override APN. Update the existing conflicted APN instead.
9439      * <p>See {@link #addOverrideApn} for the definition of conflict.
9440      *
9441      * @param admin which {@link DeviceAdminReceiver} this request is associated with
9442      * @param apnId the {@code id} of the override APN to update
9443      * @param apnSetting the override APN to update
9444      * @return {@code true} if the required override APN is successfully updated,
9445      *         {@code false} otherwise.
9446      * @throws SecurityException if {@code admin} is not a device owner.
9447      *
9448      * @see #setOverrideApnsEnabled(ComponentName, boolean)
9449      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)9450     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
9451             @NonNull ApnSetting apnSetting) {
9452         throwIfParentInstance("updateOverrideApn");
9453         if (mService != null) {
9454             try {
9455                 return mService.updateOverrideApn(admin, apnId, apnSetting);
9456             } catch (RemoteException e) {
9457                 throw e.rethrowFromSystemServer();
9458             }
9459         }
9460         return false;
9461     }
9462 
9463     /**
9464      * Called by device owner to remove an override APN.
9465      *
9466      * <p>This method may returns {@code false} if there is no override APN with the given
9467      * {@code apnId}.
9468      *
9469      * @param admin which {@link DeviceAdminReceiver} this request is associated with
9470      * @param apnId the {@code id} of the override APN to remove
9471      * @return {@code true} if the required override APN is successfully removed, {@code false}
9472      *         otherwise.
9473      * @throws SecurityException if {@code admin} is not a device owner.
9474      *
9475      * @see #setOverrideApnsEnabled(ComponentName, boolean)
9476      */
removeOverrideApn(@onNull ComponentName admin, int apnId)9477     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
9478         throwIfParentInstance("removeOverrideApn");
9479         if (mService != null) {
9480             try {
9481                 return mService.removeOverrideApn(admin, apnId);
9482             } catch (RemoteException e) {
9483                 throw e.rethrowFromSystemServer();
9484             }
9485         }
9486         return false;
9487     }
9488 
9489     /**
9490      * Called by device owner to get all override APNs inserted by device owner.
9491      *
9492      * @param admin which {@link DeviceAdminReceiver} this request is associated with
9493      * @return A list of override APNs inserted by device owner.
9494      * @throws SecurityException if {@code admin} is not a device owner.
9495      *
9496      * @see #setOverrideApnsEnabled(ComponentName, boolean)
9497      */
getOverrideApns(@onNull ComponentName admin)9498     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
9499         throwIfParentInstance("getOverrideApns");
9500         if (mService != null) {
9501             try {
9502                 return mService.getOverrideApns(admin);
9503             } catch (RemoteException e) {
9504                 throw e.rethrowFromSystemServer();
9505             }
9506         }
9507         return Collections.emptyList();
9508     }
9509 
9510     /**
9511      * Called by device owner to set if override APNs should be enabled.
9512      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
9513      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
9514      * are ignored.
9515      *
9516      * @param admin which {@link DeviceAdminReceiver} this request is associated with
9517      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
9518      * @throws SecurityException if {@code admin} is not a device owner.
9519      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)9520     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
9521         throwIfParentInstance("setOverrideApnEnabled");
9522         if (mService != null) {
9523             try {
9524                 mService.setOverrideApnsEnabled(admin, enabled);
9525             } catch (RemoteException e) {
9526                 throw e.rethrowFromSystemServer();
9527             }
9528         }
9529     }
9530 
9531     /**
9532      * Called by device owner to check if override APNs are currently enabled.
9533      *
9534      * @param admin which {@link DeviceAdminReceiver} this request is associated with
9535      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
9536      * @throws SecurityException if {@code admin} is not a device owner.
9537      *
9538      * @see #setOverrideApnsEnabled(ComponentName, boolean)
9539      */
isOverrideApnEnabled(@onNull ComponentName admin)9540     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
9541         throwIfParentInstance("isOverrideApnEnabled");
9542         if (mService != null) {
9543             try {
9544                 return mService.isOverrideApnEnabled(admin);
9545             } catch (RemoteException e) {
9546                 throw e.rethrowFromSystemServer();
9547             }
9548         }
9549         return false;
9550     }
9551 
9552     /**
9553      * Returns the data passed from the current administrator to the new administrator during an
9554      * ownership transfer. This is the same {@code bundle} passed in
9555      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
9556      * persisted until the profile owner or device owner is removed.
9557      *
9558      * <p>This is the same <code>bundle</code> received in the
9559      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
9560      * Use this method to retrieve it after the transfer as long as the new administrator is the
9561      * active device or profile owner.
9562      *
9563      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
9564      *
9565      * @see #transferOwnership
9566      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
9567      * @throws SecurityException if the caller is not a device or profile owner.
9568      */
9569     @Nullable
getTransferOwnershipBundle()9570     public PersistableBundle getTransferOwnershipBundle() {
9571         throwIfParentInstance("getTransferOwnershipBundle");
9572         try {
9573             return mService.getTransferOwnershipBundle();
9574         } catch (RemoteException re) {
9575             throw re.rethrowFromSystemServer();
9576         }
9577     }
9578 }
9579