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