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