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