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