DevicePolicyManager.java revision 8040fd1b62ee4dbb8ac3941f3666d7fbe6bcd3e6
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     * @hide
1173     */
1174    public static final String POLICY_MANDATORY_BACKUPS = "policy_mandatory_backups";
1175
1176    /**
1177     * Constant to indicate the feature of suspending app. Use it as the value of
1178     * {@link #EXTRA_RESTRICTION}.
1179     * @hide
1180     */
1181    public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
1182
1183    /**
1184     * A String indicating a specific restricted feature. Can be a user restriction from the
1185     * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1186     * {@link #POLICY_DISABLE_CAMERA}, {@link #POLICY_DISABLE_SCREEN_CAPTURE} or
1187     * {@link #POLICY_MANDATORY_BACKUPS}.
1188     * @see #createAdminSupportIntent(String)
1189     * @hide
1190     */
1191    @TestApi
1192    public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1193
1194    /**
1195     * Activity action: have the user enter a new password. This activity should
1196     * be launched after using {@link #setPasswordQuality(ComponentName, int)},
1197     * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
1198     * enter a new password that meets the current requirements. You can use
1199     * {@link #isActivePasswordSufficient()} to determine whether you need to
1200     * have the user select a new password in order to meet the current
1201     * constraints. Upon being resumed from this activity, you can check the new
1202     * password characteristics to see if they are sufficient.
1203     *
1204     * If the intent is launched from within a managed profile with a profile
1205     * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1206     * this will trigger entering a new password for the parent of the profile.
1207     * For all other cases it will trigger entering a new password for the user
1208     * or profile it is launched from.
1209     *
1210     * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1211     */
1212    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1213    public static final String ACTION_SET_NEW_PASSWORD
1214            = "android.app.action.SET_NEW_PASSWORD";
1215
1216    /**
1217     * Activity action: have the user enter a new password for the parent profile.
1218     * If the intent is launched from within a managed profile, this will trigger
1219     * entering a new password for the parent of the profile. In all other cases
1220     * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
1221     */
1222    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1223    public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1224            = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1225
1226    /**
1227     * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1228     * Network logging was enabled and the user tapped the notification.
1229     * <p class="note">This is a protected intent that can only be sent by the system.</p>
1230     * @hide
1231     */
1232    public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1233            = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1234
1235    /**
1236     * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1237     * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1238     * {@link #EXTRA_DELEGATION_SCOPES} key.
1239     *
1240     * <p class=”note”> Note: This is a protected intent that can only be sent by the system.</p>
1241     */
1242    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1243    public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1244            "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1245
1246    /**
1247     * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1248     * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1249     */
1250    public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1251
1252    /**
1253     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1254     * the parent profile to access intents sent from the managed profile.
1255     * That is, when an app in the managed profile calls
1256     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1257     * matching activity in the parent profile.
1258     */
1259    public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1260
1261    /**
1262     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1263     * the managed profile to access intents sent from the parent profile.
1264     * That is, when an app in the parent profile calls
1265     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1266     * matching activity in the managed profile.
1267     */
1268    public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1269
1270    /**
1271     * Broadcast action: notify that a new local system update policy has been set by the device
1272     * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1273     */
1274    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1275    public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1276            = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1277
1278    /**
1279     * Broadcast action to notify ManagedProvisioning that
1280     * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has changed.
1281     * @hide
1282     */
1283    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1284    public static final String ACTION_DATA_SHARING_RESTRICTION_CHANGED =
1285            "android.app.action.DATA_SHARING_RESTRICTION_CHANGED";
1286
1287    /**
1288     * Broadcast action from ManagedProvisioning to notify that the latest change to
1289     * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
1290     * applied (cross profile intent filters updated). Only usesd for CTS tests.
1291     * @hide
1292     */
1293    @TestApi
1294    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1295    public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
1296            "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
1297
1298    /**
1299     * Permission policy to prompt user for new permission requests for runtime permissions.
1300     * Already granted or denied permissions are not affected by this.
1301     */
1302    public static final int PERMISSION_POLICY_PROMPT = 0;
1303
1304    /**
1305     * Permission policy to always grant new permission requests for runtime permissions.
1306     * Already granted or denied permissions are not affected by this.
1307     */
1308    public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1309
1310    /**
1311     * Permission policy to always deny new permission requests for runtime permissions.
1312     * Already granted or denied permissions are not affected by this.
1313     */
1314    public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1315
1316    /**
1317     * Runtime permission state: The user can manage the permission
1318     * through the UI.
1319     */
1320    public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1321
1322    /**
1323     * Runtime permission state: The permission is granted to the app
1324     * and the user cannot manage the permission through the UI.
1325     */
1326    public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1327
1328    /**
1329     * Runtime permission state: The permission is denied to the app
1330     * and the user cannot manage the permission through the UI.
1331     */
1332    public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1333
1334    /**
1335     * Delegation of certificate installation and management. This scope grants access to the
1336     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1337     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1338     */
1339    public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1340
1341    /**
1342     * Delegation of application restrictions management. This scope grants access to the
1343     * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1344     */
1345    public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1346
1347    /**
1348     * Delegation of application uninstall block. This scope grants access to the
1349     * {@link #setUninstallBlocked} API.
1350     */
1351    public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1352
1353    /**
1354     * Delegation of permission policy and permission grant state. This scope grants access to the
1355     * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1356     * and {@link #setPermissionGrantState} APIs.
1357     */
1358    public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1359
1360    /**
1361     * Delegation of package access state. This scope grants access to the
1362     * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1363     * {@link #setPackagesSuspended} APIs.
1364     */
1365    public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1366
1367    /**
1368     * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1369     * API.
1370     */
1371    public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1372
1373    /**
1374     * Delegation for installing existing packages. This scope grants access to the
1375     * {@link #installExistingPackage} API.
1376     */
1377    public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
1378            "delegation-install-existing-package";
1379
1380    /**
1381     * Delegation of management of uninstalled packages. This scope grants access to the
1382     * {@code #setKeepUninstalledPackages} and {@code #getKeepUninstalledPackages} APIs.
1383     */
1384    public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1385            "delegation-keep-uninstalled-packages";
1386
1387    /**
1388     * No management for current user in-effect. This is the default.
1389     * @hide
1390     */
1391    @SystemApi
1392    public static final int STATE_USER_UNMANAGED = 0;
1393
1394    /**
1395     * Management partially setup, user setup needs to be completed.
1396     * @hide
1397     */
1398    @SystemApi
1399    public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1400
1401    /**
1402     * Management partially setup, user setup completed.
1403     * @hide
1404     */
1405    @SystemApi
1406    public static final int STATE_USER_SETUP_COMPLETE = 2;
1407
1408    /**
1409     * Management setup and active on current user.
1410     * @hide
1411     */
1412    @SystemApi
1413    public static final int STATE_USER_SETUP_FINALIZED = 3;
1414
1415    /**
1416     * Management partially setup on a managed profile.
1417     * @hide
1418     */
1419    @SystemApi
1420    public static final int STATE_USER_PROFILE_COMPLETE = 4;
1421
1422    /**
1423     * @hide
1424     */
1425    @IntDef(prefix = { "STATE_USER_" }, value = {
1426            STATE_USER_UNMANAGED,
1427            STATE_USER_SETUP_INCOMPLETE,
1428            STATE_USER_SETUP_COMPLETE,
1429            STATE_USER_SETUP_FINALIZED,
1430            STATE_USER_PROFILE_COMPLETE
1431    })
1432    @Retention(RetentionPolicy.SOURCE)
1433    public @interface UserProvisioningState {}
1434
1435    /**
1436     * Result code for {@link #checkProvisioningPreCondition}.
1437     *
1438     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1439     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1440     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when provisioning is allowed.
1441     *
1442     * @hide
1443     */
1444    public static final int CODE_OK = 0;
1445
1446    /**
1447     * Result code for {@link #checkProvisioningPreCondition}.
1448     *
1449     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1450     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the device already has a device
1451     * owner.
1452     *
1453     * @hide
1454     */
1455    public static final int CODE_HAS_DEVICE_OWNER = 1;
1456
1457    /**
1458     * Result code for {@link #checkProvisioningPreCondition}.
1459     *
1460     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1461     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user has a profile owner and for
1462     * {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
1463     *
1464     * @hide
1465     */
1466    public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
1467
1468    /**
1469     * Result code for {@link #checkProvisioningPreCondition}.
1470     *
1471     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1472     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user isn't running.
1473     *
1474     * @hide
1475     */
1476    public static final int CODE_USER_NOT_RUNNING = 3;
1477
1478    /**
1479     * Result code for {@link #checkProvisioningPreCondition}.
1480     *
1481     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1482     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the device has already been setup and
1483     * for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
1484     *
1485     * @hide
1486     */
1487    public static final int CODE_USER_SETUP_COMPLETED = 4;
1488
1489    /**
1490     * Code used to indicate that the device also has a user other than the system user.
1491     *
1492     * @hide
1493     */
1494    public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
1495
1496    /**
1497     * Code used to indicate that device has an account that prevents provisioning.
1498     *
1499     * @hide
1500     */
1501    public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
1502
1503    /**
1504     * Result code for {@link #checkProvisioningPreCondition}.
1505     *
1506     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1507     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the user is not a system user.
1508     *
1509     * @hide
1510     */
1511    public static final int CODE_NOT_SYSTEM_USER = 7;
1512
1513    /**
1514     * Result code for {@link #checkProvisioningPreCondition}.
1515     *
1516     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1517     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} and {@link #ACTION_PROVISION_MANAGED_USER}
1518     * when the device is a watch and is already paired.
1519     *
1520     * @hide
1521     */
1522    public static final int CODE_HAS_PAIRED = 8;
1523
1524    /**
1525     * Result code for {@link #checkProvisioningPreCondition}.
1526     *
1527     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
1528     * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
1529     *
1530     * @see {@link PackageManager#FEATURE_MANAGED_USERS}
1531     * @hide
1532     */
1533    public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
1534
1535    /**
1536     * Result code for {@link #checkProvisioningPreCondition}.
1537     *
1538     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user.
1539     *
1540     * @hide
1541     */
1542    public static final int CODE_SYSTEM_USER = 10;
1543
1544    /**
1545     * Result code for {@link #checkProvisioningPreCondition}.
1546     *
1547     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
1548     * managed profiles.
1549     *
1550     * @hide
1551     */
1552    public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
1553
1554    /**
1555     * Result code for {@link #checkProvisioningPreCondition}.
1556     *
1557     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} and
1558     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices not running with split system
1559     * user.
1560     *
1561     * @hide
1562     */
1563    public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
1564
1565    /**
1566     * Result code for {@link #checkProvisioningPreCondition}.
1567     *
1568     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1569     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1570     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices which do no support device
1571     * admins.
1572     *
1573     * @hide
1574     */
1575    public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
1576
1577    /**
1578     * Result code for {@link #checkProvisioningPreCondition}.
1579     *
1580     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the device the user is a
1581     * system user on a split system user device.
1582     *
1583     * @hide
1584     */
1585    public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
1586
1587    /**
1588     * Result code for {@link #checkProvisioningPreCondition}.
1589     *
1590     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when adding a managed profile is
1591     * disallowed by {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
1592     *
1593     * @hide
1594     */
1595    public static final int CODE_ADD_MANAGED_PROFILE_DISALLOWED = 15;
1596
1597    /**
1598     * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
1599     * conditions.
1600     *
1601     * @hide
1602     */
1603    @Retention(RetentionPolicy.SOURCE)
1604    @IntDef(prefix = { "CODE_" }, value = {
1605            CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
1606            CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
1607            CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
1608            CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
1609            CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER, CODE_ADD_MANAGED_PROFILE_DISALLOWED
1610    })
1611    public @interface ProvisioningPreCondition {}
1612
1613    /**
1614     * Disable all configurable SystemUI features during LockTask mode. This includes,
1615     * <ul>
1616     *     <li>system info area in the status bar (connectivity icons, clock, etc.)
1617     *     <li>notifications (including alerts, icons, and the notification shade)
1618     *     <li>Home button
1619     *     <li>Recents button and UI
1620     *     <li>global actions menu (i.e. power button menu)
1621     *     <li>keyguard
1622     * </ul>
1623     *
1624     * @see #setLockTaskFeatures(ComponentName, int)
1625     */
1626    public static final int LOCK_TASK_FEATURE_NONE = 0;
1627
1628    /**
1629     * Enable the system info area in the status bar during LockTask mode. The system info area
1630     * usually occupies the right side of the status bar (although this can differ across OEMs). It
1631     * includes all system information indicators, such as date and time, connectivity, battery,
1632     * vibration mode, etc.
1633     *
1634     * @see #setLockTaskFeatures(ComponentName, int)
1635     */
1636    public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
1637
1638    /**
1639     * Enable notifications during LockTask mode. This includes notification icons on the status
1640     * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
1641     * Settings panel remains disabled. This feature flag can only be used in combination with
1642     * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
1643     * throws an {@link IllegalArgumentException} if this feature flag is defined without
1644     * {@link #LOCK_TASK_FEATURE_HOME}.
1645     *
1646     * @see #setLockTaskFeatures(ComponentName, int)
1647     */
1648    public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
1649
1650    /**
1651     * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
1652     * to be registered as the default launcher with
1653     * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
1654     * package needs to be whitelisted for LockTask with
1655     * {@link #setLockTaskPackages(ComponentName, String[])}.
1656     *
1657     * @see #setLockTaskFeatures(ComponentName, int)
1658     */
1659    public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
1660
1661    /**
1662     * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
1663     * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
1664     * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
1665     * {@link IllegalArgumentException} if this feature flag is defined without
1666     * {@link #LOCK_TASK_FEATURE_HOME}.
1667     *
1668     * @see #setLockTaskFeatures(ComponentName, int)
1669     */
1670    public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
1671
1672    /**
1673     * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
1674     * the user long-presses the power button, for example. Note that the user may not be able to
1675     * power off the device if this flag is not set.
1676     *
1677     * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
1678     * called for the first time.
1679     *
1680     * @see #setLockTaskFeatures(ComponentName, int)
1681     */
1682    public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
1683
1684    /**
1685     * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
1686     * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
1687     * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
1688     * credential.
1689     *
1690     * @see #setLockTaskFeatures(ComponentName, int)
1691     */
1692    public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
1693
1694    /**
1695     * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
1696     *
1697     * @hide
1698     */
1699    @Retention(RetentionPolicy.SOURCE)
1700    @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
1701            LOCK_TASK_FEATURE_NONE,
1702            LOCK_TASK_FEATURE_SYSTEM_INFO,
1703            LOCK_TASK_FEATURE_NOTIFICATIONS,
1704            LOCK_TASK_FEATURE_HOME,
1705            LOCK_TASK_FEATURE_OVERVIEW,
1706            LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
1707            LOCK_TASK_FEATURE_KEYGUARD
1708    })
1709    public @interface LockTaskFeature {}
1710
1711    /**
1712     * Service action: Action for a service that device owner and profile owner can optionally
1713     * own.  If a device owner or a profile owner has such a service, the system tries to keep
1714     * a bound connection to it, in order to keep their process always running.
1715     * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
1716     * permission.
1717     */
1718    @SdkConstant(SdkConstantType.SERVICE_ACTION)
1719    public static final String ACTION_DEVICE_ADMIN_SERVICE
1720            = "android.app.action.DEVICE_ADMIN_SERVICE";
1721
1722    /** @hide */
1723    @Retention(RetentionPolicy.SOURCE)
1724    @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
1725        ID_TYPE_BASE_INFO,
1726        ID_TYPE_SERIAL,
1727        ID_TYPE_IMEI,
1728        ID_TYPE_MEID
1729    })
1730    public @interface AttestationIdType {}
1731
1732    /**
1733     * Specifies that the device should attest its manufacturer details. For use with
1734     * {@link #generateKeyPair}.
1735     *
1736     * @see #generateKeyPair
1737     */
1738    public static final int ID_TYPE_BASE_INFO = 1;
1739
1740    /**
1741     * Specifies that the device should attest its serial number. For use with
1742     * {@link #generateKeyPair}.
1743     *
1744     * @see #generateKeyPair
1745     */
1746    public static final int ID_TYPE_SERIAL = 2;
1747
1748    /**
1749     * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
1750     *
1751     * @see #generateKeyPair
1752     */
1753    public static final int ID_TYPE_IMEI = 4;
1754
1755    /**
1756     * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
1757     *
1758     * @see #generateKeyPair
1759     */
1760    public static final int ID_TYPE_MEID = 8;
1761
1762    /**
1763     * Specifies that the calling app should be granted access to the installed credentials
1764     * immediately. Otherwise, access to the credentials will be gated by user approval.
1765     * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
1766     *
1767     * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
1768     */
1769    public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
1770
1771    /**
1772     * Specifies that a user can select the key via the Certificate Selection prompt.
1773     * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
1774     * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
1775     * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
1776     *
1777     * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
1778     */
1779    public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
1780
1781    /**
1782     * Broadcast action: sent when the profile owner is set, changed or cleared.
1783     *
1784     * This broadcast is sent only to the user managed by the new profile owner.
1785     * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1786     */
1787    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1788    public static final String ACTION_PROFILE_OWNER_CHANGED =
1789            "android.app.action.PROFILE_OWNER_CHANGED";
1790
1791    /**
1792     * Return true if the given administrator component is currently active (enabled) in the system.
1793     *
1794     * @param admin The administrator component to check for.
1795     * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
1796     *         otherwise
1797     */
1798    public boolean isAdminActive(@NonNull ComponentName admin) {
1799        throwIfParentInstance("isAdminActive");
1800        return isAdminActiveAsUser(admin, myUserId());
1801    }
1802
1803    /**
1804     * @see #isAdminActive(ComponentName)
1805     * @hide
1806     */
1807    public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
1808        if (mService != null) {
1809            try {
1810                return mService.isAdminActive(admin, userId);
1811            } catch (RemoteException e) {
1812                throw e.rethrowFromSystemServer();
1813            }
1814        }
1815        return false;
1816    }
1817
1818    /**
1819     * Return true if the given administrator component is currently being removed
1820     * for the user.
1821     * @hide
1822     */
1823    public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
1824        if (mService != null) {
1825            try {
1826                return mService.isRemovingAdmin(admin, userId);
1827            } catch (RemoteException e) {
1828                throw e.rethrowFromSystemServer();
1829            }
1830        }
1831        return false;
1832    }
1833
1834    /**
1835     * Return a list of all currently active device administrators' component
1836     * names.  If there are no administrators {@code null} may be
1837     * returned.
1838     */
1839    public @Nullable List<ComponentName> getActiveAdmins() {
1840        throwIfParentInstance("getActiveAdmins");
1841        return getActiveAdminsAsUser(myUserId());
1842    }
1843
1844    /**
1845     * @see #getActiveAdmins()
1846     * @hide
1847     */
1848    public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
1849        if (mService != null) {
1850            try {
1851                return mService.getActiveAdmins(userId);
1852            } catch (RemoteException e) {
1853                throw e.rethrowFromSystemServer();
1854            }
1855        }
1856        return null;
1857    }
1858
1859    /**
1860     * Used by package administration code to determine if a package can be stopped
1861     * or uninstalled.
1862     * @hide
1863     */
1864    @SystemApi
1865    @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1866    public boolean packageHasActiveAdmins(String packageName) {
1867        return packageHasActiveAdmins(packageName, myUserId());
1868    }
1869
1870    /**
1871     * Used by package administration code to determine if a package can be stopped
1872     * or uninstalled.
1873     * @hide
1874     */
1875    public boolean packageHasActiveAdmins(String packageName, int userId) {
1876        if (mService != null) {
1877            try {
1878                return mService.packageHasActiveAdmins(packageName, userId);
1879            } catch (RemoteException e) {
1880                throw e.rethrowFromSystemServer();
1881            }
1882        }
1883        return false;
1884    }
1885
1886    /**
1887     * Remove a current administration component.  This can only be called
1888     * by the application that owns the administration component; if you
1889     * try to remove someone else's component, a security exception will be
1890     * thrown.
1891     *
1892     * <p>Note that the operation is not synchronous and the admin might still be active (as
1893     * indicated by {@link #getActiveAdmins()}) by the time this method returns.
1894     *
1895     * @param admin The administration compononent to remove.
1896     * @throws SecurityException if the caller is not in the owner application of {@code admin}.
1897     */
1898    public void removeActiveAdmin(@NonNull ComponentName admin) {
1899        throwIfParentInstance("removeActiveAdmin");
1900        if (mService != null) {
1901            try {
1902                mService.removeActiveAdmin(admin, myUserId());
1903            } catch (RemoteException e) {
1904                throw e.rethrowFromSystemServer();
1905            }
1906        }
1907    }
1908
1909    /**
1910     * Returns true if an administrator has been granted a particular device policy. This can be
1911     * used to check whether the administrator was activated under an earlier set of policies, but
1912     * requires additional policies after an upgrade.
1913     *
1914     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
1915     *            active administrator, or an exception will be thrown.
1916     * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
1917     * @throws SecurityException if {@code admin} is not an active administrator.
1918     */
1919    public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
1920        throwIfParentInstance("hasGrantedPolicy");
1921        if (mService != null) {
1922            try {
1923                return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
1924            } catch (RemoteException e) {
1925                throw e.rethrowFromSystemServer();
1926            }
1927        }
1928        return false;
1929    }
1930
1931    /**
1932     * Returns true if the Profile Challenge is available to use for the given profile user.
1933     *
1934     * @hide
1935     */
1936    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
1937        if (mService != null) {
1938            try {
1939                return mService.isSeparateProfileChallengeAllowed(userHandle);
1940            } catch (RemoteException e) {
1941                throw e.rethrowFromSystemServer();
1942            }
1943        }
1944        return false;
1945    }
1946
1947    /**
1948     * Constant for {@link #setPasswordQuality}: the policy has no requirements
1949     * for the password.  Note that quality constants are ordered so that higher
1950     * values are more restrictive.
1951     */
1952    public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
1953
1954    /**
1955     * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
1956     * recognition technology.  This implies technologies that can recognize the identity of
1957     * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
1958     * Note that quality constants are ordered so that higher values are more restrictive.
1959     */
1960    public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
1961
1962    /**
1963     * Constant for {@link #setPasswordQuality}: the policy requires some kind
1964     * of password or pattern, but doesn't care what it is. Note that quality constants
1965     * are ordered so that higher values are more restrictive.
1966     */
1967    public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
1968
1969    /**
1970     * Constant for {@link #setPasswordQuality}: the user must have entered a
1971     * password containing at least numeric characters.  Note that quality
1972     * constants are ordered so that higher values are more restrictive.
1973     */
1974    public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
1975
1976    /**
1977     * Constant for {@link #setPasswordQuality}: the user must have entered a
1978     * password containing at least numeric characters with no repeating (4444)
1979     * or ordered (1234, 4321, 2468) sequences.  Note that quality
1980     * constants are ordered so that higher values are more restrictive.
1981     */
1982    public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
1983
1984    /**
1985     * Constant for {@link #setPasswordQuality}: the user must have entered a
1986     * password containing at least alphabetic (or other symbol) characters.
1987     * Note that quality constants are ordered so that higher values are more
1988     * restrictive.
1989     */
1990    public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
1991
1992    /**
1993     * Constant for {@link #setPasswordQuality}: the user must have entered a
1994     * password containing at least <em>both></em> numeric <em>and</em>
1995     * alphabetic (or other symbol) characters.  Note that quality constants are
1996     * ordered so that higher values are more restrictive.
1997     */
1998    public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
1999
2000    /**
2001     * Constant for {@link #setPasswordQuality}: the user must have entered a
2002     * password containing at least a letter, a numerical digit and a special
2003     * symbol, by default. With this password quality, passwords can be
2004     * restricted to contain various sets of characters, like at least an
2005     * uppercase letter, etc. These are specified using various methods,
2006     * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
2007     * that quality constants are ordered so that higher values are more
2008     * restrictive.
2009     */
2010    public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
2011
2012    /**
2013     * Constant for {@link #setPasswordQuality}: the user is not allowed to
2014     * modify password. In case this password quality is set, the password is
2015     * managed by a profile owner. The profile owner can set any password,
2016     * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
2017     * that quality constants are ordered so that higher values are more
2018     * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
2019     * the highest.
2020     * @hide
2021     */
2022    public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
2023
2024    /**
2025     * @hide
2026     *
2027     * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
2028     * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
2029     * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
2030     * used by authenticator to exempt their accounts from this:
2031     *
2032     * <ul>
2033     *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
2034     *     <p>In order to make an apk test-only, add android:testOnly="true" to the
2035     *     &lt;application&gt; tag in the manifest.
2036     *
2037     *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
2038     *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
2039     *     Some authenticators claim to have any features, so to detect it, we also check
2040     *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
2041     *     if any of the accounts have it.
2042     * </ul>
2043     */
2044    @SystemApi
2045    @TestApi
2046    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
2047            "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
2048
2049    /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
2050    @SystemApi
2051    @TestApi
2052    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
2053            "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
2054
2055    /**
2056     * Called by an application that is administering the device to set the password restrictions it
2057     * is imposing. After setting this, the user will not be able to enter a new password that is
2058     * not at least as restrictive as what has been set. Note that the current password will remain
2059     * until the user has set a new one, so the change does not take place immediately. To prompt
2060     * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2061     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
2062     * <p>
2063     * Quality constants are ordered so that higher values are more restrictive; thus the highest
2064     * requested quality constant (between the policy set here, the user's preference, and any other
2065     * considerations) is the one that is in effect.
2066     * <p>
2067     * The calling device admin must have requested
2068     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2069     * not, a security exception will be thrown.
2070     * <p>
2071     * This method can be called on the {@link DevicePolicyManager} instance returned by
2072     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2073     * profile.
2074     *
2075     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2076     * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
2077     *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
2078     *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2079     *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
2080     * @throws SecurityException if {@code admin} is not an active administrator or if {@code admin}
2081     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2082     */
2083    public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
2084        if (mService != null) {
2085            try {
2086                mService.setPasswordQuality(admin, quality, mParentInstance);
2087            } catch (RemoteException e) {
2088                throw e.rethrowFromSystemServer();
2089            }
2090        }
2091    }
2092
2093    /**
2094     * Retrieve the current minimum password quality for a particular admin or all admins that set
2095     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2096     * a separate challenge are not taken into account.
2097     *
2098     * <p>This method can be called on the {@link DevicePolicyManager} instance
2099     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2100     * restrictions on the parent profile.
2101     *
2102     * @param admin The name of the admin component to check, or {@code null} to aggregate
2103     * all admins.
2104     */
2105    public int getPasswordQuality(@Nullable ComponentName admin) {
2106        return getPasswordQuality(admin, myUserId());
2107    }
2108
2109    /** @hide per-user version */
2110    public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
2111        if (mService != null) {
2112            try {
2113                return mService.getPasswordQuality(admin, userHandle, mParentInstance);
2114            } catch (RemoteException e) {
2115                throw e.rethrowFromSystemServer();
2116            }
2117        }
2118        return PASSWORD_QUALITY_UNSPECIFIED;
2119    }
2120
2121    /**
2122     * Called by an application that is administering the device to set the minimum allowed password
2123     * length. After setting this, the user will not be able to enter a new password that is not at
2124     * least as restrictive as what has been set. Note that the current password will remain until
2125     * the user has set a new one, so the change does not take place immediately. To prompt the user
2126     * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2127     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2128     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2129     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2130     * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
2131     * {@link #setPasswordQuality}.
2132     * <p>
2133     * The calling device admin must have requested
2134     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2135     * not, a security exception will be thrown.
2136     * <p>
2137     * This method can be called on the {@link DevicePolicyManager} instance returned by
2138     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2139     * profile.
2140     *
2141     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2142     * @param length The new desired minimum password length. A value of 0 means there is no
2143     *            restriction.
2144     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2145     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2146     */
2147    public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
2148        if (mService != null) {
2149            try {
2150                mService.setPasswordMinimumLength(admin, length, mParentInstance);
2151            } catch (RemoteException e) {
2152                throw e.rethrowFromSystemServer();
2153            }
2154        }
2155    }
2156
2157    /**
2158     * Retrieve the current minimum password length for a particular admin or all admins that set
2159     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2160     * a separate challenge are not taken into account.
2161     *
2162     * <p>This method can be called on the {@link DevicePolicyManager} instance
2163     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2164     * restrictions on the parent profile.
2165     *
2166     * user and its profiles or a particular one.
2167     * @param admin The name of the admin component to check, or {@code null} to aggregate
2168     * all admins.
2169     */
2170    public int getPasswordMinimumLength(@Nullable ComponentName admin) {
2171        return getPasswordMinimumLength(admin, myUserId());
2172    }
2173
2174    /** @hide per-user version */
2175    public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
2176        if (mService != null) {
2177            try {
2178                return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
2179            } catch (RemoteException e) {
2180                throw e.rethrowFromSystemServer();
2181            }
2182        }
2183        return 0;
2184    }
2185
2186    /**
2187     * Called by an application that is administering the device to set the minimum number of upper
2188     * case letters required in the password. After setting this, the user will not be able to enter
2189     * a new password that is not at least as restrictive as what has been set. Note that the
2190     * current password will remain until the user has set a new one, so the change does not take
2191     * place immediately. To prompt the user for a new password, use
2192     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2193     * setting this value. This constraint is only imposed if the administrator has also requested
2194     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2195     * <p>
2196     * The calling device admin must have requested
2197     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2198     * not, a security exception will be thrown.
2199     * <p>
2200     * This method can be called on the {@link DevicePolicyManager} instance returned by
2201     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2202     * profile.
2203     *
2204     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2205     * @param length The new desired minimum number of upper case letters required in the password.
2206     *            A value of 0 means there is no restriction.
2207     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2208     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2209     */
2210    public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
2211        if (mService != null) {
2212            try {
2213                mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
2214            } catch (RemoteException e) {
2215                throw e.rethrowFromSystemServer();
2216            }
2217        }
2218    }
2219
2220    /**
2221     * Retrieve the current number of upper case letters required in the password
2222     * for a particular admin or all admins that set restrictions on this user and
2223     * its participating profiles. Restrictions on profiles that have a separate challenge
2224     * are not taken into account.
2225     * This is the same value as set by
2226     * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
2227     * and only applies when the password quality is
2228     * {@link #PASSWORD_QUALITY_COMPLEX}.
2229     *
2230     * <p>This method can be called on the {@link DevicePolicyManager} instance
2231     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2232     * restrictions on the parent profile.
2233     *
2234     * @param admin The name of the admin component to check, or {@code null} to
2235     *            aggregate all admins.
2236     * @return The minimum number of upper case letters required in the
2237     *         password.
2238     */
2239    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
2240        return getPasswordMinimumUpperCase(admin, myUserId());
2241    }
2242
2243    /** @hide per-user version */
2244    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
2245        if (mService != null) {
2246            try {
2247                return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
2248            } catch (RemoteException e) {
2249                throw e.rethrowFromSystemServer();
2250            }
2251        }
2252        return 0;
2253    }
2254
2255    /**
2256     * Called by an application that is administering the device to set the minimum number of lower
2257     * case letters required in the password. After setting this, the user will not be able to enter
2258     * a new password that is not at least as restrictive as what has been set. Note that the
2259     * current password will remain until the user has set a new one, so the change does not take
2260     * place immediately. To prompt the user for a new password, use
2261     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2262     * setting this value. This constraint is only imposed if the administrator has also requested
2263     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2264     * <p>
2265     * The calling device admin must have requested
2266     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2267     * not, a security exception will be thrown.
2268     * <p>
2269     * This method can be called on the {@link DevicePolicyManager} instance returned by
2270     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2271     * profile.
2272     *
2273     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2274     * @param length The new desired minimum number of lower case letters required in the password.
2275     *            A value of 0 means there is no restriction.
2276     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2277     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2278     */
2279    public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
2280        if (mService != null) {
2281            try {
2282                mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
2283            } catch (RemoteException e) {
2284                throw e.rethrowFromSystemServer();
2285            }
2286        }
2287    }
2288
2289    /**
2290     * Retrieve the current number of lower case letters required in the password
2291     * for a particular admin or all admins that set restrictions on this user
2292     * and its participating profiles. Restrictions on profiles that have
2293     * a separate challenge are not taken into account.
2294     * This is the same value as set by
2295     * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
2296     * and only applies when the password quality is
2297     * {@link #PASSWORD_QUALITY_COMPLEX}.
2298     *
2299     * <p>This method can be called on the {@link DevicePolicyManager} instance
2300     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2301     * restrictions on the parent profile.
2302     *
2303     * @param admin The name of the admin component to check, or {@code null} to
2304     *            aggregate all admins.
2305     * @return The minimum number of lower case letters required in the
2306     *         password.
2307     */
2308    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
2309        return getPasswordMinimumLowerCase(admin, myUserId());
2310    }
2311
2312    /** @hide per-user version */
2313    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
2314        if (mService != null) {
2315            try {
2316                return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
2317            } catch (RemoteException e) {
2318                throw e.rethrowFromSystemServer();
2319            }
2320        }
2321        return 0;
2322    }
2323
2324    /**
2325     * Called by an application that is administering the device to set the minimum number of
2326     * letters required in the password. After setting this, the user will not be able to enter a
2327     * new password that is not at least as restrictive as what has been set. Note that the current
2328     * password will remain until the user has set a new one, so the change does not take place
2329     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2330     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2331     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2332     * {@link #setPasswordQuality}. The default value is 1.
2333     * <p>
2334     * The calling device admin must have requested
2335     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2336     * not, a security exception will be thrown.
2337     * <p>
2338     * This method can be called on the {@link DevicePolicyManager} instance returned by
2339     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2340     * profile.
2341     *
2342     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2343     * @param length The new desired minimum number of letters required in the password. A value of
2344     *            0 means there is no restriction.
2345     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2346     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2347     */
2348    public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
2349        if (mService != null) {
2350            try {
2351                mService.setPasswordMinimumLetters(admin, length, mParentInstance);
2352            } catch (RemoteException e) {
2353                throw e.rethrowFromSystemServer();
2354            }
2355        }
2356    }
2357
2358    /**
2359     * Retrieve the current number of letters required in the password
2360     * for a particular admin or all admins that set restrictions on this user
2361     * and its participating profiles. Restrictions on profiles that have
2362     * a separate challenge are not taken into account.
2363     * This is the same value as set by
2364     * {@link #setPasswordMinimumLetters(ComponentName, int)}
2365     * and only applies when the password quality is
2366     * {@link #PASSWORD_QUALITY_COMPLEX}.
2367     *
2368     * <p>This method can be called on the {@link DevicePolicyManager} instance
2369     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2370     * restrictions on the parent profile.
2371     *
2372     * @param admin The name of the admin component to check, or {@code null} to
2373     *            aggregate all admins.
2374     * @return The minimum number of letters required in the password.
2375     */
2376    public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
2377        return getPasswordMinimumLetters(admin, myUserId());
2378    }
2379
2380    /** @hide per-user version */
2381    public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
2382        if (mService != null) {
2383            try {
2384                return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
2385            } catch (RemoteException e) {
2386                throw e.rethrowFromSystemServer();
2387            }
2388        }
2389        return 0;
2390    }
2391
2392    /**
2393     * Called by an application that is administering the device to set the minimum number of
2394     * numerical digits required in the password. After setting this, the user will not be able to
2395     * enter a new password that is not at least as restrictive as what has been set. Note that the
2396     * current password will remain until the user has set a new one, so the change does not take
2397     * place immediately. To prompt the user for a new password, use
2398     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2399     * setting this value. This constraint is only imposed if the administrator has also requested
2400     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 1.
2401     * <p>
2402     * The calling device admin must have requested
2403     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2404     * not, a security exception will be thrown.
2405     * <p>
2406     * This method can be called on the {@link DevicePolicyManager} instance returned by
2407     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2408     * profile.
2409     *
2410     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2411     * @param length The new desired minimum number of numerical digits required in the password. A
2412     *            value of 0 means there is no restriction.
2413     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2414     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2415     */
2416    public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
2417        if (mService != null) {
2418            try {
2419                mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
2420            } catch (RemoteException e) {
2421                throw e.rethrowFromSystemServer();
2422            }
2423        }
2424    }
2425
2426    /**
2427     * Retrieve the current number of numerical digits required in the password
2428     * for a particular admin or all admins that set restrictions on this user
2429     * and its participating profiles. Restrictions on profiles that have
2430     * a separate challenge are not taken into account.
2431     * This is the same value as set by
2432     * {@link #setPasswordMinimumNumeric(ComponentName, int)}
2433     * and only applies when the password quality is
2434     * {@link #PASSWORD_QUALITY_COMPLEX}.
2435     *
2436     * <p>This method can be called on the {@link DevicePolicyManager} instance
2437     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2438     * restrictions on the parent profile.
2439     *
2440     * @param admin The name of the admin component to check, or {@code null} to
2441     *            aggregate all admins.
2442     * @return The minimum number of numerical digits required in the password.
2443     */
2444    public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
2445        return getPasswordMinimumNumeric(admin, myUserId());
2446    }
2447
2448    /** @hide per-user version */
2449    public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
2450        if (mService != null) {
2451            try {
2452                return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
2453            } catch (RemoteException e) {
2454                throw e.rethrowFromSystemServer();
2455            }
2456        }
2457        return 0;
2458    }
2459
2460    /**
2461     * Called by an application that is administering the device to set the minimum number of
2462     * symbols required in the password. After setting this, the user will not be able to enter a
2463     * new password that is not at least as restrictive as what has been set. Note that the current
2464     * password will remain until the user has set a new one, so the change does not take place
2465     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2466     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2467     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2468     * {@link #setPasswordQuality}. The default value is 1.
2469     * <p>
2470     * The calling device admin must have requested
2471     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2472     * not, a security exception will be thrown.
2473     * <p>
2474     * This method can be called on the {@link DevicePolicyManager} instance returned by
2475     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2476     * profile.
2477     *
2478     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2479     * @param length The new desired minimum number of symbols required in the password. A value of
2480     *            0 means there is no restriction.
2481     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2482     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2483     */
2484    public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
2485        if (mService != null) {
2486            try {
2487                mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
2488            } catch (RemoteException e) {
2489                throw e.rethrowFromSystemServer();
2490            }
2491        }
2492    }
2493
2494    /**
2495     * Retrieve the current number of symbols required in the password
2496     * for a particular admin or all admins that set restrictions on this user
2497     * and its participating profiles. Restrictions on profiles that have
2498     * a separate challenge are not taken into account. This is the same value as
2499     * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
2500     * and only applies when the password quality is
2501     * {@link #PASSWORD_QUALITY_COMPLEX}.
2502     *
2503     * <p>This method can be called on the {@link DevicePolicyManager} instance
2504     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2505     * restrictions on the parent profile.
2506     *
2507     * @param admin The name of the admin component to check, or {@code null} to
2508     *            aggregate all admins.
2509     * @return The minimum number of symbols required in the password.
2510     */
2511    public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
2512        return getPasswordMinimumSymbols(admin, myUserId());
2513    }
2514
2515    /** @hide per-user version */
2516    public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
2517        if (mService != null) {
2518            try {
2519                return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
2520            } catch (RemoteException e) {
2521                throw e.rethrowFromSystemServer();
2522            }
2523        }
2524        return 0;
2525    }
2526
2527    /**
2528     * Called by an application that is administering the device to set the minimum number of
2529     * non-letter characters (numerical digits or symbols) required in the password. After setting
2530     * this, the user will not be able to enter a new password that is not at least as restrictive
2531     * as what has been set. Note that the current password will remain until the user has set a new
2532     * one, so the change does not take place immediately. To prompt the user for a new password,
2533     * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2534     * setting this value. This constraint is only imposed if the administrator has also requested
2535     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2536     * <p>
2537     * The calling device admin must have requested
2538     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2539     * not, a security exception will be thrown.
2540     * <p>
2541     * This method can be called on the {@link DevicePolicyManager} instance returned by
2542     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2543     * profile.
2544     *
2545     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2546     * @param length The new desired minimum number of letters required in the password. A value of
2547     *            0 means there is no restriction.
2548     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2549     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2550     */
2551    public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
2552        if (mService != null) {
2553            try {
2554                mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
2555            } catch (RemoteException e) {
2556                throw e.rethrowFromSystemServer();
2557            }
2558        }
2559    }
2560
2561    /**
2562     * Retrieve the current number of non-letter characters required in the password
2563     * for a particular admin or all admins that set restrictions on this user
2564     * and its participating profiles. Restrictions on profiles that have
2565     * a separate challenge are not taken into account.
2566     * This is the same value as set by
2567     * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
2568     * and only applies when the password quality is
2569     * {@link #PASSWORD_QUALITY_COMPLEX}.
2570     *
2571     * <p>This method can be called on the {@link DevicePolicyManager} instance
2572     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2573     * restrictions on the parent profile.
2574     *
2575     * @param admin The name of the admin component to check, or {@code null} to
2576     *            aggregate all admins.
2577     * @return The minimum number of letters required in the password.
2578     */
2579    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
2580        return getPasswordMinimumNonLetter(admin, myUserId());
2581    }
2582
2583    /** @hide per-user version */
2584    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
2585        if (mService != null) {
2586            try {
2587                return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
2588            } catch (RemoteException e) {
2589                throw e.rethrowFromSystemServer();
2590            }
2591        }
2592        return 0;
2593    }
2594
2595    /**
2596     * Called by an application that is administering the device to set the length of the password
2597     * history. After setting this, the user will not be able to enter a new password that is the
2598     * same as any password in the history. Note that the current password will remain until the
2599     * user has set a new one, so the change does not take place immediately. To prompt the user for
2600     * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2601     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2602     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2603     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX} {@link #PASSWORD_QUALITY_ALPHABETIC}, or
2604     * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
2605     * <p>
2606     * The calling device admin must have requested
2607     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2608     * not, a security exception will be thrown.
2609     * <p>
2610     * This method can be called on the {@link DevicePolicyManager} instance returned by
2611     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2612     * profile.
2613     *
2614     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2615     * @param length The new desired length of password history. A value of 0 means there is no
2616     *            restriction.
2617     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2618     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2619     */
2620    public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
2621        if (mService != null) {
2622            try {
2623                mService.setPasswordHistoryLength(admin, length, mParentInstance);
2624            } catch (RemoteException e) {
2625                throw e.rethrowFromSystemServer();
2626            }
2627        }
2628    }
2629
2630    /**
2631     * Called by a device admin to set the password expiration timeout. Calling this method will
2632     * restart the countdown for password expiration for the given admin, as will changing the
2633     * device password (for all admins).
2634     * <p>
2635     * The provided timeout is the time delta in ms and will be added to the current time. For
2636     * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
2637     * 432000000 ms for timeout.
2638     * <p>
2639     * To disable password expiration, a value of 0 may be used for timeout.
2640     * <p>
2641     * The calling device admin must have requested
2642     * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
2643     * not, a security exception will be thrown.
2644     * <p>
2645     * Note that setting the password will automatically reset the expiration time for all active
2646     * admins. Active admins do not need to explicitly call this method in that case.
2647     * <p>
2648     * This method can be called on the {@link DevicePolicyManager} instance returned by
2649     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2650     * profile.
2651     *
2652     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2653     * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
2654     *            there is no restriction (unlimited).
2655     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2656     *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
2657     */
2658    public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
2659        if (mService != null) {
2660            try {
2661                mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
2662            } catch (RemoteException e) {
2663                throw e.rethrowFromSystemServer();
2664            }
2665        }
2666    }
2667
2668    /**
2669     * Get the password expiration timeout for the given admin. The expiration timeout is the
2670     * recurring expiration timeout provided in the call to
2671     * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
2672     * aggregate of all participating policy administrators if {@code admin} is null. Admins that
2673     * have set restrictions on profiles that have a separate challenge are not taken into account.
2674     *
2675     * <p>This method can be called on the {@link DevicePolicyManager} instance
2676     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2677     * restrictions on the parent profile.
2678     *
2679     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2680     * @return The timeout for the given admin or the minimum of all timeouts
2681     */
2682    public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
2683        if (mService != null) {
2684            try {
2685                return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
2686            } catch (RemoteException e) {
2687                throw e.rethrowFromSystemServer();
2688            }
2689        }
2690        return 0;
2691    }
2692
2693    /**
2694     * Get the current password expiration time for a particular admin or all admins that set
2695     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2696     * a separate challenge are not taken into account. If admin is {@code null}, then a composite
2697     * of all expiration times is returned - which will be the minimum of all of them.
2698     *
2699     * <p>This method can be called on the {@link DevicePolicyManager} instance
2700     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2701     * the password expiration for the parent profile.
2702     *
2703     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2704     * @return The password expiration time, in milliseconds since epoch.
2705     */
2706    public long getPasswordExpiration(@Nullable ComponentName admin) {
2707        if (mService != null) {
2708            try {
2709                return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
2710            } catch (RemoteException e) {
2711                throw e.rethrowFromSystemServer();
2712            }
2713        }
2714        return 0;
2715    }
2716
2717    /**
2718     * Retrieve the current password history length for a particular admin or all admins that
2719     * set restrictions on this user and its participating profiles. Restrictions on profiles that
2720     * have a separate challenge are not taken into account.
2721     *
2722     * <p>This method can be called on the {@link DevicePolicyManager} instance
2723     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2724     * restrictions on the parent profile.
2725     *
2726     * @param admin The name of the admin component to check, or {@code null} to aggregate
2727     * all admins.
2728     * @return The length of the password history
2729     */
2730    public int getPasswordHistoryLength(@Nullable ComponentName admin) {
2731        return getPasswordHistoryLength(admin, myUserId());
2732    }
2733
2734    /** @hide per-user version */
2735    public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
2736        if (mService != null) {
2737            try {
2738                return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
2739            } catch (RemoteException e) {
2740                throw e.rethrowFromSystemServer();
2741            }
2742        }
2743        return 0;
2744    }
2745
2746    /**
2747     * Return the maximum password length that the device supports for a
2748     * particular password quality.
2749     * @param quality The quality being interrogated.
2750     * @return Returns the maximum length that the user can enter.
2751     */
2752    public int getPasswordMaximumLength(int quality) {
2753        // Kind-of arbitrary.
2754        return 16;
2755    }
2756
2757    /**
2758     * Determine whether the current password the user has set is sufficient to meet the policy
2759     * requirements (e.g. quality, minimum length) that have been requested by the admins of this
2760     * user and its participating profiles. Restrictions on profiles that have a separate challenge
2761     * are not taken into account. The user must be unlocked in order to perform the check.
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>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
4070     * the user to select the key from a dialog.
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     * Returns {@code true} if the device supports attestation of device identifiers in addition
4223     * to key attestation.
4224     * @return {@code true} if Device ID attestation is supported.
4225     */
4226    public boolean isDeviceIdAttestationSupported() {
4227        PackageManager pm = mContext.getPackageManager();
4228        return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
4229    }
4230
4231    /**
4232     * Called by a device or profile owner, or delegated certificate installer, to associate
4233     * certificates with a key pair that was generated using {@link #generateKeyPair}, and
4234     * set whether the key is available for the user to choose in the certificate selection
4235     * prompt.
4236     *
4237     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4238     *            {@code null} if calling from a delegated certificate installer.
4239     * @param alias The private key alias under which to install the certificate. The {@code alias}
4240     *        should denote an existing private key. If a certificate with that alias already
4241     *        exists, it will be overwritten.
4242     * @param certs The certificate chain to install. The chain should start with the leaf
4243     *        certificate and include the chain of trust in order. This will be returned by
4244     *        {@link android.security.KeyChain#getCertificateChain}.
4245     * @param isUserSelectable {@code true} to indicate that a user can select this key via the
4246     *        certificate selection prompt, {@code false} to indicate that this key can only be
4247     *        granted access by implementing
4248     *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
4249     * @return {@code true} if the provided {@code alias} exists and the certificates has been
4250     *        successfully associated with it, {@code false} otherwise.
4251     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4252     *         owner, or {@code admin} is null but the calling application is not a delegated
4253     *         certificate installer.
4254     */
4255    public boolean setKeyPairCertificate(@Nullable ComponentName admin,
4256            @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
4257        throwIfParentInstance("setKeyPairCertificate");
4258        try {
4259            final byte[] pemCert = Credentials.convertToPem(certs.get(0));
4260            byte[] pemChain = null;
4261            if (certs.size() > 1) {
4262                pemChain = Credentials.convertToPem(
4263                        certs.subList(1, certs.size()).toArray(new Certificate[0]));
4264            }
4265            return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
4266                    pemChain, isUserSelectable);
4267        } catch (RemoteException e) {
4268            throw e.rethrowFromSystemServer();
4269        } catch (CertificateException | IOException e) {
4270            Log.w(TAG, "Could not pem-encode certificate", e);
4271        }
4272        return false;
4273    }
4274
4275
4276    /**
4277     * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
4278     * doesn't exist.
4279     */
4280    private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
4281        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4282        final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
4283                              new ByteArrayInputStream(certBuffer));
4284        return new TrustedCertificateStore().getCertificateAlias(cert);
4285    }
4286
4287    /**
4288     * Called by a profile owner or device owner to grant access to privileged certificate
4289     * manipulation APIs to a third-party certificate installer app. Granted APIs include
4290     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
4291     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
4292     * <p>
4293     * Delegated certificate installer is a per-user state. The delegated access is persistent until
4294     * it is later cleared by calling this method with a null value or uninstallling the certificate
4295     * installer.
4296     * <p>
4297     * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
4298     * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
4299     * supplied certificate installer package must be installed when calling this API, otherwise an
4300     * {@link IllegalArgumentException} will be thrown.
4301     *
4302     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4303     * @param installerPackage The package name of the certificate installer which will be given
4304     *            access. If {@code null} is given the current package will be cleared.
4305     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4306     *
4307     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
4308     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
4309     */
4310    @Deprecated
4311    public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
4312            installerPackage) throws SecurityException {
4313        throwIfParentInstance("setCertInstallerPackage");
4314        if (mService != null) {
4315            try {
4316                mService.setCertInstallerPackage(admin, installerPackage);
4317            } catch (RemoteException e) {
4318                throw e.rethrowFromSystemServer();
4319            }
4320        }
4321    }
4322
4323    /**
4324     * Called by a profile owner or device owner to retrieve the certificate installer for the user,
4325     * or {@code null} if none is set. If there are multiple delegates this function will return one
4326     * of them.
4327     *
4328     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4329     * @return The package name of the current delegated certificate installer, or {@code null} if
4330     *         none is set.
4331     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4332     *
4333     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
4334     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
4335     */
4336    @Deprecated
4337    public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
4338            throws SecurityException {
4339        throwIfParentInstance("getCertInstallerPackage");
4340        if (mService != null) {
4341            try {
4342                return mService.getCertInstallerPackage(admin);
4343            } catch (RemoteException e) {
4344                throw e.rethrowFromSystemServer();
4345            }
4346        }
4347        return null;
4348    }
4349
4350    /**
4351     * Called by a profile owner or device owner to grant access to privileged APIs to another app.
4352     * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
4353     * constants.
4354     * <p>
4355     * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
4356     * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
4357     * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
4358     * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
4359     * <p>
4360     * Delegated scopes are a per-user state. The delegated access is persistent until it is later
4361     * cleared by calling this method with an empty {@code scopes} list or uninstalling the
4362     * {@code delegatePackage}.
4363     *
4364     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4365     * @param delegatePackage The package name of the app which will be given access.
4366     * @param scopes The groups of privileged APIs whose access should be granted to
4367     *            {@code delegatedPackage}.
4368     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4369     */
4370     public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
4371            @NonNull List<String> scopes) {
4372        throwIfParentInstance("setDelegatedScopes");
4373        if (mService != null) {
4374            try {
4375                mService.setDelegatedScopes(admin, delegatePackage, scopes);
4376            } catch (RemoteException e) {
4377                throw e.rethrowFromSystemServer();
4378            }
4379        }
4380    }
4381
4382    /**
4383     * Called by a profile owner or device owner to retrieve a list of the scopes given to a
4384     * delegate package. Other apps can use this method to retrieve their own delegated scopes by
4385     * passing {@code null} for {@code admin} and their own package name as
4386     * {@code delegatedPackage}.
4387     *
4388     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4389     *            {@code null} if the caller is {@code delegatedPackage}.
4390     * @param delegatedPackage The package name of the app whose scopes should be retrieved.
4391     * @return A list containing the scopes given to {@code delegatedPackage}.
4392     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4393     */
4394     @NonNull
4395     public List<String> getDelegatedScopes(@Nullable ComponentName admin,
4396             @NonNull String delegatedPackage) {
4397         throwIfParentInstance("getDelegatedScopes");
4398         if (mService != null) {
4399             try {
4400                 return mService.getDelegatedScopes(admin, delegatedPackage);
4401             } catch (RemoteException e) {
4402                 throw e.rethrowFromSystemServer();
4403             }
4404         }
4405         return null;
4406    }
4407
4408    /**
4409     * Called by a profile owner or device owner to retrieve a list of delegate packages that were
4410     * granted a delegation scope.
4411     *
4412     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4413     * @param delegationScope The scope whose delegates should be retrieved.
4414     * @return A list of package names of the current delegated packages for
4415               {@code delegationScope}.
4416     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4417     */
4418     @Nullable
4419     public List<String> getDelegatePackages(@NonNull ComponentName admin,
4420             @NonNull String delegationScope) {
4421        throwIfParentInstance("getDelegatePackages");
4422        if (mService != null) {
4423            try {
4424                return mService.getDelegatePackages(admin, delegationScope);
4425            } catch (RemoteException e) {
4426                throw e.rethrowFromSystemServer();
4427            }
4428        }
4429        return null;
4430    }
4431
4432    /**
4433     * Called by a device or profile owner to configure an always-on VPN connection through a
4434     * specific application for the current user. This connection is automatically granted and
4435     * persisted after a reboot.
4436     * <p>
4437     * To support the always-on feature, an app must
4438     * <ul>
4439     *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
4440     *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
4441     *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
4442     *     <li><i>not</i> explicitly opt out of the feature through
4443     *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
4444     * </ul>
4445     * The call will fail if called with the package name of an unsupported VPN app.
4446     *
4447     * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
4448     *        remove an existing always-on VPN configuration.
4449     * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
4450     *        {@code false} otherwise. This carries the risk that any failure of the VPN provider
4451     *        could break networking for all apps. This has no effect when clearing.
4452     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4453     * @throws NameNotFoundException if {@code vpnPackage} is not installed.
4454     * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
4455     *         set as always-on, or if always-on VPN is not available.
4456     */
4457    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
4458            boolean lockdownEnabled)
4459            throws NameNotFoundException, UnsupportedOperationException {
4460        throwIfParentInstance("setAlwaysOnVpnPackage");
4461        if (mService != null) {
4462            try {
4463                if (!mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled)) {
4464                    throw new NameNotFoundException(vpnPackage);
4465                }
4466            } catch (RemoteException e) {
4467                throw e.rethrowFromSystemServer();
4468            }
4469        }
4470    }
4471
4472    /**
4473     * Called by a device or profile owner to read the name of the package administering an
4474     * always-on VPN connection for the current user. If there is no such package, or the always-on
4475     * VPN is provided by the system instead of by an application, {@code null} will be returned.
4476     *
4477     * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
4478     *         is set.
4479     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4480     */
4481    public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
4482        throwIfParentInstance("getAlwaysOnVpnPackage");
4483        if (mService != null) {
4484            try {
4485                return mService.getAlwaysOnVpnPackage(admin);
4486            } catch (RemoteException e) {
4487                throw e.rethrowFromSystemServer();
4488            }
4489        }
4490        return null;
4491    }
4492
4493    /**
4494     * Called by an application that is administering the device to disable all cameras on the
4495     * device, for this user. After setting this, no applications running as this user will be able
4496     * to access any cameras on the device.
4497     * <p>
4498     * If the caller is device owner, then the restriction will be applied to all users.
4499     * <p>
4500     * The calling device admin must have requested
4501     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
4502     * not, a security exception will be thrown.
4503     *
4504     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4505     * @param disabled Whether or not the camera should be disabled.
4506     * @throws SecurityException if {@code admin} is not an active administrator or does not use
4507     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
4508     */
4509    public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
4510        throwIfParentInstance("setCameraDisabled");
4511        if (mService != null) {
4512            try {
4513                mService.setCameraDisabled(admin, disabled);
4514            } catch (RemoteException e) {
4515                throw e.rethrowFromSystemServer();
4516            }
4517        }
4518    }
4519
4520    /**
4521     * Determine whether or not the device's cameras have been disabled for this user,
4522     * either by the calling admin, if specified, or all admins.
4523     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4524     * have disabled the camera
4525     */
4526    public boolean getCameraDisabled(@Nullable ComponentName admin) {
4527        throwIfParentInstance("getCameraDisabled");
4528        return getCameraDisabled(admin, myUserId());
4529    }
4530
4531    /** @hide per-user version */
4532    public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
4533        if (mService != null) {
4534            try {
4535                return mService.getCameraDisabled(admin, userHandle);
4536            } catch (RemoteException e) {
4537                throw e.rethrowFromSystemServer();
4538            }
4539        }
4540        return false;
4541    }
4542
4543    /**
4544     * Called by a device owner to request a bugreport.
4545     * <p>
4546     * If the device contains secondary users or profiles, they must be affiliated with the device.
4547     * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
4548     *
4549     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4550     * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
4551     *         wasn't triggered because a previous bugreport operation is still active (either the
4552     *         bugreport is still running or waiting for the user to share or decline)
4553     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
4554     *         profile or secondary user that is not affiliated with the device.
4555     * @see #isAffiliatedUser
4556     */
4557    public boolean requestBugreport(@NonNull ComponentName admin) {
4558        throwIfParentInstance("requestBugreport");
4559        if (mService != null) {
4560            try {
4561                return mService.requestBugreport(admin);
4562            } catch (RemoteException e) {
4563                throw e.rethrowFromSystemServer();
4564            }
4565        }
4566        return false;
4567    }
4568
4569    /**
4570     * Determine whether or not creating a guest user has been disabled for the device
4571     *
4572     * @hide
4573     */
4574    public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
4575        // Currently guest users can always be created if multi-user is enabled
4576        // TODO introduce a policy for guest user creation
4577        return false;
4578    }
4579
4580    /**
4581     * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
4582     * screen capture also prevents the content from being shown on display devices that do not have
4583     * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
4584     * secure surfaces and secure displays.
4585     * <p>
4586     * The calling device admin must be a device or profile owner. If it is not, a security
4587     * exception will be thrown.
4588     * <p>
4589     * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
4590     * assist requests for all activities of the relevant user.
4591     *
4592     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4593     * @param disabled Whether screen capture is disabled or not.
4594     * @throws SecurityException if {@code admin} is not a device or profile owner.
4595     */
4596    public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
4597        throwIfParentInstance("setScreenCaptureDisabled");
4598        if (mService != null) {
4599            try {
4600                mService.setScreenCaptureDisabled(admin, disabled);
4601            } catch (RemoteException e) {
4602                throw e.rethrowFromSystemServer();
4603            }
4604        }
4605    }
4606
4607    /**
4608     * Determine whether or not screen capture has been disabled by the calling
4609     * admin, if specified, or all admins.
4610     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4611     * have disabled screen capture.
4612     */
4613    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
4614        throwIfParentInstance("getScreenCaptureDisabled");
4615        return getScreenCaptureDisabled(admin, myUserId());
4616    }
4617
4618    /** @hide per-user version */
4619    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
4620        if (mService != null) {
4621            try {
4622                return mService.getScreenCaptureDisabled(admin, userHandle);
4623            } catch (RemoteException e) {
4624                throw e.rethrowFromSystemServer();
4625            }
4626        }
4627        return false;
4628    }
4629
4630    /**
4631     * Called by a device or profile owner to set whether auto time is required. If auto time is
4632     * required, no user will be able set the date and time and network date and time will be used.
4633     * <p>
4634     * Note: if auto time is required the user can still manually set the time zone.
4635     * <p>
4636     * The calling device admin must be a device or profile owner. If it is not, a security
4637     * exception will be thrown.
4638     *
4639     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4640     * @param required Whether auto time is set required or not.
4641     * @throws SecurityException if {@code admin} is not a device owner.
4642     */
4643    public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
4644        throwIfParentInstance("setAutoTimeRequired");
4645        if (mService != null) {
4646            try {
4647                mService.setAutoTimeRequired(admin, required);
4648            } catch (RemoteException e) {
4649                throw e.rethrowFromSystemServer();
4650            }
4651        }
4652    }
4653
4654    /**
4655     * @return true if auto time is required.
4656     */
4657    public boolean getAutoTimeRequired() {
4658        throwIfParentInstance("getAutoTimeRequired");
4659        if (mService != null) {
4660            try {
4661                return mService.getAutoTimeRequired();
4662            } catch (RemoteException e) {
4663                throw e.rethrowFromSystemServer();
4664            }
4665        }
4666        return false;
4667    }
4668
4669    /**
4670     * Called by a device owner to set whether all users created on the device should be ephemeral.
4671     * <p>
4672     * The system user is exempt from this policy - it is never ephemeral.
4673     * <p>
4674     * The calling device admin must be the device owner. If it is not, a security exception will be
4675     * thrown.
4676     *
4677     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4678     * @param forceEphemeralUsers If true, all the existing users will be deleted and all
4679     *            subsequently created users will be ephemeral.
4680     * @throws SecurityException if {@code admin} is not a device owner.
4681     * @hide
4682     */
4683    public void setForceEphemeralUsers(
4684            @NonNull ComponentName admin, boolean forceEphemeralUsers) {
4685        throwIfParentInstance("setForceEphemeralUsers");
4686        if (mService != null) {
4687            try {
4688                mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
4689            } catch (RemoteException e) {
4690                throw e.rethrowFromSystemServer();
4691            }
4692        }
4693    }
4694
4695    /**
4696     * @return true if all users are created ephemeral.
4697     * @throws SecurityException if {@code admin} is not a device owner.
4698     * @hide
4699     */
4700    public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
4701        throwIfParentInstance("getForceEphemeralUsers");
4702        if (mService != null) {
4703            try {
4704                return mService.getForceEphemeralUsers(admin);
4705            } catch (RemoteException e) {
4706                throw e.rethrowFromSystemServer();
4707            }
4708        }
4709        return false;
4710    }
4711
4712    /**
4713     * Called by an application that is administering the device to disable keyguard customizations,
4714     * such as widgets. After setting this, keyguard features will be disabled according to the
4715     * provided feature list.
4716     * <p>
4717     * The calling device admin must have requested
4718     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
4719     * if it has not, a security exception will be thrown.
4720     * <p>
4721     * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
4722     * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
4723     * profile owner of a managed profile can set:
4724     * <ul>
4725     * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
4726     * is no separate challenge set on the managed profile.
4727     * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT} which affects the managed profile challenge if
4728     * there is one, or the parent user otherwise.
4729     * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
4730     * by applications in the managed profile.
4731     * </ul>
4732     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and {@link #KEYGUARD_DISABLE_FINGERPRINT} can also be
4733     * set on the {@link DevicePolicyManager} instance returned by
4734     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4735     * profile.
4736     * <p>
4737     * Requests to disable other features on a managed profile will be ignored.
4738     * <p>
4739     * The admin can check which features have been disabled by calling
4740     * {@link #getKeyguardDisabledFeatures(ComponentName)}
4741     *
4742     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4743     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
4744     *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
4745     *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
4746     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
4747     *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
4748     *            {@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
4749     * @throws SecurityException if {@code admin} is not an active administrator or does not user
4750     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
4751     */
4752    public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
4753        if (mService != null) {
4754            try {
4755                mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
4756            } catch (RemoteException e) {
4757                throw e.rethrowFromSystemServer();
4758            }
4759        }
4760    }
4761
4762    /**
4763     * Determine whether or not features have been disabled in keyguard either by the calling
4764     * admin, if specified, or all admins that set restrictions on this user and its participating
4765     * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
4766     *
4767     * <p>This method can be called on the {@link DevicePolicyManager} instance
4768     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4769     * restrictions on the parent profile.
4770     *
4771     * @param admin The name of the admin component to check, or {@code null} to check whether any
4772     * admins have disabled features in keyguard.
4773     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
4774     * for a list.
4775     */
4776    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
4777        return getKeyguardDisabledFeatures(admin, myUserId());
4778    }
4779
4780    /** @hide per-user version */
4781    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
4782        if (mService != null) {
4783            try {
4784                return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
4785            } catch (RemoteException e) {
4786                throw e.rethrowFromSystemServer();
4787            }
4788        }
4789        return KEYGUARD_DISABLE_FEATURES_NONE;
4790    }
4791
4792    /**
4793     * @hide
4794     */
4795    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
4796            int userHandle) {
4797        if (mService != null) {
4798            try {
4799                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
4800            } catch (RemoteException e) {
4801                throw e.rethrowFromSystemServer();
4802            }
4803        }
4804    }
4805
4806    /**
4807     * @hide
4808     */
4809    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
4810        setActiveAdmin(policyReceiver, refreshing, myUserId());
4811    }
4812
4813    /**
4814     * @hide
4815     */
4816    public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
4817        if (mService != null) {
4818            try {
4819                mService.getRemoveWarning(admin, result, myUserId());
4820            } catch (RemoteException e) {
4821                throw e.rethrowFromSystemServer();
4822            }
4823        }
4824    }
4825
4826    /**
4827     * @hide
4828     */
4829    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
4830        if (mService != null) {
4831            try {
4832                mService.setActivePasswordState(metrics, userHandle);
4833            } catch (RemoteException e) {
4834                throw e.rethrowFromSystemServer();
4835            }
4836        }
4837    }
4838
4839    /**
4840     * @hide
4841     */
4842    public void reportPasswordChanged(@UserIdInt int userId) {
4843        if (mService != null) {
4844            try {
4845                mService.reportPasswordChanged(userId);
4846            } catch (RemoteException e) {
4847                throw e.rethrowFromSystemServer();
4848            }
4849        }
4850    }
4851
4852    /**
4853     * @hide
4854     */
4855    public void reportFailedPasswordAttempt(int userHandle) {
4856        if (mService != null) {
4857            try {
4858                mService.reportFailedPasswordAttempt(userHandle);
4859            } catch (RemoteException e) {
4860                throw e.rethrowFromSystemServer();
4861            }
4862        }
4863    }
4864
4865    /**
4866     * @hide
4867     */
4868    public void reportSuccessfulPasswordAttempt(int userHandle) {
4869        if (mService != null) {
4870            try {
4871                mService.reportSuccessfulPasswordAttempt(userHandle);
4872            } catch (RemoteException e) {
4873                throw e.rethrowFromSystemServer();
4874            }
4875        }
4876    }
4877
4878    /**
4879     * @hide
4880     */
4881    public void reportFailedFingerprintAttempt(int userHandle) {
4882        if (mService != null) {
4883            try {
4884                mService.reportFailedFingerprintAttempt(userHandle);
4885            } catch (RemoteException e) {
4886                throw e.rethrowFromSystemServer();
4887            }
4888        }
4889    }
4890
4891    /**
4892     * @hide
4893     */
4894    public void reportSuccessfulFingerprintAttempt(int userHandle) {
4895        if (mService != null) {
4896            try {
4897                mService.reportSuccessfulFingerprintAttempt(userHandle);
4898            } catch (RemoteException e) {
4899                throw e.rethrowFromSystemServer();
4900            }
4901        }
4902    }
4903
4904    /**
4905     * Should be called when keyguard has been dismissed.
4906     * @hide
4907     */
4908    public void reportKeyguardDismissed(int userHandle) {
4909        if (mService != null) {
4910            try {
4911                mService.reportKeyguardDismissed(userHandle);
4912            } catch (RemoteException e) {
4913                throw e.rethrowFromSystemServer();
4914            }
4915        }
4916    }
4917
4918    /**
4919     * Should be called when keyguard view has been shown to the user.
4920     * @hide
4921     */
4922    public void reportKeyguardSecured(int userHandle) {
4923        if (mService != null) {
4924            try {
4925                mService.reportKeyguardSecured(userHandle);
4926            } catch (RemoteException e) {
4927                throw e.rethrowFromSystemServer();
4928            }
4929        }
4930    }
4931
4932    /**
4933     * @hide
4934     * Sets the given package as the device owner.
4935     * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
4936     * @param who the component name to be registered as device owner.
4937     * @return whether the package was successfully registered as the device owner.
4938     * @throws IllegalArgumentException if the package name is null or invalid
4939     * @throws IllegalStateException If the preconditions mentioned are not met.
4940     */
4941    public boolean setDeviceOwner(ComponentName who) {
4942        return setDeviceOwner(who, null);
4943    }
4944
4945    /**
4946     * @hide
4947     */
4948    public boolean setDeviceOwner(ComponentName who, int userId)  {
4949        return setDeviceOwner(who, null, userId);
4950    }
4951
4952    /**
4953     * @hide
4954     */
4955    public boolean setDeviceOwner(ComponentName who, String ownerName) {
4956        return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
4957    }
4958
4959    /**
4960     * @hide
4961     * Sets the given package as the device owner. The package must already be installed. There
4962     * must not already be a device owner.
4963     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
4964     * this method.
4965     * Calling this after the setup phase of the primary user has completed is allowed only if
4966     * the caller is the shell uid, and there are no additional users and no accounts.
4967     * @param who the component name to be registered as device owner.
4968     * @param ownerName the human readable name of the institution that owns this device.
4969     * @param userId ID of the user on which the device owner runs.
4970     * @return whether the package was successfully registered as the device owner.
4971     * @throws IllegalArgumentException if the package name is null or invalid
4972     * @throws IllegalStateException If the preconditions mentioned are not met.
4973     */
4974    public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
4975            throws IllegalArgumentException, IllegalStateException {
4976        if (mService != null) {
4977            try {
4978                return mService.setDeviceOwner(who, ownerName, userId);
4979            } catch (RemoteException re) {
4980                throw re.rethrowFromSystemServer();
4981            }
4982        }
4983        return false;
4984    }
4985
4986    /**
4987     * Used to determine if a particular package has been registered as a Device Owner app.
4988     * A device owner app is a special device admin that cannot be deactivated by the user, once
4989     * activated as a device admin. It also cannot be uninstalled. To check whether a particular
4990     * package is currently registered as the device owner app, pass in the package name from
4991     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
4992     * admin apps that want to check whether they are also registered as the device owner app. The
4993     * exact mechanism by which a device admin app is registered as a device owner app is defined by
4994     * the setup process.
4995     * @param packageName the package name of the app, to compare with the registered device owner
4996     * app, if any.
4997     * @return whether or not the package is registered as the device owner app.
4998     */
4999    public boolean isDeviceOwnerApp(String packageName) {
5000        throwIfParentInstance("isDeviceOwnerApp");
5001        return isDeviceOwnerAppOnCallingUser(packageName);
5002    }
5003
5004    /**
5005     * @return true if a package is registered as device owner, only when it's running on the
5006     * calling user.
5007     *
5008     * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
5009     * @hide
5010     */
5011    public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
5012        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
5013    }
5014
5015    /**
5016     * @return true if a package is registered as device owner, even if it's running on a different
5017     * user.
5018     *
5019     * <p>Requires the MANAGE_USERS permission.
5020     *
5021     * @hide
5022     */
5023    public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
5024        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
5025    }
5026
5027    /**
5028     * @return device owner component name, only when it's running on the calling user.
5029     *
5030     * @hide
5031     */
5032    public ComponentName getDeviceOwnerComponentOnCallingUser() {
5033        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
5034    }
5035
5036    /**
5037     * @return device owner component name, even if it's running on a different user.
5038     *
5039     * @hide
5040     */
5041    @SystemApi
5042    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5043    public ComponentName getDeviceOwnerComponentOnAnyUser() {
5044        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
5045    }
5046
5047    private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
5048        if (packageName == null) {
5049            return false;
5050        }
5051        final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
5052        if (deviceOwner == null) {
5053            return false;
5054        }
5055        return packageName.equals(deviceOwner.getPackageName());
5056    }
5057
5058    private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
5059        if (mService != null) {
5060            try {
5061                return mService.getDeviceOwnerComponent(callingUserOnly);
5062            } catch (RemoteException re) {
5063                throw re.rethrowFromSystemServer();
5064            }
5065        }
5066        return null;
5067    }
5068
5069    /**
5070     * @return ID of the user who runs device owner, or {@link UserHandle#USER_NULL} if there's
5071     * no device owner.
5072     *
5073     * <p>Requires the MANAGE_USERS permission.
5074     *
5075     * @hide
5076     */
5077    public int getDeviceOwnerUserId() {
5078        if (mService != null) {
5079            try {
5080                return mService.getDeviceOwnerUserId();
5081            } catch (RemoteException re) {
5082                throw re.rethrowFromSystemServer();
5083            }
5084        }
5085        return UserHandle.USER_NULL;
5086    }
5087
5088    /**
5089     * Clears the current device owner. The caller must be the device owner. This function should be
5090     * used cautiously as once it is called it cannot be undone. The device owner can only be set as
5091     * a part of device setup, before it completes.
5092     * <p>
5093     * While some policies previously set by the device owner will be cleared by this method, it is
5094     * a best-effort process and some other policies will still remain in place after the device
5095     * owner is cleared.
5096     *
5097     * @param packageName The package name of the device owner.
5098     * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
5099     *             does not own the current device owner component.
5100     *
5101     * @deprecated This method is expected to be used for testing purposes only. The device owner
5102     * will lose control of the device and its data after calling it. In order to protect any
5103     * sensitive data that remains on the device, it is advised that the device owner factory resets
5104     * the device instead of calling this method. See {@link #wipeData(int)}.
5105     */
5106    @Deprecated
5107    public void clearDeviceOwnerApp(String packageName) {
5108        throwIfParentInstance("clearDeviceOwnerApp");
5109        if (mService != null) {
5110            try {
5111                mService.clearDeviceOwner(packageName);
5112            } catch (RemoteException re) {
5113                throw re.rethrowFromSystemServer();
5114            }
5115        }
5116    }
5117
5118    /**
5119     * Returns the device owner package name, only if it's running on the calling user.
5120     *
5121     * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
5122     *
5123     * @hide
5124     */
5125    @SystemApi
5126    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5127    public @Nullable String getDeviceOwner() {
5128        throwIfParentInstance("getDeviceOwner");
5129        final ComponentName name = getDeviceOwnerComponentOnCallingUser();
5130        return name != null ? name.getPackageName() : null;
5131    }
5132
5133    /**
5134     * Called by the system to find out whether the device is managed by a Device Owner.
5135     *
5136     * @return whether the device is managed by a Device Owner.
5137     * @throws SecurityException if the caller is not the device owner, does not hold the
5138     *         MANAGE_USERS permission and is not the system.
5139     *
5140     * @hide
5141     */
5142    @SystemApi
5143    @TestApi
5144    @SuppressLint("Doclava125")
5145    public boolean isDeviceManaged() {
5146        try {
5147            return mService.hasDeviceOwner();
5148        } catch (RemoteException re) {
5149            throw re.rethrowFromSystemServer();
5150        }
5151    }
5152
5153    /**
5154     * Returns the device owner name.  Note this method *will* return the device owner
5155     * name when it's running on a different user.
5156     *
5157     * @hide
5158     */
5159    @SystemApi
5160    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5161    public String getDeviceOwnerNameOnAnyUser() {
5162        throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
5163        if (mService != null) {
5164            try {
5165                return mService.getDeviceOwnerName();
5166            } catch (RemoteException re) {
5167                throw re.rethrowFromSystemServer();
5168            }
5169        }
5170        return null;
5171    }
5172
5173    /**
5174     * @hide
5175     * @deprecated Do not use
5176     * @removed
5177     */
5178    @Deprecated
5179    @SystemApi
5180    @SuppressLint("Doclava125")
5181    public @Nullable String getDeviceInitializerApp() {
5182        return null;
5183    }
5184
5185    /**
5186     * @hide
5187     * @deprecated Do not use
5188     * @removed
5189     */
5190    @Deprecated
5191    @SystemApi
5192    @SuppressLint("Doclava125")
5193    public @Nullable ComponentName getDeviceInitializerComponent() {
5194        return null;
5195    }
5196
5197    /**
5198     * @hide
5199     * @deprecated Use #ACTION_SET_PROFILE_OWNER
5200     * Sets the given component as an active admin and registers the package as the profile
5201     * owner for this user. The package must already be installed and there shouldn't be
5202     * an existing profile owner registered for this user. Also, this method must be called
5203     * before the user setup has been completed.
5204     * <p>
5205     * This method can only be called by system apps that hold MANAGE_USERS permission and
5206     * MANAGE_DEVICE_ADMINS permission.
5207     * @param admin The component to register as an active admin and profile owner.
5208     * @param ownerName The user-visible name of the entity that is managing this user.
5209     * @return whether the admin was successfully registered as the profile owner.
5210     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
5211     *         the user has already been set up.
5212     */
5213    @Deprecated
5214    @SystemApi
5215    @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
5216    public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
5217            throws IllegalArgumentException {
5218        throwIfParentInstance("setActiveProfileOwner");
5219        if (mService != null) {
5220            try {
5221                final int myUserId = myUserId();
5222                mService.setActiveAdmin(admin, false, myUserId);
5223                return mService.setProfileOwner(admin, ownerName, myUserId);
5224            } catch (RemoteException re) {
5225                throw re.rethrowFromSystemServer();
5226            }
5227        }
5228        return false;
5229    }
5230
5231    /**
5232     * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
5233     * a SecurityException will be thrown. This method is not available to managed profile owners.
5234     * <p>
5235     * While some policies previously set by the profile owner will be cleared by this method, it is
5236     * a best-effort process and some other policies will still remain in place after the profile
5237     * owner is cleared.
5238     *
5239     * @param admin The component to remove as the profile owner.
5240     * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
5241     * being called from a managed profile.
5242     *
5243     * @deprecated This method is expected to be used for testing purposes only. The profile owner
5244     * will lose control of the user and its data after calling it. In order to protect any
5245     * sensitive data that remains on this user, it is advised that the profile owner deletes it
5246     * instead of calling this method. See {@link #wipeData(int)}.
5247     */
5248    @Deprecated
5249    public void clearProfileOwner(@NonNull ComponentName admin) {
5250        throwIfParentInstance("clearProfileOwner");
5251        if (mService != null) {
5252            try {
5253                mService.clearProfileOwner(admin);
5254            } catch (RemoteException re) {
5255                throw re.rethrowFromSystemServer();
5256            }
5257        }
5258    }
5259
5260    /**
5261     * @hide
5262     * Checks whether the user was already setup.
5263     */
5264    public boolean hasUserSetupCompleted() {
5265        if (mService != null) {
5266            try {
5267                return mService.hasUserSetupCompleted();
5268            } catch (RemoteException re) {
5269                throw re.rethrowFromSystemServer();
5270            }
5271        }
5272        return true;
5273    }
5274
5275    /**
5276     * @hide
5277     * Sets the given component as the profile owner of the given user profile. The package must
5278     * already be installed. There must not already be a profile owner for this user.
5279     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
5280     * this method.
5281     * Calling this after the setup phase of the specified user has completed is allowed only if:
5282     * - the caller is SYSTEM_UID.
5283     * - or the caller is the shell uid, and there are no accounts on the specified user.
5284     * @param admin the component name to be registered as profile owner.
5285     * @param ownerName the human readable name of the organisation associated with this DPM.
5286     * @param userHandle the userId to set the profile owner for.
5287     * @return whether the component was successfully registered as the profile owner.
5288     * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
5289     * preconditions mentioned are not met.
5290     */
5291    public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
5292            int userHandle) throws IllegalArgumentException {
5293        if (mService != null) {
5294            try {
5295                if (ownerName == null) {
5296                    ownerName = "";
5297                }
5298                return mService.setProfileOwner(admin, ownerName, userHandle);
5299            } catch (RemoteException re) {
5300                throw re.rethrowFromSystemServer();
5301            }
5302        }
5303        return false;
5304    }
5305
5306    /**
5307     * Sets the device owner information to be shown on the lock screen.
5308     * <p>
5309     * If the device owner information is {@code null} or empty then the device owner info is
5310     * cleared and the user owner info is shown on the lock screen if it is set.
5311     * <p>
5312     * If the device owner information contains only whitespaces then the message on the lock screen
5313     * will be blank and the user will not be allowed to change it.
5314     * <p>
5315     * If the device owner information needs to be localized, it is the responsibility of the
5316     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
5317     * and set a new version of this string accordingly.
5318     *
5319     * @param admin The name of the admin component to check.
5320     * @param info Device owner information which will be displayed instead of the user owner info.
5321     * @throws SecurityException if {@code admin} is not a device owner.
5322     */
5323    public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
5324        throwIfParentInstance("setDeviceOwnerLockScreenInfo");
5325        if (mService != null) {
5326            try {
5327                mService.setDeviceOwnerLockScreenInfo(admin, info);
5328            } catch (RemoteException re) {
5329                throw re.rethrowFromSystemServer();
5330            }
5331        }
5332    }
5333
5334    /**
5335     * @return The device owner information. If it is not set returns {@code null}.
5336     */
5337    public CharSequence getDeviceOwnerLockScreenInfo() {
5338        throwIfParentInstance("getDeviceOwnerLockScreenInfo");
5339        if (mService != null) {
5340            try {
5341                return mService.getDeviceOwnerLockScreenInfo();
5342            } catch (RemoteException re) {
5343                throw re.rethrowFromSystemServer();
5344            }
5345        }
5346        return null;
5347    }
5348
5349    /**
5350     * Called by device or profile owners to suspend packages for this user. This function can be
5351     * called by a device owner, profile owner, or by a delegate given the
5352     * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
5353     * <p>
5354     * A suspended package will not be able to start activities. Its notifications will be hidden,
5355     * it will not show up in recents, will not be able to show toasts or dialogs or ring the
5356     * device.
5357     * <p>
5358     * The package must already be installed. If the package is uninstalled while suspended the
5359     * package will no longer be suspended. The admin can block this by using
5360     * {@link #setUninstallBlocked}.
5361     *
5362     * @param admin The name of the admin component to check, or {@code null} if the caller is a
5363     *            package access delegate.
5364     * @param packageNames The package names to suspend or unsuspend.
5365     * @param suspended If set to {@code true} than the packages will be suspended, if set to
5366     *            {@code false} the packages will be unsuspended.
5367     * @return an array of package names for which the suspended status is not set as requested in
5368     *         this method.
5369     * @throws SecurityException if {@code admin} is not a device or profile owner.
5370     * @see #setDelegatedScopes
5371     * @see #DELEGATION_PACKAGE_ACCESS
5372     */
5373    public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
5374            @NonNull String[] packageNames, boolean suspended) {
5375        throwIfParentInstance("setPackagesSuspended");
5376        if (mService != null) {
5377            try {
5378                return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
5379                        suspended);
5380            } catch (RemoteException re) {
5381                throw re.rethrowFromSystemServer();
5382            }
5383        }
5384        return packageNames;
5385    }
5386
5387    /**
5388     * Determine if a package is suspended. This function can be called by a device owner, profile
5389     * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
5390     * {@link #setDelegatedScopes}.
5391     *
5392     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5393     *            {@code null} if the caller is a package access delegate.
5394     * @param packageName The name of the package to retrieve the suspended status of.
5395     * @return {@code true} if the package is suspended or {@code false} if the package is not
5396     *         suspended, could not be found or an error occurred.
5397     * @throws SecurityException if {@code admin} is not a device or profile owner.
5398     * @throws NameNotFoundException if the package could not be found.
5399     * @see #setDelegatedScopes
5400     * @see #DELEGATION_PACKAGE_ACCESS
5401     */
5402    public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
5403            throws NameNotFoundException {
5404        throwIfParentInstance("isPackageSuspended");
5405        if (mService != null) {
5406            try {
5407                return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
5408            } catch (RemoteException e) {
5409                throw e.rethrowFromSystemServer();
5410            } catch (IllegalArgumentException ex) {
5411                throw new NameNotFoundException(packageName);
5412            }
5413        }
5414        return false;
5415    }
5416
5417    /**
5418     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
5419     * be used. Only the profile owner can call this.
5420     *
5421     * @see #isProfileOwnerApp
5422     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5423     * @throws SecurityException if {@code admin} is not a profile owner.
5424     */
5425    public void setProfileEnabled(@NonNull ComponentName admin) {
5426        throwIfParentInstance("setProfileEnabled");
5427        if (mService != null) {
5428            try {
5429                mService.setProfileEnabled(admin);
5430            } catch (RemoteException e) {
5431                throw e.rethrowFromSystemServer();
5432            }
5433        }
5434    }
5435
5436    /**
5437     * Sets the name of the profile. In the device owner case it sets the name of the user which it
5438     * is called from. Only a profile owner or device owner can call this. If this is never called
5439     * by the profile or device owner, the name will be set to default values.
5440     *
5441     * @see #isProfileOwnerApp
5442     * @see #isDeviceOwnerApp
5443     * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
5444     * @param profileName The name of the profile.
5445     * @throws SecurityException if {@code admin} is not a device or profile owner.
5446     */
5447    public void setProfileName(@NonNull ComponentName admin, String profileName) {
5448        throwIfParentInstance("setProfileName");
5449        if (mService != null) {
5450            try {
5451                mService.setProfileName(admin, profileName);
5452            } catch (RemoteException e) {
5453                throw e.rethrowFromSystemServer();
5454            }
5455        }
5456    }
5457
5458    /**
5459     * Used to determine if a particular package is registered as the profile owner for the
5460     * user. A profile owner is a special device admin that has additional privileges
5461     * within the profile.
5462     *
5463     * @param packageName The package name of the app to compare with the registered profile owner.
5464     * @return Whether or not the package is registered as the profile owner.
5465     */
5466    public boolean isProfileOwnerApp(String packageName) {
5467        throwIfParentInstance("isProfileOwnerApp");
5468        if (mService != null) {
5469            try {
5470                ComponentName profileOwner = mService.getProfileOwner(myUserId());
5471                return profileOwner != null
5472                        && profileOwner.getPackageName().equals(packageName);
5473            } catch (RemoteException re) {
5474                throw re.rethrowFromSystemServer();
5475            }
5476        }
5477        return false;
5478    }
5479
5480    /**
5481     * @hide
5482     * @return the packageName of the owner of the given user profile or {@code null} if no profile
5483     * owner has been set for that user.
5484     * @throws IllegalArgumentException if the userId is invalid.
5485     */
5486    @SystemApi
5487    public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
5488        throwIfParentInstance("getProfileOwner");
5489        return getProfileOwnerAsUser(mContext.getUserId());
5490    }
5491
5492    /**
5493     * @see #getProfileOwner()
5494     * @hide
5495     */
5496    public @Nullable ComponentName getProfileOwnerAsUser(final int userId)
5497            throws IllegalArgumentException {
5498        if (mService != null) {
5499            try {
5500                return mService.getProfileOwner(userId);
5501            } catch (RemoteException re) {
5502                throw re.rethrowFromSystemServer();
5503            }
5504        }
5505        return null;
5506    }
5507
5508    /**
5509     * @hide
5510     * @return the human readable name of the organisation associated with this DPM or {@code null}
5511     *         if one is not set.
5512     * @throws IllegalArgumentException if the userId is invalid.
5513     */
5514    public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
5515        if (mService != null) {
5516            try {
5517                return mService.getProfileOwnerName(mContext.getUserId());
5518            } catch (RemoteException re) {
5519                throw re.rethrowFromSystemServer();
5520            }
5521        }
5522        return null;
5523    }
5524
5525    /**
5526     * @hide
5527     * @param userId The user for whom to fetch the profile owner name, if any.
5528     * @return the human readable name of the organisation associated with this profile owner or
5529     *         null if one is not set.
5530     * @throws IllegalArgumentException if the userId is invalid.
5531     */
5532    @SystemApi
5533    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5534    public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
5535        throwIfParentInstance("getProfileOwnerNameAsUser");
5536        if (mService != null) {
5537            try {
5538                return mService.getProfileOwnerName(userId);
5539            } catch (RemoteException re) {
5540                throw re.rethrowFromSystemServer();
5541            }
5542        }
5543        return null;
5544    }
5545
5546    /**
5547     * Called by a profile owner or device owner to set a default activity that the system selects
5548     * to handle intents that match the given {@link IntentFilter}. This activity will remain the
5549     * default intent handler even if the set of potential event handlers for the intent filter
5550     * changes and if the intent preferences are reset.
5551     * <p>
5552     * Note that the caller should still declare the activity in the manifest, the API just sets
5553     * the activity to be the default one to handle the given intent filter.
5554     * <p>
5555     * The default disambiguation mechanism takes over if the activity is not installed (anymore).
5556     * When the activity is (re)installed, it is automatically reset as default intent handler for
5557     * the filter.
5558     * <p>
5559     * The calling device admin must be a profile owner or device owner. If it is not, a security
5560     * exception will be thrown.
5561     *
5562     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5563     * @param filter The IntentFilter for which a default handler is added.
5564     * @param activity The Activity that is added as default intent handler.
5565     * @throws SecurityException if {@code admin} is not a device or profile owner.
5566     */
5567    public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
5568            @NonNull ComponentName activity) {
5569        throwIfParentInstance("addPersistentPreferredActivity");
5570        if (mService != null) {
5571            try {
5572                mService.addPersistentPreferredActivity(admin, filter, activity);
5573            } catch (RemoteException e) {
5574                throw e.rethrowFromSystemServer();
5575            }
5576        }
5577    }
5578
5579    /**
5580     * Called by a profile owner or device owner to remove all persistent intent handler preferences
5581     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
5582     * <p>
5583     * The calling device admin must be a profile owner. If it is not, a security exception will be
5584     * thrown.
5585     *
5586     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5587     * @param packageName The name of the package for which preferences are removed.
5588     * @throws SecurityException if {@code admin} is not a device or profile owner.
5589     */
5590    public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
5591            String packageName) {
5592        throwIfParentInstance("clearPackagePersistentPreferredActivities");
5593        if (mService != null) {
5594            try {
5595                mService.clearPackagePersistentPreferredActivities(admin, packageName);
5596            } catch (RemoteException e) {
5597                throw e.rethrowFromSystemServer();
5598            }
5599        }
5600    }
5601
5602    /**
5603     * Called by a device owner to set the default SMS application.
5604     * <p>
5605     * The calling device admin must be a device owner. If it is not, a security exception will be
5606     * thrown.
5607     *
5608     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5609     * @param packageName The name of the package to set as the default SMS application.
5610     * @throws SecurityException if {@code admin} is not a device owner.
5611     *
5612     * @hide
5613     */
5614    public void setDefaultSmsApplication(@NonNull ComponentName admin, String packageName) {
5615        throwIfParentInstance("setDefaultSmsApplication");
5616        if (mService != null) {
5617            try {
5618                mService.setDefaultSmsApplication(admin, packageName);
5619            } catch (RemoteException e) {
5620                throw e.rethrowFromSystemServer();
5621            }
5622        }
5623    }
5624
5625    /**
5626     * Called by a profile owner or device owner to grant permission to a package to manage
5627     * application restrictions for the calling user via {@link #setApplicationRestrictions} and
5628     * {@link #getApplicationRestrictions}.
5629     * <p>
5630     * This permission is persistent until it is later cleared by calling this method with a
5631     * {@code null} value or uninstalling the managing package.
5632     * <p>
5633     * The supplied application restriction managing package must be installed when calling this
5634     * API, otherwise an {@link NameNotFoundException} will be thrown.
5635     *
5636     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5637     * @param packageName The package name which will be given access to application restrictions
5638     *            APIs. If {@code null} is given the current package will be cleared.
5639     * @throws SecurityException if {@code admin} is not a device or profile owner.
5640     * @throws NameNotFoundException if {@code packageName} is not found
5641     *
5642     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5643     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5644     */
5645    @Deprecated
5646    public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
5647            @Nullable String packageName) throws NameNotFoundException {
5648        throwIfParentInstance("setApplicationRestrictionsManagingPackage");
5649        if (mService != null) {
5650            try {
5651                if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
5652                    throw new NameNotFoundException(packageName);
5653                }
5654            } catch (RemoteException e) {
5655                throw e.rethrowFromSystemServer();
5656            }
5657        }
5658    }
5659
5660    /**
5661     * Called by a profile owner or device owner to retrieve the application restrictions managing
5662     * package for the current user, or {@code null} if none is set. If there are multiple
5663     * delegates this function will return one of them.
5664     *
5665     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5666     * @return The package name allowed to manage application restrictions on the current user, or
5667     *         {@code null} if none is set.
5668     * @throws SecurityException if {@code admin} is not a device or profile owner.
5669     *
5670     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5671     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5672     */
5673    @Deprecated
5674    @Nullable
5675    public String getApplicationRestrictionsManagingPackage(
5676            @NonNull ComponentName admin) {
5677        throwIfParentInstance("getApplicationRestrictionsManagingPackage");
5678        if (mService != null) {
5679            try {
5680                return mService.getApplicationRestrictionsManagingPackage(admin);
5681            } catch (RemoteException e) {
5682                throw e.rethrowFromSystemServer();
5683            }
5684        }
5685        return null;
5686    }
5687
5688    /**
5689     * Called by any application to find out whether it has been granted permission via
5690     * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
5691     * for the calling user.
5692     *
5693     * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
5694     * that method.
5695     *
5696     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
5697     * instead.
5698     */
5699    @Deprecated
5700    public boolean isCallerApplicationRestrictionsManagingPackage() {
5701        throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
5702        if (mService != null) {
5703            try {
5704                return mService.isCallerApplicationRestrictionsManagingPackage(
5705                        mContext.getPackageName());
5706            } catch (RemoteException e) {
5707                throw e.rethrowFromSystemServer();
5708            }
5709        }
5710        return false;
5711    }
5712
5713    /**
5714     * Sets the application restrictions for a given target application running in the calling user.
5715     * <p>
5716     * The caller must be a profile or device owner on that user, or the package allowed to manage
5717     * application restrictions via {@link #setDelegatedScopes} with the
5718     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
5719     * <p>
5720     * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
5721     * <ul>
5722     * <li>{@code boolean}
5723     * <li>{@code int}
5724     * <li>{@code String} or {@code String[]}
5725     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
5726     * </ul>
5727     * <p>
5728     * If the restrictions are not available yet, but may be applied in the near future, the caller
5729     * can notify the target application of that by adding
5730     * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
5731     * <p>
5732     * The application restrictions are only made visible to the target application via
5733     * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
5734     * owner, and the application restrictions managing package via
5735     * {@link #getApplicationRestrictions}.
5736     *
5737     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
5738     *
5739     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5740     *            {@code null} if called by the application restrictions managing package.
5741     * @param packageName The name of the package to update restricted settings for.
5742     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
5743     *            set of active restrictions.
5744     * @throws SecurityException if {@code admin} is not a device or profile owner.
5745     * @see #setDelegatedScopes
5746     * @see #DELEGATION_APP_RESTRICTIONS
5747     * @see UserManager#KEY_RESTRICTIONS_PENDING
5748     */
5749    @WorkerThread
5750    public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
5751            Bundle settings) {
5752        throwIfParentInstance("setApplicationRestrictions");
5753        if (mService != null) {
5754            try {
5755                mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
5756                        settings);
5757            } catch (RemoteException e) {
5758                throw e.rethrowFromSystemServer();
5759            }
5760        }
5761    }
5762
5763    /**
5764     * Sets a list of configuration features to enable for a trust agent component. This is meant to
5765     * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
5766     * agents but those enabled by this function call. If flag
5767     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
5768     * <p>
5769     * For any specific trust agent, whether it is disabled or not depends on the aggregated state
5770     * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
5771     * configuration as set by this function call. In particular: if any admin sets
5772     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
5773     * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
5774     * will receive the list of configurations from all admins who set
5775     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
5776     * behavior. The exact meaning of aggregation is trust-agent-specific.
5777     * <p>
5778     * The calling device admin must have requested
5779     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
5780     * if not, a security exception will be thrown.
5781     * <p>
5782     * This method can be called on the {@link DevicePolicyManager} instance returned by
5783     * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
5784     * the parent profile.
5785     *
5786     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5787     * @param target Component name of the agent to be configured.
5788     * @param configuration Trust-agent-specific feature configuration bundle. Please consult
5789     *        documentation of the specific trust agent to determine the interpretation of this
5790     *        bundle.
5791     * @throws SecurityException if {@code admin} is not an active administrator or does not use
5792     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
5793     */
5794    public void setTrustAgentConfiguration(@NonNull ComponentName admin,
5795            @NonNull ComponentName target, PersistableBundle configuration) {
5796        if (mService != null) {
5797            try {
5798                mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
5799            } catch (RemoteException e) {
5800                throw e.rethrowFromSystemServer();
5801            }
5802        }
5803    }
5804
5805    /**
5806     * Gets configuration for the given trust agent based on aggregating all calls to
5807     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
5808     * all device admins.
5809     * <p>
5810     * This method can be called on the {@link DevicePolicyManager} instance returned by
5811     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
5812     * on the parent profile.
5813     *
5814     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
5815     * this function returns a list of configurations for all admins that declare
5816     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
5817     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
5818     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
5819     * for this {@param agent} or calls it with a null configuration, null is returned.
5820     * @param agent Which component to get enabled features for.
5821     * @return configuration for the given trust agent.
5822     */
5823    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5824            @Nullable ComponentName admin, @NonNull ComponentName agent) {
5825        return getTrustAgentConfiguration(admin, agent, myUserId());
5826    }
5827
5828    /** @hide per-user version */
5829    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5830            @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
5831        if (mService != null) {
5832            try {
5833                return mService.getTrustAgentConfiguration(admin, agent, userHandle,
5834                        mParentInstance);
5835            } catch (RemoteException e) {
5836                throw e.rethrowFromSystemServer();
5837            }
5838        }
5839        return new ArrayList<PersistableBundle>(); // empty list
5840    }
5841
5842    /**
5843     * Called by a profile owner of a managed profile to set whether caller-Id information from the
5844     * managed profile will be shown in the parent profile, for incoming calls.
5845     * <p>
5846     * The calling device admin must be a profile owner. If it is not, a security exception will be
5847     * thrown.
5848     *
5849     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5850     * @param disabled If true caller-Id information in the managed profile is not displayed.
5851     * @throws SecurityException if {@code admin} is not a profile owner.
5852     */
5853    public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
5854        throwIfParentInstance("setCrossProfileCallerIdDisabled");
5855        if (mService != null) {
5856            try {
5857                mService.setCrossProfileCallerIdDisabled(admin, disabled);
5858            } catch (RemoteException e) {
5859                throw e.rethrowFromSystemServer();
5860            }
5861        }
5862    }
5863
5864    /**
5865     * Called by a profile owner of a managed profile to determine whether or not caller-Id
5866     * information has been disabled.
5867     * <p>
5868     * The calling device admin must be a profile owner. If it is not, a security exception will be
5869     * thrown.
5870     *
5871     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5872     * @throws SecurityException if {@code admin} is not a profile owner.
5873     */
5874    public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
5875        throwIfParentInstance("getCrossProfileCallerIdDisabled");
5876        if (mService != null) {
5877            try {
5878                return mService.getCrossProfileCallerIdDisabled(admin);
5879            } catch (RemoteException e) {
5880                throw e.rethrowFromSystemServer();
5881            }
5882        }
5883        return false;
5884    }
5885
5886    /**
5887     * Determine whether or not caller-Id information has been disabled.
5888     *
5889     * @param userHandle The user for whom to check the caller-id permission
5890     * @hide
5891     */
5892    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
5893        if (mService != null) {
5894            try {
5895                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
5896            } catch (RemoteException e) {
5897                throw e.rethrowFromSystemServer();
5898            }
5899        }
5900        return false;
5901    }
5902
5903    /**
5904     * Called by a profile owner of a managed profile to set whether contacts search from the
5905     * managed profile will be shown in the parent profile, for incoming calls.
5906     * <p>
5907     * The calling device admin must be a profile owner. If it is not, a security exception will be
5908     * thrown.
5909     *
5910     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5911     * @param disabled If true contacts search in the managed profile is not displayed.
5912     * @throws SecurityException if {@code admin} is not a profile owner.
5913     */
5914    public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
5915            boolean disabled) {
5916        throwIfParentInstance("setCrossProfileContactsSearchDisabled");
5917        if (mService != null) {
5918            try {
5919                mService.setCrossProfileContactsSearchDisabled(admin, disabled);
5920            } catch (RemoteException e) {
5921                throw e.rethrowFromSystemServer();
5922            }
5923        }
5924    }
5925
5926    /**
5927     * Called by a profile owner of a managed profile to determine whether or not contacts search
5928     * has been disabled.
5929     * <p>
5930     * The calling device admin must be a profile owner. If it is not, a security exception will be
5931     * thrown.
5932     *
5933     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5934     * @throws SecurityException if {@code admin} is not a profile owner.
5935     */
5936    public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
5937        throwIfParentInstance("getCrossProfileContactsSearchDisabled");
5938        if (mService != null) {
5939            try {
5940                return mService.getCrossProfileContactsSearchDisabled(admin);
5941            } catch (RemoteException e) {
5942                throw e.rethrowFromSystemServer();
5943            }
5944        }
5945        return false;
5946    }
5947
5948
5949    /**
5950     * Determine whether or not contacts search has been disabled.
5951     *
5952     * @param userHandle The user for whom to check the contacts search permission
5953     * @hide
5954     */
5955    public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
5956        if (mService != null) {
5957            try {
5958                return mService
5959                        .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
5960            } catch (RemoteException e) {
5961                throw e.rethrowFromSystemServer();
5962            }
5963        }
5964        return false;
5965    }
5966
5967    /**
5968     * Start Quick Contact on the managed profile for the user, if the policy allows.
5969     *
5970     * @hide
5971     */
5972    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5973            boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
5974        if (mService != null) {
5975            try {
5976                mService.startManagedQuickContact(actualLookupKey, actualContactId,
5977                        isContactIdIgnored, directoryId, originalIntent);
5978            } catch (RemoteException e) {
5979                throw e.rethrowFromSystemServer();
5980            }
5981        }
5982    }
5983
5984    /**
5985     * Start Quick Contact on the managed profile for the user, if the policy allows.
5986     * @hide
5987     */
5988    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5989            Intent originalIntent) {
5990        startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
5991                originalIntent);
5992    }
5993
5994    /**
5995     * Called by a profile owner of a managed profile to set whether bluetooth devices can access
5996     * enterprise contacts.
5997     * <p>
5998     * The calling device admin must be a profile owner. If it is not, a security exception will be
5999     * thrown.
6000     * <p>
6001     * This API works on managed profile only.
6002     *
6003     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6004     * @param disabled If true, bluetooth devices cannot access enterprise contacts.
6005     * @throws SecurityException if {@code admin} is not a profile owner.
6006     */
6007    public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
6008        throwIfParentInstance("setBluetoothContactSharingDisabled");
6009        if (mService != null) {
6010            try {
6011                mService.setBluetoothContactSharingDisabled(admin, disabled);
6012            } catch (RemoteException e) {
6013                throw e.rethrowFromSystemServer();
6014            }
6015        }
6016    }
6017
6018    /**
6019     * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
6020     * cannot access enterprise contacts.
6021     * <p>
6022     * The calling device admin must be a profile owner. If it is not, a security exception will be
6023     * thrown.
6024     * <p>
6025     * This API works on managed profile only.
6026     *
6027     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6028     * @throws SecurityException if {@code admin} is not a profile owner.
6029     */
6030    public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
6031        throwIfParentInstance("getBluetoothContactSharingDisabled");
6032        if (mService != null) {
6033            try {
6034                return mService.getBluetoothContactSharingDisabled(admin);
6035            } catch (RemoteException e) {
6036                throw e.rethrowFromSystemServer();
6037            }
6038        }
6039        return true;
6040    }
6041
6042    /**
6043     * Determine whether or not Bluetooth devices cannot access contacts.
6044     * <p>
6045     * This API works on managed profile UserHandle only.
6046     *
6047     * @param userHandle The user for whom to check the caller-id permission
6048     * @hide
6049     */
6050    public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
6051        if (mService != null) {
6052            try {
6053                return mService.getBluetoothContactSharingDisabledForUser(userHandle
6054                        .getIdentifier());
6055            } catch (RemoteException e) {
6056                throw e.rethrowFromSystemServer();
6057            }
6058        }
6059        return true;
6060    }
6061
6062    /**
6063     * Called by the profile owner of a managed profile so that some intents sent in the managed
6064     * profile can also be resolved in the parent, or vice versa. Only activity intents are
6065     * supported.
6066     *
6067     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6068     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
6069     *            other profile
6070     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
6071     *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
6072     * @throws SecurityException if {@code admin} is not a device or profile owner.
6073     */
6074    public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
6075        throwIfParentInstance("addCrossProfileIntentFilter");
6076        if (mService != null) {
6077            try {
6078                mService.addCrossProfileIntentFilter(admin, filter, flags);
6079            } catch (RemoteException e) {
6080                throw e.rethrowFromSystemServer();
6081            }
6082        }
6083    }
6084
6085    /**
6086     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
6087     * that go from the managed profile to the parent, or from the parent to the managed profile.
6088     * Only removes those that have been set by the profile owner.
6089     * <p>
6090     * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
6091     * the profile is created, some of them ensure the proper functioning of the profile, while
6092     * others enable sharing of data from the parent to the managed profile for user convenience.
6093     * These default intent filters are not cleared when this API is called. If the default cross
6094     * profile data sharing is not desired, they can be disabled with
6095     * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
6096     *
6097     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6098     * @throws SecurityException if {@code admin} is not a profile owner.
6099     */
6100    public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
6101        throwIfParentInstance("clearCrossProfileIntentFilters");
6102        if (mService != null) {
6103            try {
6104                mService.clearCrossProfileIntentFilters(admin);
6105            } catch (RemoteException e) {
6106                throw e.rethrowFromSystemServer();
6107            }
6108        }
6109    }
6110
6111    /**
6112     * Called by a profile or device owner to set the permitted
6113     * {@link android.accessibilityservice.AccessibilityService}. When set by
6114     * a device owner or profile owner the restriction applies to all profiles of the user the
6115     * device owner or profile owner is an admin for. By default, the user can use any accessibility
6116     * service. When zero or more packages have been added, accessibility services that are not in
6117     * the list and not part of the system can not be enabled by the user.
6118     * <p>
6119     * Calling with a null value for the list disables the restriction so that all services can be
6120     * used, calling with an empty list only allows the built-in system services. Any non-system
6121     * accessibility service that's currently enabled must be included in the list.
6122     * <p>
6123     * System accessibility services are always available to the user the list can't modify this.
6124     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6125     * @param packageNames List of accessibility service package names.
6126     * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
6127     *         contain every enabled non-system accessibility service.
6128     * @throws SecurityException if {@code admin} is not a device or profile owner.
6129     */
6130    public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
6131            List<String> packageNames) {
6132        throwIfParentInstance("setPermittedAccessibilityServices");
6133        if (mService != null) {
6134            try {
6135                return mService.setPermittedAccessibilityServices(admin, packageNames);
6136            } catch (RemoteException e) {
6137                throw e.rethrowFromSystemServer();
6138            }
6139        }
6140        return false;
6141    }
6142
6143    /**
6144     * Returns the list of permitted accessibility services set by this device or profile owner.
6145     * <p>
6146     * An empty list means no accessibility services except system services are allowed. Null means
6147     * all accessibility services are allowed.
6148     *
6149     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6150     * @return List of accessiblity service package names.
6151     * @throws SecurityException if {@code admin} is not a device or profile owner.
6152     */
6153    public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
6154        throwIfParentInstance("getPermittedAccessibilityServices");
6155        if (mService != null) {
6156            try {
6157                return mService.getPermittedAccessibilityServices(admin);
6158            } catch (RemoteException e) {
6159                throw e.rethrowFromSystemServer();
6160            }
6161        }
6162        return null;
6163    }
6164
6165    /**
6166     * Called by the system to check if a specific accessibility service is disabled by admin.
6167     *
6168     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6169     * @param packageName Accessibility service package name that needs to be checked.
6170     * @param userHandle user id the admin is running as.
6171     * @return true if the accessibility service is permitted, otherwise false.
6172     *
6173     * @hide
6174     */
6175    public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
6176            @NonNull String packageName, int userHandle) {
6177        if (mService != null) {
6178            try {
6179                return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
6180                        userHandle);
6181            } catch (RemoteException e) {
6182                throw e.rethrowFromSystemServer();
6183            }
6184        }
6185        return false;
6186    }
6187
6188    /**
6189     * Returns the list of accessibility services permitted by the device or profiles
6190     * owners of this user.
6191     *
6192     * <p>Null means all accessibility services are allowed, if a non-null list is returned
6193     * it will contain the intersection of the permitted lists for any device or profile
6194     * owners that apply to this user. It will also include any system accessibility services.
6195     *
6196     * @param userId which user to check for.
6197     * @return List of accessiblity service package names.
6198     * @hide
6199     */
6200     @SystemApi
6201     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
6202     public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
6203        throwIfParentInstance("getPermittedAccessibilityServices");
6204        if (mService != null) {
6205            try {
6206                return mService.getPermittedAccessibilityServicesForUser(userId);
6207            } catch (RemoteException e) {
6208                throw e.rethrowFromSystemServer();
6209            }
6210        }
6211        return null;
6212     }
6213
6214    /**
6215     * Called by a profile or device owner to set the permitted input methods services. When set by
6216     * a device owner or profile owner the restriction applies to all profiles of the user the
6217     * device owner or profile owner is an admin for. By default, the user can use any input method.
6218     * When zero or more packages have been added, input method that are not in the list and not
6219     * part of the system can not be enabled by the user. This method will fail if it is called for
6220     * a admin that is not for the foreground user or a profile of the foreground user. Any
6221     * non-system input method service that's currently enabled must be included in the list.
6222     * <p>
6223     * Calling with a null value for the list disables the restriction so that all input methods can
6224     * be used, calling with an empty list disables all but the system's own input methods.
6225     * <p>
6226     * System input methods are always available to the user this method can't modify this.
6227     *
6228     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6229     * @param packageNames List of input method package names.
6230     * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
6231     *        contain every enabled non-system input method service.
6232     * @throws SecurityException if {@code admin} is not a device or profile owner.
6233     */
6234    public boolean setPermittedInputMethods(
6235            @NonNull ComponentName admin, List<String> packageNames) {
6236        throwIfParentInstance("setPermittedInputMethods");
6237        if (mService != null) {
6238            try {
6239                return mService.setPermittedInputMethods(admin, packageNames);
6240            } catch (RemoteException e) {
6241                throw e.rethrowFromSystemServer();
6242            }
6243        }
6244        return false;
6245    }
6246
6247
6248    /**
6249     * Returns the list of permitted input methods set by this device or profile owner.
6250     * <p>
6251     * An empty list means no input methods except system input methods are allowed. Null means all
6252     * input methods are allowed.
6253     *
6254     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6255     * @return List of input method package names.
6256     * @throws SecurityException if {@code admin} is not a device or profile owner.
6257     */
6258    public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
6259        throwIfParentInstance("getPermittedInputMethods");
6260        if (mService != null) {
6261            try {
6262                return mService.getPermittedInputMethods(admin);
6263            } catch (RemoteException e) {
6264                throw e.rethrowFromSystemServer();
6265            }
6266        }
6267        return null;
6268    }
6269
6270    /**
6271     * Called by the system to check if a specific input method is disabled by admin.
6272     *
6273     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6274     * @param packageName Input method package name that needs to be checked.
6275     * @param userHandle user id the admin is running as.
6276     * @return true if the input method is permitted, otherwise false.
6277     *
6278     * @hide
6279     */
6280    public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
6281            @NonNull String packageName, int userHandle) {
6282        if (mService != null) {
6283            try {
6284                return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
6285            } catch (RemoteException e) {
6286                throw e.rethrowFromSystemServer();
6287            }
6288        }
6289        return false;
6290    }
6291
6292    /**
6293     * Returns the list of input methods permitted by the device or profiles
6294     * owners of the current user.  (*Not* calling user, due to a limitation in InputMethodManager.)
6295     *
6296     * <p>Null means all input methods are allowed, if a non-null list is returned
6297     * it will contain the intersection of the permitted lists for any device or profile
6298     * owners that apply to this user. It will also include any system input methods.
6299     *
6300     * @return List of input method package names.
6301     * @hide
6302     */
6303    @SystemApi
6304    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
6305    public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
6306        throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
6307        if (mService != null) {
6308            try {
6309                return mService.getPermittedInputMethodsForCurrentUser();
6310            } catch (RemoteException e) {
6311                throw e.rethrowFromSystemServer();
6312            }
6313        }
6314        return null;
6315    }
6316
6317    /**
6318     * Called by a profile owner of a managed profile to set the packages that are allowed to use
6319     * a {@link android.service.notification.NotificationListenerService} in the primary user to
6320     * see notifications from the managed profile. By default all packages are permitted by this
6321     * policy. When zero or more packages have been added, notification listeners installed on the
6322     * primary user that are not in the list and are not part of the system won't receive events
6323     * for managed profile notifications.
6324     * <p>
6325     * Calling with a {@code null} value for the list disables the restriction so that all
6326     * notification listener services be used. Calling with an empty list disables all but the
6327     * system's own notification listeners. System notification listener services are always
6328     * available to the user.
6329     * <p>
6330     * If a device or profile owner want to stop notification listeners in their user from seeing
6331     * that user's notifications they should prevent that service from running instead (e.g. via
6332     * {@link #setApplicationHidden(ComponentName, String, boolean)})
6333     *
6334     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6335     * @param packageList List of package names to whitelist
6336     * @return true if setting the restriction succeeded. It will fail if called outside a managed
6337     * profile
6338     * @throws SecurityException if {@code admin} is not a profile owner.
6339     *
6340     * @see android.service.notification.NotificationListenerService
6341     */
6342    public boolean setPermittedCrossProfileNotificationListeners(
6343            @NonNull ComponentName admin, @Nullable List<String> packageList) {
6344        throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
6345        if (mService != null) {
6346            try {
6347                return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
6348            } catch (RemoteException e) {
6349                throw e.rethrowFromSystemServer();
6350            }
6351        }
6352        return false;
6353    }
6354
6355    /**
6356     * Returns the list of packages installed on the primary user that allowed to use a
6357     * {@link android.service.notification.NotificationListenerService} to receive
6358     * notifications from this managed profile, as set by the profile owner.
6359     * <p>
6360     * An empty list means no notification listener services except system ones are allowed.
6361     * A {@code null} return value indicates that all notification listeners are allowed.
6362     */
6363    public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
6364            @NonNull ComponentName admin) {
6365        throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
6366        if (mService != null) {
6367            try {
6368                return mService.getPermittedCrossProfileNotificationListeners(admin);
6369            } catch (RemoteException e) {
6370                throw e.rethrowFromSystemServer();
6371            }
6372        }
6373        return null;
6374    }
6375
6376    /**
6377     * Returns true if {@code NotificationListenerServices} from the given package are allowed to
6378     * receive events for notifications from the given user id. Can only be called by the system uid
6379     *
6380     * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
6381     *
6382     * @hide
6383     */
6384    public boolean isNotificationListenerServicePermitted(
6385            @NonNull String packageName, @UserIdInt int userId) {
6386        if (mService != null) {
6387            try {
6388                return mService.isNotificationListenerServicePermitted(packageName, userId);
6389            } catch (RemoteException e) {
6390                throw e.rethrowFromSystemServer();
6391            }
6392        }
6393        return true;
6394    }
6395
6396    /**
6397     * Get the list of apps to keep around as APKs even if no user has currently installed it. This
6398     * function can be called by a device owner or by a delegate given the
6399     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
6400     * <p>
6401     * Please note that packages returned in this method are not automatically pre-cached.
6402     *
6403     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6404     *            {@code null} if the caller is a keep uninstalled packages delegate.
6405     * @return List of package names to keep cached.
6406     * @see #setDelegatedScopes
6407     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
6408     */
6409    public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
6410        throwIfParentInstance("getKeepUninstalledPackages");
6411        if (mService != null) {
6412            try {
6413                return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
6414            } catch (RemoteException e) {
6415                throw e.rethrowFromSystemServer();
6416            }
6417        }
6418        return null;
6419    }
6420
6421    /**
6422     * Set a list of apps to keep around as APKs even if no user has currently installed it. This
6423     * function can be called by a device owner or by a delegate given the
6424     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
6425     *
6426     * <p>Please note that setting this policy does not imply that specified apps will be
6427     * automatically pre-cached.</p>
6428     *
6429     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6430     *            {@code null} if the caller is a keep uninstalled packages delegate.
6431     * @param packageNames List of package names to keep cached.
6432     * @throws SecurityException if {@code admin} is not a device owner.
6433     * @see #setDelegatedScopes
6434     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
6435     */
6436    public void setKeepUninstalledPackages(@Nullable ComponentName admin,
6437            @NonNull List<String> packageNames) {
6438        throwIfParentInstance("setKeepUninstalledPackages");
6439        if (mService != null) {
6440            try {
6441                mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
6442            } catch (RemoteException e) {
6443                throw e.rethrowFromSystemServer();
6444            }
6445        }
6446    }
6447
6448    /**
6449     * Called by a device owner to create a user with the specified name. The UserHandle returned
6450     * by this method should not be persisted as user handles are recycled as users are removed and
6451     * created. If you need to persist an identifier for this user, use
6452     * {@link UserManager#getSerialNumberForUser}.
6453     *
6454     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6455     * @param name the user's name
6456     * @see UserHandle
6457     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6458     *         user could not be created.
6459     *
6460     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
6461     * @removed From {@link android.os.Build.VERSION_CODES#N}
6462     */
6463    @Deprecated
6464    public @Nullable UserHandle createUser(@NonNull ComponentName admin, String name) {
6465        return null;
6466    }
6467
6468    /**
6469     * Called by a device owner to create a user with the specified name. The UserHandle returned
6470     * by this method should not be persisted as user handles are recycled as users are removed and
6471     * created. If you need to persist an identifier for this user, use
6472     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
6473     * immediately.
6474     *
6475     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
6476     * as registered as an active admin on the new user.  The profile owner package will be
6477     * installed on the new user if it already is installed on the device.
6478     *
6479     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
6480     * profileOwnerComponent when onEnable is called.
6481     *
6482     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6483     * @param name the user's name
6484     * @param ownerName the human readable name of the organisation associated with this DPM.
6485     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
6486     *      the user.
6487     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
6488     *      on the new user.
6489     * @see UserHandle
6490     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6491     *         user could not be created.
6492     *
6493     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
6494     * @removed From {@link android.os.Build.VERSION_CODES#N}
6495     */
6496    @Deprecated
6497    public @Nullable UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
6498            String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
6499        return null;
6500    }
6501
6502    /**
6503      * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
6504      */
6505    public static final int SKIP_SETUP_WIZARD = 0x0001;
6506
6507    /**
6508     * Flag used by {@link #createAndManageUser} to specify that the user should be created
6509     * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
6510     * device.
6511     */
6512    public static final int MAKE_USER_EPHEMERAL = 0x0002;
6513
6514    /**
6515     * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
6516     * demo user.
6517     * @hide
6518     */
6519    public static final int MAKE_USER_DEMO = 0x0004;
6520
6521    /**
6522     * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
6523     * the disabling of system apps during provisioning.
6524     */
6525    public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
6526
6527    /**
6528     * @hide
6529     */
6530    @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
6531            SKIP_SETUP_WIZARD,
6532            MAKE_USER_EPHEMERAL,
6533            MAKE_USER_DEMO,
6534            LEAVE_ALL_SYSTEM_APPS_ENABLED
6535    })
6536    @Retention(RetentionPolicy.SOURCE)
6537    public @interface CreateAndManageUserFlags {}
6538
6539
6540    /**
6541     * Called by a device owner to create a user with the specified name and a given component of
6542     * the calling package as profile owner. The UserHandle returned by this method should not be
6543     * persisted as user handles are recycled as users are removed and created. If you need to
6544     * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
6545     * user will not be started in the background.
6546     * <p>
6547     * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
6548     * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
6549     * be registered as an active admin on the new user. The profile owner package will be installed
6550     * on the new user.
6551     * <p>
6552     * If the adminExtras are not null, they will be stored on the device until the user is started
6553     * for the first time. Then the extras will be passed to the admin when onEnable is called.
6554     * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
6555     * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
6556     * returning {@code null} on failure.
6557     *
6558     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6559     * @param name The user's name.
6560     * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
6561     *            same package as admin, otherwise no user is created and an
6562     *            IllegalArgumentException is thrown.
6563     * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
6564     *            user.
6565     * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
6566     *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
6567     * @see UserHandle
6568     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6569     *         user could not be created.
6570     * @throws SecurityException if {@code admin} is not a device owner.
6571     * @throws UserOperationException if the user could not be created and the calling app is
6572     * targeting {@link android.os.Build.VERSION_CODES#P} and running on
6573     * {@link android.os.Build.VERSION_CODES#P}.
6574     */
6575    public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
6576            @NonNull String name,
6577            @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
6578            @CreateAndManageUserFlags int flags) {
6579        throwIfParentInstance("createAndManageUser");
6580        try {
6581            return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
6582        } catch (ServiceSpecificException e) {
6583            throw new UserOperationException(e.getMessage(), e.errorCode);
6584        } catch (RemoteException re) {
6585            throw re.rethrowFromSystemServer();
6586        }
6587    }
6588
6589    /**
6590     * Called by a device owner to remove a user/profile and all associated data. The primary user
6591     * can not be removed.
6592     *
6593     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6594     * @param userHandle the user to remove.
6595     * @return {@code true} if the user was removed, {@code false} otherwise.
6596     * @throws SecurityException if {@code admin} is not a device owner.
6597     */
6598    public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6599        throwIfParentInstance("removeUser");
6600        try {
6601            return mService.removeUser(admin, userHandle);
6602        } catch (RemoteException re) {
6603            throw re.rethrowFromSystemServer();
6604        }
6605    }
6606
6607    /**
6608     * Called by a device owner to switch the specified secondary user to the foreground.
6609     *
6610     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6611     * @param userHandle the user to switch to; null will switch to primary.
6612     * @return {@code true} if the switch was successful, {@code false} otherwise.
6613     * @throws SecurityException if {@code admin} is not a device owner.
6614     * @see Intent#ACTION_USER_FOREGROUND
6615     * @see #getSecondaryUsers(ComponentName)
6616     */
6617    public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
6618        throwIfParentInstance("switchUser");
6619        try {
6620            return mService.switchUser(admin, userHandle);
6621        } catch (RemoteException re) {
6622            throw re.rethrowFromSystemServer();
6623        }
6624    }
6625
6626    /**
6627     * Called by a device owner to start the specified secondary user in background.
6628     *
6629     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6630     * @param userHandle the user to be started in background.
6631     * @return one of the following result codes:
6632     * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
6633     * {@link UserManager#USER_OPERATION_SUCCESS},
6634     * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
6635     * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
6636     * @throws SecurityException if {@code admin} is not a device owner.
6637     * @see #getSecondaryUsers(ComponentName)
6638     */
6639    public @UserOperationResult int startUserInBackground(
6640            @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6641        throwIfParentInstance("startUserInBackground");
6642        try {
6643            return mService.startUserInBackground(admin, userHandle);
6644        } catch (RemoteException re) {
6645            throw re.rethrowFromSystemServer();
6646        }
6647    }
6648
6649    /**
6650     * Called by a device owner to stop the specified secondary user.
6651     *
6652     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6653     * @param userHandle the user to be stopped.
6654     * @return one of the following result codes:
6655     * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
6656     * {@link UserManager#USER_OPERATION_SUCCESS},
6657     * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
6658     * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
6659     * @throws SecurityException if {@code admin} is not a device owner.
6660     * @see #getSecondaryUsers(ComponentName)
6661     */
6662    public @UserOperationResult int stopUser(
6663            @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6664        throwIfParentInstance("stopUser");
6665        try {
6666            return mService.stopUser(admin, userHandle);
6667        } catch (RemoteException re) {
6668            throw re.rethrowFromSystemServer();
6669        }
6670    }
6671
6672    /**
6673     * Called by a profile owner of secondary user that is affiliated with the device to stop the
6674     * calling user and switch back to primary.
6675     *
6676     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6677     * @return one of the following result codes:
6678     * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
6679     * {@link UserManager#USER_OPERATION_SUCCESS},
6680     * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
6681     * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
6682     * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
6683     * @see #getSecondaryUsers(ComponentName)
6684     */
6685    public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
6686        throwIfParentInstance("logoutUser");
6687        try {
6688            return mService.logoutUser(admin);
6689        } catch (RemoteException re) {
6690            throw re.rethrowFromSystemServer();
6691        }
6692    }
6693
6694    /**
6695     * Called by a device owner to list all secondary users on the device. Managed profiles are not
6696     * considered as secondary users.
6697     * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
6698     * and {@link #stopUser}.
6699     *
6700     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6701     * @return list of other {@link UserHandle}s on the device.
6702     * @throws SecurityException if {@code admin} is not a device owner.
6703     * @see #removeUser(ComponentName, UserHandle)
6704     * @see #switchUser(ComponentName, UserHandle)
6705     * @see #startUserInBackground(ComponentName, UserHandle)
6706     * @see #stopUser(ComponentName, UserHandle)
6707     */
6708    public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
6709        throwIfParentInstance("getSecondaryUsers");
6710        try {
6711            return mService.getSecondaryUsers(admin);
6712        } catch (RemoteException re) {
6713            throw re.rethrowFromSystemServer();
6714        }
6715    }
6716
6717    /**
6718     * Checks if the profile owner is running in an ephemeral user.
6719     *
6720     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6721     * @return whether the profile owner is running in an ephemeral user.
6722     */
6723    public boolean isEphemeralUser(@NonNull ComponentName admin) {
6724        throwIfParentInstance("isEphemeralUser");
6725        try {
6726            return mService.isEphemeralUser(admin);
6727        } catch (RemoteException re) {
6728            throw re.rethrowFromSystemServer();
6729        }
6730    }
6731
6732    /**
6733     * Retrieves the application restrictions for a given target application running in the calling
6734     * user.
6735     * <p>
6736     * The caller must be a profile or device owner on that user, or the package allowed to manage
6737     * application restrictions via {@link #setDelegatedScopes} with the
6738     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
6739     *
6740     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
6741     *
6742     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6743     *            {@code null} if called by the application restrictions managing package.
6744     * @param packageName The name of the package to fetch restricted settings of.
6745     * @return {@link Bundle} of settings corresponding to what was set last time
6746     *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
6747     *         {@link Bundle} if no restrictions have been set.
6748     * @throws SecurityException if {@code admin} is not a device or profile owner.
6749     * @see #setDelegatedScopes
6750     * @see #DELEGATION_APP_RESTRICTIONS
6751     */
6752    @WorkerThread
6753    public @NonNull Bundle getApplicationRestrictions(
6754            @Nullable ComponentName admin, String packageName) {
6755        throwIfParentInstance("getApplicationRestrictions");
6756        if (mService != null) {
6757            try {
6758                return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
6759                        packageName);
6760            } catch (RemoteException e) {
6761                throw e.rethrowFromSystemServer();
6762            }
6763        }
6764        return null;
6765    }
6766
6767    /**
6768     * Called by a profile or device owner to set a user restriction specified by the key.
6769     * <p>
6770     * The calling device admin must be a profile or device owner; if it is not, a security
6771     * exception will be thrown.
6772     *
6773     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6774     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6775     *            for the list of keys.
6776     * @throws SecurityException if {@code admin} is not a device or profile owner.
6777     */
6778    public void addUserRestriction(@NonNull ComponentName admin, String key) {
6779        throwIfParentInstance("addUserRestriction");
6780        if (mService != null) {
6781            try {
6782                mService.setUserRestriction(admin, key, true);
6783            } catch (RemoteException e) {
6784                throw e.rethrowFromSystemServer();
6785            }
6786        }
6787    }
6788
6789    /**
6790     * Called by a profile or device owner to clear a user restriction specified by the key.
6791     * <p>
6792     * The calling device admin must be a profile or device owner; if it is not, a security
6793     * exception will be thrown.
6794     *
6795     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6796     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6797     *            for the list of keys.
6798     * @throws SecurityException if {@code admin} is not a device or profile owner.
6799     */
6800    public void clearUserRestriction(@NonNull ComponentName admin, String key) {
6801        throwIfParentInstance("clearUserRestriction");
6802        if (mService != null) {
6803            try {
6804                mService.setUserRestriction(admin, key, false);
6805            } catch (RemoteException e) {
6806                throw e.rethrowFromSystemServer();
6807            }
6808        }
6809    }
6810
6811    /**
6812     * Called by a profile or device owner to get user restrictions set with
6813     * {@link #addUserRestriction(ComponentName, String)}.
6814     * <p>
6815     * The target user may have more restrictions set by the system or other device owner / profile
6816     * owner. To get all the user restrictions currently set, use
6817     * {@link UserManager#getUserRestrictions()}.
6818     *
6819     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6820     * @throws SecurityException if {@code admin} is not a device or profile owner.
6821     */
6822    public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
6823        throwIfParentInstance("getUserRestrictions");
6824        Bundle ret = null;
6825        if (mService != null) {
6826            try {
6827                ret = mService.getUserRestrictions(admin);
6828            } catch (RemoteException e) {
6829                throw e.rethrowFromSystemServer();
6830            }
6831        }
6832        return ret == null ? new Bundle() : ret;
6833    }
6834
6835    /**
6836     * Called by any app to display a support dialog when a feature was disabled by an admin.
6837     * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
6838     * display the dialog. It will tell the user that the feature indicated by {@code restriction}
6839     * was disabled by an admin, and include a link for more information. The default content of
6840     * the dialog can be changed by the restricting admin via
6841     * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
6842     * set (i.e. the feature is available), then the return value will be {@code null}.
6843     * @param restriction Indicates for which feature the dialog should be displayed. Can be a
6844     *            user restriction from {@link UserManager}, e.g.
6845     *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
6846     *            {@link #POLICY_DISABLE_CAMERA}, {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
6847     * @return Intent An intent to be used to start the dialog-activity if the restriction is
6848     *            set by an admin, or null if the restriction does not exist or no admin set it.
6849     */
6850    public Intent createAdminSupportIntent(@NonNull String restriction) {
6851        throwIfParentInstance("createAdminSupportIntent");
6852        if (mService != null) {
6853            try {
6854                return mService.createAdminSupportIntent(restriction);
6855            } catch (RemoteException e) {
6856                throw e.rethrowFromSystemServer();
6857            }
6858        }
6859        return null;
6860    }
6861
6862    /**
6863     * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
6864     * actual package file remain. This function can be called by a device owner, profile owner, or
6865     * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6866     * {@link #setDelegatedScopes}.
6867     *
6868     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6869     *            {@code null} if the caller is a package access delegate.
6870     * @param packageName The name of the package to hide or unhide.
6871     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
6872     *            unhidden.
6873     * @return boolean Whether the hidden setting of the package was successfully updated.
6874     * @throws SecurityException if {@code admin} is not a device or profile owner.
6875     * @see #setDelegatedScopes
6876     * @see #DELEGATION_PACKAGE_ACCESS
6877     */
6878    public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
6879            boolean hidden) {
6880        throwIfParentInstance("setApplicationHidden");
6881        if (mService != null) {
6882            try {
6883                return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
6884                        hidden);
6885            } catch (RemoteException e) {
6886                throw e.rethrowFromSystemServer();
6887            }
6888        }
6889        return false;
6890    }
6891
6892    /**
6893     * Determine if a package is hidden. This function can be called by a device owner, profile
6894     * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6895     * {@link #setDelegatedScopes}.
6896     *
6897     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6898     *            {@code null} if the caller is a package access delegate.
6899     * @param packageName The name of the package to retrieve the hidden status of.
6900     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
6901     * @throws SecurityException if {@code admin} is not a device or profile owner.
6902     * @see #setDelegatedScopes
6903     * @see #DELEGATION_PACKAGE_ACCESS
6904     */
6905    public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
6906        throwIfParentInstance("isApplicationHidden");
6907        if (mService != null) {
6908            try {
6909                return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName);
6910            } catch (RemoteException e) {
6911                throw e.rethrowFromSystemServer();
6912            }
6913        }
6914        return false;
6915    }
6916
6917    /**
6918     * Re-enable a system app that was disabled by default when the user was initialized. This
6919     * function can be called by a device owner, profile owner, or by a delegate given the
6920     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6921     *
6922     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6923     *            {@code null} if the caller is an enable system app delegate.
6924     * @param packageName The package to be re-enabled in the calling profile.
6925     * @throws SecurityException if {@code admin} is not a device or profile owner.
6926     * @see #setDelegatedScopes
6927     * @see #DELEGATION_PACKAGE_ACCESS
6928     */
6929    public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
6930        throwIfParentInstance("enableSystemApp");
6931        if (mService != null) {
6932            try {
6933                mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
6934            } catch (RemoteException e) {
6935                throw e.rethrowFromSystemServer();
6936            }
6937        }
6938    }
6939
6940    /**
6941     * Re-enable system apps by intent that were disabled by default when the user was initialized.
6942     * This function can be called by a device owner, profile owner, or by a delegate given the
6943     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6944     *
6945     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6946     *            {@code null} if the caller is an enable system app delegate.
6947     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
6948     *            intent will be re-enabled in the calling profile.
6949     * @return int The number of activities that matched the intent and were installed.
6950     * @throws SecurityException if {@code admin} is not a device or profile owner.
6951     * @see #setDelegatedScopes
6952     * @see #DELEGATION_PACKAGE_ACCESS
6953     */
6954    public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
6955        throwIfParentInstance("enableSystemApp");
6956        if (mService != null) {
6957            try {
6958                return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
6959            } catch (RemoteException e) {
6960                throw e.rethrowFromSystemServer();
6961            }
6962        }
6963        return 0;
6964    }
6965
6966    /**
6967     * Install an existing package that has been installed in another user, or has been kept after
6968     * removal via {@link #setKeepUninstalledPackages}.
6969     * This function can be called by a device owner, profile owner or a delegate given
6970     * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
6971     * When called in a secondary user or managed profile, the user/profile must be affiliated with
6972     * the device. See {@link #isAffiliatedUser}.
6973     *
6974     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6975     * @param packageName The package to be installed in the calling profile.
6976     * @return {@code true} if the app is installed; {@code false} otherwise.
6977     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
6978     * an affiliated user or profile.
6979     * @see #setKeepUninstalledPackages
6980     * @see #setDelegatedScopes
6981     * @see #isAffiliatedUser
6982     * @see #DELEGATION_PACKAGE_ACCESS
6983     */
6984    public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
6985        throwIfParentInstance("installExistingPackage");
6986        if (mService != null) {
6987            try {
6988                return mService.installExistingPackage(admin, mContext.getPackageName(),
6989                        packageName);
6990            } catch (RemoteException e) {
6991                throw e.rethrowFromSystemServer();
6992            }
6993        }
6994        return false;
6995    }
6996
6997    /**
6998     * Called by a device owner or profile owner to disable account management for a specific type
6999     * of account.
7000     * <p>
7001     * The calling device admin must be a device owner or profile owner. If it is not, a security
7002     * exception will be thrown.
7003     * <p>
7004     * When account management is disabled for an account type, adding or removing an account of
7005     * that type will not be possible.
7006     * <p>
7007     * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
7008     * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
7009     * management for a specific type is disabled.
7010     *
7011     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7012     * @param accountType For which account management is disabled or enabled.
7013     * @param disabled The boolean indicating that account management will be disabled (true) or
7014     *            enabled (false).
7015     * @throws SecurityException if {@code admin} is not a device or profile owner.
7016     */
7017    public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
7018            boolean disabled) {
7019        throwIfParentInstance("setAccountManagementDisabled");
7020        if (mService != null) {
7021            try {
7022                mService.setAccountManagementDisabled(admin, accountType, disabled);
7023            } catch (RemoteException e) {
7024                throw e.rethrowFromSystemServer();
7025            }
7026        }
7027    }
7028
7029    /**
7030     * Gets the array of accounts for which account management is disabled by the profile owner.
7031     *
7032     * <p> Account management can be disabled/enabled by calling
7033     * {@link #setAccountManagementDisabled}.
7034     *
7035     * @return a list of account types for which account management has been disabled.
7036     *
7037     * @see #setAccountManagementDisabled
7038     */
7039    public @Nullable String[] getAccountTypesWithManagementDisabled() {
7040        throwIfParentInstance("getAccountTypesWithManagementDisabled");
7041        return getAccountTypesWithManagementDisabledAsUser(myUserId());
7042    }
7043
7044    /**
7045     * @see #getAccountTypesWithManagementDisabled()
7046     * @hide
7047     */
7048    public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7049        if (mService != null) {
7050            try {
7051                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
7052            } catch (RemoteException e) {
7053                throw e.rethrowFromSystemServer();
7054            }
7055        }
7056
7057        return null;
7058    }
7059
7060    /**
7061     * Sets which packages may enter lock task mode.
7062     * <p>
7063     * Any packages that share uid with an allowed package will also be allowed to activate lock
7064     * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
7065     * package list results in locked tasks belonging to those packages to be finished.
7066     * <p>
7067     * This function can only be called by the device owner, a profile owner of an affiliated user
7068     * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
7069     * Any package set via this method will be cleared if the user becomes unaffiliated.
7070     *
7071     * @param packages The list of packages allowed to enter lock task mode
7072     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7073     * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7074     * affiliated user or profile, or the profile owner when no device owner is set.
7075     * @see #isAffiliatedUser
7076     * @see Activity#startLockTask()
7077     * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
7078     * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
7079     * @see UserManager#DISALLOW_CREATE_WINDOWS
7080     */
7081    public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
7082            throws SecurityException {
7083        throwIfParentInstance("setLockTaskPackages");
7084        if (mService != null) {
7085            try {
7086                mService.setLockTaskPackages(admin, packages);
7087            } catch (RemoteException e) {
7088                throw e.rethrowFromSystemServer();
7089            }
7090        }
7091    }
7092
7093    /**
7094     * Returns the list of packages allowed to start the lock task mode.
7095     *
7096     * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7097     * affiliated user or profile, or the profile owner when no device owner is set.
7098     * @see #isAffiliatedUser
7099     * @see #setLockTaskPackages
7100     */
7101    public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
7102        throwIfParentInstance("getLockTaskPackages");
7103        if (mService != null) {
7104            try {
7105                return mService.getLockTaskPackages(admin);
7106            } catch (RemoteException e) {
7107                throw e.rethrowFromSystemServer();
7108            }
7109        }
7110        return new String[0];
7111    }
7112
7113    /**
7114     * This function lets the caller know whether the given component is allowed to start the
7115     * lock task mode.
7116     * @param pkg The package to check
7117     */
7118    public boolean isLockTaskPermitted(String pkg) {
7119        throwIfParentInstance("isLockTaskPermitted");
7120        if (mService != null) {
7121            try {
7122                return mService.isLockTaskPermitted(pkg);
7123            } catch (RemoteException e) {
7124                throw e.rethrowFromSystemServer();
7125            }
7126        }
7127        return false;
7128    }
7129
7130    /**
7131     * Sets which system features are enabled when the device runs in lock task mode. This method
7132     * doesn't affect the features when lock task mode is inactive. Any system features not included
7133     * in {@code flags} are implicitly disabled when calling this method. By default, only
7134     * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled—all the other features are disabled. To
7135     * disable the global actions dialog, call this method omitting
7136     * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
7137     *
7138     * <p>This method can only be called by the device owner, a profile owner of an affiliated
7139     * user or profile, or the profile owner when no device owner is set. See
7140     * {@link #isAffiliatedUser}.
7141     * Any features set using this method are cleared if the user becomes unaffiliated.
7142     *
7143     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7144     * @param flags The system features enabled during lock task mode.
7145     * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7146     * affiliated user or profile, or the profile owner when no device owner is set.
7147     * @see #isAffiliatedUser
7148     **/
7149    public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
7150        throwIfParentInstance("setLockTaskFeatures");
7151        if (mService != null) {
7152            try {
7153                mService.setLockTaskFeatures(admin, flags);
7154            } catch (RemoteException e) {
7155                throw e.rethrowFromSystemServer();
7156            }
7157        }
7158    }
7159
7160    /**
7161     * Gets which system features are enabled for LockTask mode.
7162     *
7163     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7164     * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
7165     * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7166     * affiliated user or profile, or the profile owner when no device owner is set.
7167     * @see #isAffiliatedUser
7168     * @see #setLockTaskFeatures
7169     */
7170    public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
7171        throwIfParentInstance("getLockTaskFeatures");
7172        if (mService != null) {
7173            try {
7174                return mService.getLockTaskFeatures(admin);
7175            } catch (RemoteException e) {
7176                throw e.rethrowFromSystemServer();
7177            }
7178        }
7179        return 0;
7180    }
7181
7182    /**
7183     * Called by device owner to update {@link android.provider.Settings.Global} settings.
7184     * Validation that the value of the setting is in the correct form for the setting type should
7185     * be performed by the caller.
7186     * <p>
7187     * The settings that can be updated with this method are:
7188     * <ul>
7189     * <li>{@link android.provider.Settings.Global#ADB_ENABLED}</li>
7190     * <li>{@link android.provider.Settings.Global#AUTO_TIME}</li>
7191     * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE}</li>
7192     * <li>{@link android.provider.Settings.Global#DATA_ROAMING}</li>
7193     * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
7194     * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}</li>
7195     * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
7196     * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
7197     * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
7198     * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
7199     * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
7200     * </ul>
7201     * <p>
7202     * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
7203     * <ul>
7204     * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
7205     * {@link android.bluetooth.BluetoothAdapter#enable()} and
7206     * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
7207     * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
7208     * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
7209     * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
7210     * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
7211     * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
7212     * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
7213     * </ul>
7214     *
7215     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7216     * @param setting The name of the setting to update.
7217     * @param value The value to update the setting to.
7218     * @throws SecurityException if {@code admin} is not a device owner.
7219     */
7220    public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
7221        throwIfParentInstance("setGlobalSetting");
7222        if (mService != null) {
7223            try {
7224                mService.setGlobalSetting(admin, setting, value);
7225            } catch (RemoteException e) {
7226                throw e.rethrowFromSystemServer();
7227            }
7228        }
7229    }
7230
7231    /** @hide */
7232    @StringDef({
7233            Settings.System.SCREEN_BRIGHTNESS_MODE,
7234            Settings.System.SCREEN_BRIGHTNESS,
7235            Settings.System.SCREEN_OFF_TIMEOUT
7236    })
7237    @Retention(RetentionPolicy.SOURCE)
7238    public @interface SystemSettingsWhitelist {}
7239
7240    /**
7241     * Called by a device or profile owner to update {@link android.provider.Settings.System}
7242     * settings. Validation that the value of the setting is in the correct form for the setting
7243     * type should be performed by the caller.
7244     * <p>
7245     * The settings that can be updated by a device owner or profile owner of secondary user with
7246     * this method are:
7247     * <ul>
7248     * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
7249     * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
7250     * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
7251     * </ul>
7252     * <p>
7253     *
7254     * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
7255     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7256     * @param setting The name of the setting to update.
7257     * @param value The value to update the setting to.
7258     * @throws SecurityException if {@code admin} is not a device or profile owner.
7259     */
7260    public void setSystemSetting(@NonNull ComponentName admin,
7261            @NonNull @SystemSettingsWhitelist String setting, String value) {
7262        throwIfParentInstance("setSystemSetting");
7263        if (mService != null) {
7264            try {
7265                mService.setSystemSetting(admin, setting, value);
7266            } catch (RemoteException e) {
7267                throw e.rethrowFromSystemServer();
7268            }
7269        }
7270    }
7271
7272    /**
7273     * Called by device owner to set the system wall clock time. This only takes effect if called
7274     * when {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false} will be
7275     * returned.
7276     *
7277     * @param admin Which {@link DeviceAdminReceiver} this request is associated with
7278     * @param millis time in milliseconds since the Epoch
7279     * @return {@code true} if set time succeeded, {@code false} otherwise.
7280     * @throws SecurityException if {@code admin} is not a device owner.
7281     */
7282    public boolean setTime(@NonNull ComponentName admin, long millis) {
7283        throwIfParentInstance("setTime");
7284        if (mService != null) {
7285            try {
7286                return mService.setTime(admin, millis);
7287            } catch (RemoteException e) {
7288                throw e.rethrowFromSystemServer();
7289            }
7290        }
7291        return false;
7292    }
7293
7294    /**
7295     * Called by device owner to set the system's persistent default time zone. This only takes
7296     * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE} is 0, otherwise
7297     * {@code false} will be returned.
7298     *
7299     * @see android.app.AlarmManager#setTimeZone(String)
7300     * @param admin Which {@link DeviceAdminReceiver} this request is associated with
7301     * @param timeZone one of the Olson ids from the list returned by
7302     *     {@link java.util.TimeZone#getAvailableIDs}
7303     * @return {@code true} if set timezone succeeded, {@code false} otherwise.
7304     * @throws SecurityException if {@code admin} is not a device owner.
7305     */
7306    public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
7307        throwIfParentInstance("setTimeZone");
7308        if (mService != null) {
7309            try {
7310                return mService.setTimeZone(admin, timeZone);
7311            } catch (RemoteException e) {
7312                throw e.rethrowFromSystemServer();
7313            }
7314        }
7315        return false;
7316    }
7317
7318    /**
7319     * Called by profile or device owners to update {@link android.provider.Settings.Secure}
7320     * settings. Validation that the value of the setting is in the correct form for the setting
7321     * type should be performed by the caller.
7322     * <p>
7323     * The settings that can be updated by a profile or device owner with this method are:
7324     * <ul>
7325     * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
7326     * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
7327     * </ul>
7328     * <p>
7329     * A device owner can additionally update the following settings:
7330     * <ul>
7331     * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}</li>
7332     * </ul>
7333     *
7334     * <strong>Note: Starting from Android O, apps should no longer call this method with the
7335     * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
7336     * deprecated. Instead, device owners or profile owners should use the restriction
7337     * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
7338     * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
7339     * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
7340     * an {@link UnsupportedOperationException} is thrown.
7341     * </strong>
7342     *
7343     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7344     * @param setting The name of the setting to update.
7345     * @param value The value to update the setting to.
7346     * @throws SecurityException if {@code admin} is not a device or profile owner.
7347     */
7348    public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
7349        throwIfParentInstance("setSecureSetting");
7350        if (mService != null) {
7351            try {
7352                mService.setSecureSetting(admin, setting, value);
7353            } catch (RemoteException e) {
7354                throw e.rethrowFromSystemServer();
7355            }
7356        }
7357    }
7358
7359    /**
7360     * Designates a specific service component as the provider for making permission requests of a
7361     * local or remote administrator of the user.
7362     * <p/>
7363     * Only a profile owner can designate the restrictions provider.
7364     *
7365     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7366     * @param provider The component name of the service that implements
7367     *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
7368     *            provider previously assigned.
7369     * @throws SecurityException if {@code admin} is not a device or profile owner.
7370     */
7371    public void setRestrictionsProvider(@NonNull ComponentName admin,
7372            @Nullable ComponentName provider) {
7373        throwIfParentInstance("setRestrictionsProvider");
7374        if (mService != null) {
7375            try {
7376                mService.setRestrictionsProvider(admin, provider);
7377            } catch (RemoteException re) {
7378                throw re.rethrowFromSystemServer();
7379            }
7380        }
7381    }
7382
7383    /**
7384     * Called by profile or device owners to set the master volume mute on or off.
7385     * This has no effect when set on a managed profile.
7386     *
7387     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7388     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
7389     * @throws SecurityException if {@code admin} is not a device or profile owner.
7390     */
7391    public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
7392        throwIfParentInstance("setMasterVolumeMuted");
7393        if (mService != null) {
7394            try {
7395                mService.setMasterVolumeMuted(admin, on);
7396            } catch (RemoteException re) {
7397                throw re.rethrowFromSystemServer();
7398            }
7399        }
7400    }
7401
7402    /**
7403     * Called by profile or device owners to check whether the master volume mute is on or off.
7404     *
7405     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7406     * @return {@code true} if master volume is muted, {@code false} if it's not.
7407     * @throws SecurityException if {@code admin} is not a device or profile owner.
7408     */
7409    public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
7410        throwIfParentInstance("isMasterVolumeMuted");
7411        if (mService != null) {
7412            try {
7413                return mService.isMasterVolumeMuted(admin);
7414            } catch (RemoteException re) {
7415                throw re.rethrowFromSystemServer();
7416            }
7417        }
7418        return false;
7419    }
7420
7421    /**
7422     * Change whether a user can uninstall a package. This function can be called by a device owner,
7423     * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
7424     * {@link #setDelegatedScopes}.
7425     *
7426     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7427     *             {@code null} if the caller is a block uninstall delegate.
7428     * @param packageName package to change.
7429     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
7430     * @throws SecurityException if {@code admin} is not a device or profile owner.
7431     * @see #setDelegatedScopes
7432     * @see #DELEGATION_BLOCK_UNINSTALL
7433     */
7434    public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
7435            boolean uninstallBlocked) {
7436        throwIfParentInstance("setUninstallBlocked");
7437        if (mService != null) {
7438            try {
7439                mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
7440                    uninstallBlocked);
7441            } catch (RemoteException re) {
7442                throw re.rethrowFromSystemServer();
7443            }
7444        }
7445    }
7446
7447    /**
7448     * Check whether the user has been blocked by device policy from uninstalling a package.
7449     * Requires the caller to be the profile owner if checking a specific admin's policy.
7450     * <p>
7451     * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
7452     * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
7453     * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
7454     * will cause a NullPointerException to be raised.
7455     *
7456     * @param admin The name of the admin component whose blocking policy will be checked, or
7457     *            {@code null} to check whether any admin has blocked the uninstallation.
7458     * @param packageName package to check.
7459     * @return true if uninstallation is blocked.
7460     * @throws SecurityException if {@code admin} is not a device or profile owner.
7461     */
7462    public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
7463        throwIfParentInstance("isUninstallBlocked");
7464        if (mService != null) {
7465            try {
7466                return mService.isUninstallBlocked(admin, packageName);
7467            } catch (RemoteException re) {
7468                throw re.rethrowFromSystemServer();
7469            }
7470        }
7471        return false;
7472    }
7473
7474    /**
7475     * Called by the profile owner of a managed profile to enable widget providers from a given
7476     * package to be available in the parent profile. As a result the user will be able to add
7477     * widgets from the white-listed package running under the profile to a widget host which runs
7478     * under the parent profile, for example the home screen. Note that a package may have zero or
7479     * more provider components, where each component provides a different widget type.
7480     * <p>
7481     * <strong>Note:</strong> By default no widget provider package is white-listed.
7482     *
7483     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7484     * @param packageName The package from which widget providers are white-listed.
7485     * @return Whether the package was added.
7486     * @throws SecurityException if {@code admin} is not a profile owner.
7487     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
7488     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
7489     */
7490    public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
7491        throwIfParentInstance("addCrossProfileWidgetProvider");
7492        if (mService != null) {
7493            try {
7494                return mService.addCrossProfileWidgetProvider(admin, packageName);
7495            } catch (RemoteException re) {
7496                throw re.rethrowFromSystemServer();
7497            }
7498        }
7499        return false;
7500    }
7501
7502    /**
7503     * Called by the profile owner of a managed profile to disable widget providers from a given
7504     * package to be available in the parent profile. For this method to take effect the package
7505     * should have been added via
7506     * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
7507     * <p>
7508     * <strong>Note:</strong> By default no widget provider package is white-listed.
7509     *
7510     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7511     * @param packageName The package from which widget providers are no longer white-listed.
7512     * @return Whether the package was removed.
7513     * @throws SecurityException if {@code admin} is not a profile owner.
7514     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
7515     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
7516     */
7517    public boolean removeCrossProfileWidgetProvider(
7518            @NonNull ComponentName admin, String packageName) {
7519        throwIfParentInstance("removeCrossProfileWidgetProvider");
7520        if (mService != null) {
7521            try {
7522                return mService.removeCrossProfileWidgetProvider(admin, packageName);
7523            } catch (RemoteException re) {
7524                throw re.rethrowFromSystemServer();
7525            }
7526        }
7527        return false;
7528    }
7529
7530    /**
7531     * Called by the profile owner of a managed profile to query providers from which packages are
7532     * available in the parent profile.
7533     *
7534     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7535     * @return The white-listed package list.
7536     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
7537     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
7538     * @throws SecurityException if {@code admin} is not a profile owner.
7539     */
7540    public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
7541        throwIfParentInstance("getCrossProfileWidgetProviders");
7542        if (mService != null) {
7543            try {
7544                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
7545                if (providers != null) {
7546                    return providers;
7547                }
7548            } catch (RemoteException re) {
7549                throw re.rethrowFromSystemServer();
7550            }
7551        }
7552        return Collections.emptyList();
7553    }
7554
7555    /**
7556     * Called by profile or device owners to set the user's photo.
7557     *
7558     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7559     * @param icon the bitmap to set as the photo.
7560     * @throws SecurityException if {@code admin} is not a device or profile owner.
7561     */
7562    public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
7563        throwIfParentInstance("setUserIcon");
7564        try {
7565            mService.setUserIcon(admin, icon);
7566        } catch (RemoteException re) {
7567            throw re.rethrowFromSystemServer();
7568        }
7569    }
7570
7571    /**
7572     * Called by device owners to set a local system update policy. When a new policy is set,
7573     * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
7574     * <p>
7575     * If the supplied system update policy has freeze periods set but the freeze periods do not
7576     * meet 90-day maximum length or 60-day minimum separation requirement set out in
7577     * {@link SystemUpdatePolicy#setFreezePeriods},
7578     * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
7579     * keeps a record of freeze periods the device experienced previously, and combines them with
7580     * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
7581     * separation constraints. As a result, freeze periods that passed validation during
7582     * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
7583     * the freeze period history. If this is causing issues during development,
7584     * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
7585     *
7586     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
7587     *            components in the device owner package can set system update policies and the most
7588     *            recent policy takes effect.
7589     * @param policy the new policy, or {@code null} to clear the current policy.
7590     * @throws SecurityException if {@code admin} is not a device owner.
7591     * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
7592     * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
7593     *             meet the requirement.
7594     * @see SystemUpdatePolicy
7595     * @see SystemUpdatePolicy#setFreezePeriods(List)
7596     */
7597    public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
7598        throwIfParentInstance("setSystemUpdatePolicy");
7599        if (mService != null) {
7600            try {
7601                mService.setSystemUpdatePolicy(admin, policy);
7602            } catch (RemoteException re) {
7603                throw re.rethrowFromSystemServer();
7604            }
7605        }
7606    }
7607
7608    /**
7609     * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
7610     *
7611     * @return The current policy object, or {@code null} if no policy is set.
7612     */
7613    public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
7614        throwIfParentInstance("getSystemUpdatePolicy");
7615        if (mService != null) {
7616            try {
7617                return mService.getSystemUpdatePolicy();
7618            } catch (RemoteException re) {
7619                throw re.rethrowFromSystemServer();
7620            }
7621        }
7622        return null;
7623    }
7624
7625    /**
7626     * Reset record of previous system update freeze period the device went through.
7627     * Only callable by ADB.
7628     * @hide
7629     */
7630    public void clearSystemUpdatePolicyFreezePeriodRecord() {
7631        throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
7632        if (mService == null) {
7633            return;
7634        }
7635        try {
7636            mService.clearSystemUpdatePolicyFreezePeriodRecord();
7637        } catch (RemoteException re) {
7638            throw re.rethrowFromSystemServer();
7639        }
7640    }
7641
7642    /**
7643     * Called by a device owner or profile owner of secondary users that is affiliated with the
7644     * device to disable the keyguard altogether.
7645     * <p>
7646     * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
7647     * type. However, this call has no effect if a password, pin or pattern is currently set. If a
7648     * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
7649     * disabled.
7650     *
7651     * <p>
7652     * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
7653     * keyguard if it is currently shown.
7654     *
7655     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7656     * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
7657     * @return {@code false} if attempting to disable the keyguard while a lock password was in
7658     *         place. {@code true} otherwise.
7659     * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
7660     * secondary user that is affiliated with the device.
7661     * @see #isAffiliatedUser
7662     * @see #getSecondaryUsers
7663     */
7664    public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
7665        throwIfParentInstance("setKeyguardDisabled");
7666        try {
7667            return mService.setKeyguardDisabled(admin, disabled);
7668        } catch (RemoteException re) {
7669            throw re.rethrowFromSystemServer();
7670        }
7671    }
7672
7673    /**
7674     * Called by device owner or profile owner of secondary users  that is affiliated with the
7675     * device to disable the status bar. Disabling the status bar blocks notifications, quick
7676     * settings and other screen overlays that allow escaping from a single use device.
7677     * <p>
7678     * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
7679     * status bar in LockTask mode can be configured with
7680     * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
7681     * LockTask mode will be registered, but will only take effect when the device leaves LockTask
7682     * mode.
7683     *
7684     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7685     * @param disabled {@code true} disables the status bar, {@code false} reenables it.
7686     * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
7687     * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
7688     * secondary user that is affiliated with the device.
7689     * @see #isAffiliatedUser
7690     * @see #getSecondaryUsers
7691     */
7692    public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
7693        throwIfParentInstance("setStatusBarDisabled");
7694        try {
7695            return mService.setStatusBarDisabled(admin, disabled);
7696        } catch (RemoteException re) {
7697            throw re.rethrowFromSystemServer();
7698        }
7699    }
7700
7701    /**
7702     * Called by the system update service to notify device and profile owners of pending system
7703     * updates.
7704     *
7705     * This method should only be used when it is unknown whether the pending system
7706     * update is a security patch. Otherwise, use
7707     * {@link #notifyPendingSystemUpdate(long, boolean)}.
7708     *
7709     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
7710     *         indicating when the current pending update was first available. {@code -1} if no
7711     *         update is available.
7712     * @see #notifyPendingSystemUpdate(long, boolean)
7713     * @hide
7714     */
7715    @SystemApi
7716    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
7717    public void notifyPendingSystemUpdate(long updateReceivedTime) {
7718        throwIfParentInstance("notifyPendingSystemUpdate");
7719        if (mService != null) {
7720            try {
7721                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
7722            } catch (RemoteException re) {
7723                throw re.rethrowFromSystemServer();
7724            }
7725        }
7726    }
7727
7728    /**
7729     * Called by the system update service to notify device and profile owners of pending system
7730     * updates.
7731     *
7732     * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
7733     * when it is known whether the pending system update is a security patch.
7734     *
7735     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
7736     *         indicating when the current pending update was first available. {@code -1} if no
7737     *         update is available.
7738     * @param isSecurityPatch {@code true} if this system update is purely a security patch;
7739     *         {@code false} if not.
7740     * @see #notifyPendingSystemUpdate(long)
7741     * @hide
7742     */
7743    @SystemApi
7744    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
7745    public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
7746        throwIfParentInstance("notifyPendingSystemUpdate");
7747        if (mService != null) {
7748            try {
7749                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
7750                        isSecurityPatch));
7751            } catch (RemoteException re) {
7752                throw re.rethrowFromSystemServer();
7753            }
7754        }
7755    }
7756
7757    /**
7758     * Called by device or profile owners to get information about a pending system update.
7759     *
7760     * @param admin Which profile or device owner this request is associated with.
7761     * @return Information about a pending system update or {@code null} if no update pending.
7762     * @throws SecurityException if {@code admin} is not a device or profile owner.
7763     * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
7764     */
7765    public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
7766        throwIfParentInstance("getPendingSystemUpdate");
7767        try {
7768            return mService.getPendingSystemUpdate(admin);
7769        } catch (RemoteException re) {
7770            throw re.rethrowFromSystemServer();
7771        }
7772    }
7773
7774    /**
7775     * Set the default response for future runtime permission requests by applications. This
7776     * function can be called by a device owner, profile owner, or by a delegate given the
7777     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7778     * The policy can allow for normal operation which prompts the user to grant a permission, or
7779     * can allow automatic granting or denying of runtime permission requests by an application.
7780     * This also applies to new permissions declared by app updates. When a permission is denied or
7781     * granted this way, the effect is equivalent to setting the permission * grant state via
7782     * {@link #setPermissionGrantState}.
7783     * <p/>
7784     * As this policy only acts on runtime permission requests, it only applies to applications
7785     * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
7786     *
7787     * @param admin Which profile or device owner this request is associated with.
7788     * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
7789     *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
7790     * @throws SecurityException if {@code admin} is not a device or profile owner.
7791     * @see #setPermissionGrantState
7792     * @see #setDelegatedScopes
7793     * @see #DELEGATION_PERMISSION_GRANT
7794     */
7795    public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
7796        throwIfParentInstance("setPermissionPolicy");
7797        try {
7798            mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
7799        } catch (RemoteException re) {
7800            throw re.rethrowFromSystemServer();
7801        }
7802    }
7803
7804    /**
7805     * Returns the current runtime permission policy set by the device or profile owner. The
7806     * default is {@link #PERMISSION_POLICY_PROMPT}.
7807     *
7808     * @param admin Which profile or device owner this request is associated with.
7809     * @return the current policy for future permission requests.
7810     */
7811    public int getPermissionPolicy(ComponentName admin) {
7812        throwIfParentInstance("getPermissionPolicy");
7813        try {
7814            return mService.getPermissionPolicy(admin);
7815        } catch (RemoteException re) {
7816            throw re.rethrowFromSystemServer();
7817        }
7818    }
7819
7820    /**
7821     * Sets the grant state of a runtime permission for a specific application. The state can be
7822     * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
7823     * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
7824     * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
7825     * the permission is granted and the user cannot manage it through the UI. This method can only
7826     * be called by a profile owner, device owner, or a delegate given the
7827     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7828     * <p/>
7829     * Note that user cannot manage other permissions in the affected group through the UI
7830     * either and their granted state will be kept as the current value. Thus, it's recommended that
7831     * you set the grant state of all the permissions in the affected group.
7832     * <p/>
7833     * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
7834     * the permission. It retains the previous grant, if any.
7835     * <p/>
7836     * Permissions can be granted or revoked only for applications built with a
7837     * {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
7838     *
7839     * @param admin Which profile or device owner this request is associated with.
7840     * @param packageName The application to grant or revoke a permission to.
7841     * @param permission The permission to grant or revoke.
7842     * @param grantState The permission grant state which is one of
7843     *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
7844     *            {@link #PERMISSION_GRANT_STATE_GRANTED},
7845     * @return whether the permission was successfully granted or revoked.
7846     * @throws SecurityException if {@code admin} is not a device or profile owner.
7847     * @see #PERMISSION_GRANT_STATE_DENIED
7848     * @see #PERMISSION_GRANT_STATE_DEFAULT
7849     * @see #PERMISSION_GRANT_STATE_GRANTED
7850     * @see #setDelegatedScopes
7851     * @see #DELEGATION_PERMISSION_GRANT
7852     */
7853    public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName,
7854            String permission, int grantState) {
7855        throwIfParentInstance("setPermissionGrantState");
7856        try {
7857            return mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
7858                    permission, grantState);
7859        } catch (RemoteException re) {
7860            throw re.rethrowFromSystemServer();
7861        }
7862    }
7863
7864    /**
7865     * Returns the current grant state of a runtime permission for a specific application. This
7866     * function can be called by a device owner, profile owner, or by a delegate given the
7867     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7868     *
7869     * @param admin Which profile or device owner this request is associated with, or {@code null}
7870     *            if the caller is a permission grant delegate.
7871     * @param packageName The application to check the grant state for.
7872     * @param permission The permission to check for.
7873     * @return the current grant state specified by device policy. If the profile or device owner
7874     *         has not set a grant state, the return value is
7875     *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
7876     *         permission is currently granted for the package.
7877     *         <p/>
7878     *         If a grant state was set by the profile or device owner, then the return value will
7879     *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
7880     *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
7881     *         currently denied or granted.
7882     * @throws SecurityException if {@code admin} is not a device or profile owner.
7883     * @see #setPermissionGrantState(ComponentName, String, String, int)
7884     * @see PackageManager#checkPermission(String, String)
7885     * @see #setDelegatedScopes
7886     * @see #DELEGATION_PERMISSION_GRANT
7887     */
7888    public int getPermissionGrantState(@Nullable ComponentName admin, String packageName,
7889            String permission) {
7890        throwIfParentInstance("getPermissionGrantState");
7891        try {
7892            return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
7893                    permission);
7894        } catch (RemoteException re) {
7895            throw re.rethrowFromSystemServer();
7896        }
7897    }
7898
7899    /**
7900     * Returns whether it is possible for the caller to initiate provisioning of a managed profile
7901     * or device, setting itself as the device or profile owner.
7902     *
7903     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7904     * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
7905     * @return whether provisioning a managed profile or device is possible.
7906     * @throws IllegalArgumentException if the supplied action is not valid.
7907     */
7908    public boolean isProvisioningAllowed(@NonNull String action) {
7909        throwIfParentInstance("isProvisioningAllowed");
7910        try {
7911            return mService.isProvisioningAllowed(action, mContext.getPackageName());
7912        } catch (RemoteException re) {
7913            throw re.rethrowFromSystemServer();
7914        }
7915    }
7916
7917    /**
7918     * Checks whether it is possible to initiate provisioning a managed device,
7919     * profile or user, setting the given package as owner.
7920     *
7921     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7922     *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
7923     *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
7924     *        {@link #ACTION_PROVISION_MANAGED_USER}
7925     * @param packageName The package of the component that would be set as device, user, or profile
7926     *        owner.
7927     * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
7928     * @hide
7929     */
7930    public @ProvisioningPreCondition int checkProvisioningPreCondition(
7931            String action, @NonNull String packageName) {
7932        try {
7933            return mService.checkProvisioningPreCondition(action, packageName);
7934        } catch (RemoteException re) {
7935            throw re.rethrowFromSystemServer();
7936        }
7937    }
7938
7939    /**
7940     * Return if this user is a managed profile of another user. An admin can become the profile
7941     * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
7942     * user with {@link #createAndManageUser}
7943     * @param admin Which profile owner this request is associated with.
7944     * @return if this user is a managed profile of another user.
7945     */
7946    public boolean isManagedProfile(@NonNull ComponentName admin) {
7947        throwIfParentInstance("isManagedProfile");
7948        try {
7949            return mService.isManagedProfile(admin);
7950        } catch (RemoteException re) {
7951            throw re.rethrowFromSystemServer();
7952        }
7953    }
7954
7955    /**
7956     * @hide
7957     * Return if this user is a system-only user. An admin can manage a device from a system only
7958     * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
7959     * @param admin Which device owner this request is associated with.
7960     * @return if this user is a system-only user.
7961     */
7962    public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
7963        try {
7964            return mService.isSystemOnlyUser(admin);
7965        } catch (RemoteException re) {
7966            throw re.rethrowFromSystemServer();
7967        }
7968    }
7969
7970    /**
7971     * Called by device owner to get the MAC address of the Wi-Fi device.
7972     *
7973     * @param admin Which device owner this request is associated with.
7974     * @return the MAC address of the Wi-Fi device, or null when the information is not available.
7975     *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
7976     *         <p>
7977     *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
7978     * @throws SecurityException if {@code admin} is not a device owner.
7979     */
7980    public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
7981        throwIfParentInstance("getWifiMacAddress");
7982        try {
7983            return mService.getWifiMacAddress(admin);
7984        } catch (RemoteException re) {
7985            throw re.rethrowFromSystemServer();
7986        }
7987    }
7988
7989    /**
7990     * Called by device owner to reboot the device. If there is an ongoing call on the device,
7991     * throws an {@link IllegalStateException}.
7992     * @param admin Which device owner the request is associated with.
7993     * @throws IllegalStateException if device has an ongoing call.
7994     * @throws SecurityException if {@code admin} is not a device owner.
7995     * @see TelephonyManager#CALL_STATE_IDLE
7996     */
7997    public void reboot(@NonNull ComponentName admin) {
7998        throwIfParentInstance("reboot");
7999        try {
8000            mService.reboot(admin);
8001        } catch (RemoteException re) {
8002            throw re.rethrowFromSystemServer();
8003        }
8004    }
8005
8006    /**
8007     * Called by a device admin to set the short support message. This will be displayed to the user
8008     * in settings screens where funtionality has been disabled by the admin. The message should be
8009     * limited to a short statement such as "This setting is disabled by your administrator. Contact
8010     * someone@example.com for support." If the message is longer than 200 characters it may be
8011     * truncated.
8012     * <p>
8013     * If the short support message needs to be localized, it is the responsibility of the
8014     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
8015     * and set a new version of this string accordingly.
8016     *
8017     * @see #setLongSupportMessage
8018     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8019     * @param message Short message to be displayed to the user in settings or null to clear the
8020     *            existing message.
8021     * @throws SecurityException if {@code admin} is not an active administrator.
8022     */
8023    public void setShortSupportMessage(@NonNull ComponentName admin,
8024            @Nullable CharSequence message) {
8025        throwIfParentInstance("setShortSupportMessage");
8026        if (mService != null) {
8027            try {
8028                mService.setShortSupportMessage(admin, message);
8029            } catch (RemoteException e) {
8030                throw e.rethrowFromSystemServer();
8031            }
8032        }
8033    }
8034
8035    /**
8036     * Called by a device admin to get the short support message.
8037     *
8038     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8039     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
8040     *         null if no message has been set.
8041     * @throws SecurityException if {@code admin} is not an active administrator.
8042     */
8043    public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
8044        throwIfParentInstance("getShortSupportMessage");
8045        if (mService != null) {
8046            try {
8047                return mService.getShortSupportMessage(admin);
8048            } catch (RemoteException e) {
8049                throw e.rethrowFromSystemServer();
8050            }
8051        }
8052        return null;
8053    }
8054
8055    /**
8056     * Called by a device admin to set the long support message. This will be displayed to the user
8057     * in the device administators settings screen.
8058     * <p>
8059     * If the long support message needs to be localized, it is the responsibility of the
8060     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
8061     * and set a new version of this string accordingly.
8062     *
8063     * @see #setShortSupportMessage
8064     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8065     * @param message Long message to be displayed to the user in settings or null to clear the
8066     *            existing message.
8067     * @throws SecurityException if {@code admin} is not an active administrator.
8068     */
8069    public void setLongSupportMessage(@NonNull ComponentName admin,
8070            @Nullable CharSequence message) {
8071        throwIfParentInstance("setLongSupportMessage");
8072        if (mService != null) {
8073            try {
8074                mService.setLongSupportMessage(admin, message);
8075            } catch (RemoteException e) {
8076                throw e.rethrowFromSystemServer();
8077            }
8078        }
8079    }
8080
8081    /**
8082     * Called by a device admin to get the long support message.
8083     *
8084     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8085     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
8086     *         null if no message has been set.
8087     * @throws SecurityException if {@code admin} is not an active administrator.
8088     */
8089    public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
8090        throwIfParentInstance("getLongSupportMessage");
8091        if (mService != null) {
8092            try {
8093                return mService.getLongSupportMessage(admin);
8094            } catch (RemoteException e) {
8095                throw e.rethrowFromSystemServer();
8096            }
8097        }
8098        return null;
8099    }
8100
8101    /**
8102     * Called by the system to get the short support message.
8103     *
8104     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8105     * @param userHandle user id the admin is running as.
8106     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
8107     *
8108     * @hide
8109     */
8110    public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
8111            int userHandle) {
8112        if (mService != null) {
8113            try {
8114                return mService.getShortSupportMessageForUser(admin, userHandle);
8115            } catch (RemoteException e) {
8116                throw e.rethrowFromSystemServer();
8117            }
8118        }
8119        return null;
8120    }
8121
8122
8123    /**
8124     * Called by the system to get the long support message.
8125     *
8126     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8127     * @param userHandle user id the admin is running as.
8128     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
8129     *
8130     * @hide
8131     */
8132    public @Nullable CharSequence getLongSupportMessageForUser(
8133            @NonNull ComponentName admin, int userHandle) {
8134        if (mService != null) {
8135            try {
8136                return mService.getLongSupportMessageForUser(admin, userHandle);
8137            } catch (RemoteException e) {
8138                throw e.rethrowFromSystemServer();
8139            }
8140        }
8141        return null;
8142    }
8143
8144    /**
8145     * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
8146     * whose calls act on the parent profile.
8147     *
8148     * <p>The following methods are supported for the parent instance, all other methods will
8149     * throw a SecurityException when called on the parent instance:
8150     * <ul>
8151     * <li>{@link #getPasswordQuality}</li>
8152     * <li>{@link #setPasswordQuality}</li>
8153     * <li>{@link #getPasswordMinimumLength}</li>
8154     * <li>{@link #setPasswordMinimumLength}</li>
8155     * <li>{@link #getPasswordMinimumUpperCase}</li>
8156     * <li>{@link #setPasswordMinimumUpperCase}</li>
8157     * <li>{@link #getPasswordMinimumLowerCase}</li>
8158     * <li>{@link #setPasswordMinimumLowerCase}</li>
8159     * <li>{@link #getPasswordMinimumLetters}</li>
8160     * <li>{@link #setPasswordMinimumLetters}</li>
8161     * <li>{@link #getPasswordMinimumNumeric}</li>
8162     * <li>{@link #setPasswordMinimumNumeric}</li>
8163     * <li>{@link #getPasswordMinimumSymbols}</li>
8164     * <li>{@link #setPasswordMinimumSymbols}</li>
8165     * <li>{@link #getPasswordMinimumNonLetter}</li>
8166     * <li>{@link #setPasswordMinimumNonLetter}</li>
8167     * <li>{@link #getPasswordHistoryLength}</li>
8168     * <li>{@link #setPasswordHistoryLength}</li>
8169     * <li>{@link #getPasswordExpirationTimeout}</li>
8170     * <li>{@link #setPasswordExpirationTimeout}</li>
8171     * <li>{@link #getPasswordExpiration}</li>
8172     * <li>{@link #getPasswordMaximumLength}</li>
8173     * <li>{@link #isActivePasswordSufficient}</li>
8174     * <li>{@link #getCurrentFailedPasswordAttempts}</li>
8175     * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
8176     * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
8177     * <li>{@link #getMaximumTimeToLock}</li>
8178     * <li>{@link #setMaximumTimeToLock}</li>
8179     * <li>{@link #lockNow}</li>
8180     * <li>{@link #getKeyguardDisabledFeatures}</li>
8181     * <li>{@link #setKeyguardDisabledFeatures}</li>
8182     * <li>{@link #getTrustAgentConfiguration}</li>
8183     * <li>{@link #setTrustAgentConfiguration}</li>
8184     * <li>{@link #getRequiredStrongAuthTimeout}</li>
8185     * <li>{@link #setRequiredStrongAuthTimeout}</li>
8186     * </ul>
8187     *
8188     * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
8189     * @throws SecurityException if {@code admin} is not a profile owner.
8190     */
8191    public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
8192        throwIfParentInstance("getParentProfileInstance");
8193        try {
8194            if (!mService.isManagedProfile(admin)) {
8195                throw new SecurityException("The current user does not have a parent profile.");
8196            }
8197            return new DevicePolicyManager(mContext, mService, true);
8198        } catch (RemoteException e) {
8199            throw e.rethrowFromSystemServer();
8200        }
8201    }
8202
8203    /**
8204     * Called by device owner to control the security logging feature.
8205     *
8206     * <p> Security logs contain various information intended for security auditing purposes.
8207     * See {@link SecurityEvent} for details.
8208     *
8209     * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
8210     * are unaffiliated secondary users or profiles on the device, regardless of whether the
8211     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
8212     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
8213     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
8214     *
8215     * @param admin Which device owner this request is associated with.
8216     * @param enabled whether security logging should be enabled or not.
8217     * @throws SecurityException if {@code admin} is not a device owner.
8218     * @see #setAffiliationIds
8219     * @see #retrieveSecurityLogs
8220     */
8221    public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
8222        throwIfParentInstance("setSecurityLoggingEnabled");
8223        try {
8224            mService.setSecurityLoggingEnabled(admin, enabled);
8225        } catch (RemoteException re) {
8226            throw re.rethrowFromSystemServer();
8227        }
8228    }
8229
8230    /**
8231     * Return whether security logging is enabled or not by the device owner.
8232     *
8233     * <p>Can only be called by the device owner, otherwise a {@link SecurityException} will be
8234     * thrown.
8235     *
8236     * @param admin Which device owner this request is associated with.
8237     * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
8238     * @throws SecurityException if {@code admin} is not a device owner.
8239     */
8240    public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
8241        throwIfParentInstance("isSecurityLoggingEnabled");
8242        try {
8243            return mService.isSecurityLoggingEnabled(admin);
8244        } catch (RemoteException re) {
8245            throw re.rethrowFromSystemServer();
8246        }
8247    }
8248
8249    /**
8250     * Called by device owner to retrieve all new security logging entries since the last call to
8251     * this API after device boots.
8252     *
8253     * <p> Access to the logs is rate limited and it will only return new logs after the device
8254     * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
8255     *
8256     * <p>If there is any other user or profile on the device, it must be affiliated with the
8257     * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8258     *
8259     * @param admin Which device owner this request is associated with.
8260     * @return the new batch of security logs which is a list of {@link SecurityEvent},
8261     * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
8262     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8263     * profile or secondary user that is not affiliated with the device.
8264     * @see #isAffiliatedUser
8265     * @see DeviceAdminReceiver#onSecurityLogsAvailable
8266     */
8267    public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
8268        throwIfParentInstance("retrieveSecurityLogs");
8269        try {
8270            ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
8271            if (list != null) {
8272                return list.getList();
8273            } else {
8274                // Rate limit exceeded.
8275                return null;
8276            }
8277        } catch (RemoteException re) {
8278            throw re.rethrowFromSystemServer();
8279        }
8280    }
8281
8282    /**
8283     * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
8284     * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
8285     * @hide
8286     */
8287    public long forceSecurityLogs() {
8288        if (mService == null) {
8289            return 0;
8290        }
8291        try {
8292            return mService.forceSecurityLogs();
8293        } catch (RemoteException re) {
8294            throw re.rethrowFromSystemServer();
8295        }
8296    }
8297
8298    /**
8299     * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
8300     * profile.
8301     *
8302     * @hide
8303     */
8304    public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
8305        mContext.checkSelfPermission(
8306                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
8307        if (!uInfo.isManagedProfile()) {
8308            throw new SecurityException("The user " + uInfo.id
8309                    + " does not have a parent profile.");
8310        }
8311        return new DevicePolicyManager(mContext, mService, true);
8312    }
8313
8314    /**
8315     * Called by a device or profile owner to restrict packages from using metered data.
8316     *
8317     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
8318     * @param packageNames the list of package names to be restricted.
8319     * @return a list of package names which could not be restricted.
8320     * @throws SecurityException if {@code admin} is not a device or profile owner.
8321     */
8322    public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
8323            @NonNull List<String> packageNames) {
8324        throwIfParentInstance("setMeteredDataDisabled");
8325        if (mService != null) {
8326            try {
8327                return mService.setMeteredDataDisabledPackages(admin, packageNames);
8328            } catch (RemoteException re) {
8329                throw re.rethrowFromSystemServer();
8330            }
8331        }
8332        return packageNames;
8333    }
8334
8335    /**
8336     * Called by a device or profile owner to retrieve the list of packages which are restricted
8337     * by the admin from using metered data.
8338     *
8339     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
8340     * @return the list of restricted package names.
8341     * @throws SecurityException if {@code admin} is not a device or profile owner.
8342     */
8343    public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
8344        throwIfParentInstance("getMeteredDataDisabled");
8345        if (mService != null) {
8346            try {
8347                return mService.getMeteredDataDisabledPackages(admin);
8348            } catch (RemoteException re) {
8349                throw re.rethrowFromSystemServer();
8350            }
8351        }
8352        return new ArrayList<>();
8353    }
8354
8355    /**
8356     * Called by the system to check if a package is restricted from using metered data
8357     * by {@param admin}.
8358     *
8359     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
8360     * @param packageName the package whose restricted status is needed.
8361     * @param userId the user to which {@param packageName} belongs.
8362     * @return {@code true} if the package is restricted by admin, otherwise {@code false}
8363     * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
8364     * @hide
8365     */
8366    public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
8367            String packageName, @UserIdInt int userId) {
8368        throwIfParentInstance("getMeteredDataDisabledForUser");
8369        if (mService != null) {
8370            try {
8371                return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
8372            } catch (RemoteException re) {
8373                throw re.rethrowFromSystemServer();
8374            }
8375        }
8376        return false;
8377    }
8378
8379    /**
8380     * Called by device owners to retrieve device logs from before the device's last reboot.
8381     * <p>
8382     * <strong> This API is not supported on all devices. Calling this API on unsupported devices
8383     * will result in {@code null} being returned. The device logs are retrieved from a RAM region
8384     * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
8385     * about data corruption when parsing. </strong>
8386     *
8387     * <p>If there is any other user or profile on the device, it must be affiliated with the
8388     * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8389     *
8390     * @param admin Which device owner this request is associated with.
8391     * @return Device logs from before the latest reboot of the system, or {@code null} if this API
8392     *         is not supported on the device.
8393     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8394     * profile or secondary user that is not affiliated with the device.
8395     * @see #isAffiliatedUser
8396     * @see #retrieveSecurityLogs
8397     */
8398    public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
8399            @NonNull ComponentName admin) {
8400        throwIfParentInstance("retrievePreRebootSecurityLogs");
8401        try {
8402            ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
8403            if (list != null) {
8404                return list.getList();
8405            } else {
8406                return null;
8407            }
8408        } catch (RemoteException re) {
8409            throw re.rethrowFromSystemServer();
8410        }
8411    }
8412
8413    /**
8414     * Called by a profile owner of a managed profile to set the color used for customization. This
8415     * color is used as background color of the confirm credentials screen for that user. The
8416     * default color is teal (#00796B).
8417     * <p>
8418     * The confirm credentials screen can be created using
8419     * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
8420     *
8421     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8422     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
8423     * @throws SecurityException if {@code admin} is not a profile owner.
8424     */
8425    public void setOrganizationColor(@NonNull ComponentName admin, int color) {
8426        throwIfParentInstance("setOrganizationColor");
8427        try {
8428            // always enforce alpha channel to have 100% opacity
8429            color |= 0xFF000000;
8430            mService.setOrganizationColor(admin, color);
8431        } catch (RemoteException re) {
8432            throw re.rethrowFromSystemServer();
8433        }
8434    }
8435
8436    /**
8437     * @hide
8438     *
8439     * Sets the color used for customization.
8440     *
8441     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
8442     * @param userId which user to set the color to.
8443     * @RequiresPermission(allOf = {
8444     *       Manifest.permission.MANAGE_USERS,
8445     *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
8446     */
8447    public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
8448        try {
8449            // always enforce alpha channel to have 100% opacity
8450            color |= 0xFF000000;
8451            mService.setOrganizationColorForUser(color, userId);
8452        } catch (RemoteException re) {
8453            throw re.rethrowFromSystemServer();
8454        }
8455    }
8456
8457    /**
8458     * Called by a profile owner of a managed profile to retrieve the color used for customization.
8459     * This color is used as background color of the confirm credentials screen for that user.
8460     *
8461     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8462     * @return The 24bit (0xRRGGBB) representation of the color to be used.
8463     * @throws SecurityException if {@code admin} is not a profile owner.
8464     */
8465    public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
8466        throwIfParentInstance("getOrganizationColor");
8467        try {
8468            return mService.getOrganizationColor(admin);
8469        } catch (RemoteException re) {
8470            throw re.rethrowFromSystemServer();
8471        }
8472    }
8473
8474    /**
8475     * @hide
8476     * Retrieve the customization color for a given user.
8477     *
8478     * @param userHandle The user id of the user we're interested in.
8479     * @return The 24bit (0xRRGGBB) representation of the color to be used.
8480     */
8481    public @ColorInt int getOrganizationColorForUser(int userHandle) {
8482        try {
8483            return mService.getOrganizationColorForUser(userHandle);
8484        } catch (RemoteException re) {
8485            throw re.rethrowFromSystemServer();
8486        }
8487    }
8488
8489    /**
8490     * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
8491     * the organization under management.
8492     *
8493     * <p>If the organization name needs to be localized, it is the responsibility of the {@link
8494     * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
8495     * a new version of this string accordingly.
8496     *
8497     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8498     * @param title The organization name or {@code null} to clear a previously set name.
8499     * @throws SecurityException if {@code admin} is not a device or profile owner.
8500     */
8501    public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
8502        throwIfParentInstance("setOrganizationName");
8503        try {
8504            mService.setOrganizationName(admin, title);
8505        } catch (RemoteException re) {
8506            throw re.rethrowFromSystemServer();
8507        }
8508    }
8509
8510    /**
8511     * Called by a profile owner of a managed profile to retrieve the name of the organization under
8512     * management.
8513     *
8514     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8515     * @return The organization name or {@code null} if none is set.
8516     * @throws SecurityException if {@code admin} is not a profile owner.
8517     */
8518    public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
8519        throwIfParentInstance("getOrganizationName");
8520        try {
8521            return mService.getOrganizationName(admin);
8522        } catch (RemoteException re) {
8523            throw re.rethrowFromSystemServer();
8524        }
8525    }
8526
8527    /**
8528     * Called by the system to retrieve the name of the organization managing the device.
8529     *
8530     * @return The organization name or {@code null} if none is set.
8531     * @throws SecurityException if the caller is not the device owner, does not hold the
8532     *         MANAGE_USERS permission and is not the system.
8533     *
8534     * @hide
8535     */
8536    @SystemApi
8537    @TestApi
8538    @SuppressLint("Doclava125")
8539    public @Nullable CharSequence getDeviceOwnerOrganizationName() {
8540        try {
8541            return mService.getDeviceOwnerOrganizationName();
8542        } catch (RemoteException re) {
8543            throw re.rethrowFromSystemServer();
8544        }
8545    }
8546
8547    /**
8548     * Retrieve the default title message used in the confirm credentials screen for a given user.
8549     *
8550     * @param userHandle The user id of the user we're interested in.
8551     * @return The organization name or {@code null} if none is set.
8552     *
8553     * @hide
8554     */
8555    public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
8556        try {
8557            return mService.getOrganizationNameForUser(userHandle);
8558        } catch (RemoteException re) {
8559            throw re.rethrowFromSystemServer();
8560        }
8561    }
8562
8563    /**
8564     * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
8565     *         return {@link #STATE_USER_UNMANAGED}
8566     * @hide
8567     */
8568    @SystemApi
8569    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8570    @UserProvisioningState
8571    public int getUserProvisioningState() {
8572        throwIfParentInstance("getUserProvisioningState");
8573        if (mService != null) {
8574            try {
8575                return mService.getUserProvisioningState();
8576            } catch (RemoteException e) {
8577                throw e.rethrowFromSystemServer();
8578            }
8579        }
8580        return STATE_USER_UNMANAGED;
8581    }
8582
8583    /**
8584     * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
8585     *
8586     * @param state to store
8587     * @param userHandle for user
8588     * @hide
8589     */
8590    public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
8591        if (mService != null) {
8592            try {
8593                mService.setUserProvisioningState(state, userHandle);
8594            } catch (RemoteException e) {
8595                throw e.rethrowFromSystemServer();
8596            }
8597        }
8598    }
8599
8600    /**
8601     * Indicates the entity that controls the device or profile owner. Two users/profiles are
8602     * affiliated if the set of ids set by their device or profile owners intersect.
8603     *
8604     * <p>A user/profile that is affiliated with the device owner user is considered to be
8605     * affiliated with the device.
8606     *
8607     * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
8608     * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user or profile
8609     * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
8610     * affiliation ids are set by its profile owner as soon as possible after the user/profile is
8611     * created.
8612     *
8613     * @param admin Which profile or device owner this request is associated with.
8614     * @param ids A set of opaque non-empty affiliation ids.
8615     *
8616     * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
8617     * @see #isAffiliatedUser
8618     */
8619    public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
8620        throwIfParentInstance("setAffiliationIds");
8621        if (ids == null) {
8622            throw new IllegalArgumentException("ids must not be null");
8623        }
8624        try {
8625            mService.setAffiliationIds(admin, new ArrayList<>(ids));
8626        } catch (RemoteException e) {
8627            throw e.rethrowFromSystemServer();
8628        }
8629    }
8630
8631    /**
8632     * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
8633     * empty set if none have been set.
8634     */
8635    public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
8636        throwIfParentInstance("getAffiliationIds");
8637        try {
8638            return new ArraySet<>(mService.getAffiliationIds(admin));
8639        } catch (RemoteException e) {
8640            throw e.rethrowFromSystemServer();
8641        }
8642    }
8643
8644    /**
8645     * Returns whether this user/profile is affiliated with the device.
8646     * <p>
8647     * By definition, the user that the device owner runs on is always affiliated with the device.
8648     * Any other user/profile is considered affiliated with the device if the set specified by its
8649     * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
8650     * @see #setAffiliationIds
8651     */
8652    public boolean isAffiliatedUser() {
8653        throwIfParentInstance("isAffiliatedUser");
8654        try {
8655            return mService.isAffiliatedUser();
8656        } catch (RemoteException e) {
8657            throw e.rethrowFromSystemServer();
8658        }
8659    }
8660
8661    /**
8662     * @hide
8663     * Returns whether the uninstall for {@code packageName} for the current user is in queue
8664     * to be started
8665     * @param packageName the package to check for
8666     * @return whether the uninstall intent for {@code packageName} is pending
8667     */
8668    public boolean isUninstallInQueue(String packageName) {
8669        try {
8670            return mService.isUninstallInQueue(packageName);
8671        } catch (RemoteException re) {
8672            throw re.rethrowFromSystemServer();
8673        }
8674    }
8675
8676    /**
8677     * @hide
8678     * @param packageName the package containing active DAs to be uninstalled
8679     */
8680    public void uninstallPackageWithActiveAdmins(String packageName) {
8681        try {
8682            mService.uninstallPackageWithActiveAdmins(packageName);
8683        } catch (RemoteException re) {
8684            throw re.rethrowFromSystemServer();
8685        }
8686    }
8687
8688    /**
8689     * @hide
8690     * Remove a test admin synchronously without sending it a broadcast about being removed.
8691     * If the admin is a profile owner or device owner it will still be removed.
8692     *
8693     * @param userHandle user id to remove the admin for.
8694     * @param admin The administration compononent to remove.
8695     * @throws SecurityException if the caller is not shell / root or the admin package
8696     *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
8697     */
8698    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
8699        try {
8700            mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
8701        } catch (RemoteException re) {
8702            throw re.rethrowFromSystemServer();
8703        }
8704    }
8705
8706    /**
8707     * Returns whether the device has been provisioned.
8708     *
8709     * <p>Not for use by third-party applications.
8710     *
8711     * @hide
8712     */
8713    @SystemApi
8714    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8715    public boolean isDeviceProvisioned() {
8716        try {
8717            return mService.isDeviceProvisioned();
8718        } catch (RemoteException re) {
8719            throw re.rethrowFromSystemServer();
8720        }
8721    }
8722
8723    /**
8724      * Writes that the provisioning configuration has been applied.
8725      *
8726      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
8727      * permission.
8728      *
8729      * <p>Not for use by third-party applications.
8730      *
8731      * @hide
8732      */
8733    @SystemApi
8734    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8735    public void setDeviceProvisioningConfigApplied() {
8736        try {
8737            mService.setDeviceProvisioningConfigApplied();
8738        } catch (RemoteException re) {
8739            throw re.rethrowFromSystemServer();
8740        }
8741    }
8742
8743    /**
8744     * Returns whether the provisioning configuration has been applied.
8745     *
8746     * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
8747     *
8748     * <p>Not for use by third-party applications.
8749     *
8750     * @return whether the provisioning configuration has been applied.
8751     *
8752     * @hide
8753     */
8754    @SystemApi
8755    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8756    public boolean isDeviceProvisioningConfigApplied() {
8757        try {
8758            return mService.isDeviceProvisioningConfigApplied();
8759        } catch (RemoteException re) {
8760            throw re.rethrowFromSystemServer();
8761        }
8762    }
8763
8764    /**
8765     * @hide
8766     * Force update user setup completed status. This API has no effect on user build.
8767     * @throws {@link SecurityException} if the caller has no
8768     *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
8769     *         not {@link UserHandle#SYSTEM_USER}
8770     */
8771    public void forceUpdateUserSetupComplete() {
8772        try {
8773            mService.forceUpdateUserSetupComplete();
8774        } catch (RemoteException re) {
8775            throw re.rethrowFromSystemServer();
8776        }
8777    }
8778
8779    private void throwIfParentInstance(String functionName) {
8780        if (mParentInstance) {
8781            throw new SecurityException(functionName + " cannot be called on the parent instance");
8782        }
8783    }
8784
8785    /**
8786     * Allows the device owner to enable or disable the backup service.
8787     *
8788     * <p> Backup service manages all backup and restore mechanisms on the device. Setting this to
8789     * false will prevent data from being backed up or restored.
8790     *
8791     * <p> Backup service is off by default when device owner is present.
8792     *
8793     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8794     * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
8795     * @throws SecurityException if {@code admin} is not a device owner.
8796     */
8797    public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
8798        throwIfParentInstance("setBackupServiceEnabled");
8799        try {
8800            mService.setBackupServiceEnabled(admin, enabled);
8801        } catch (RemoteException re) {
8802            throw re.rethrowFromSystemServer();
8803        }
8804    }
8805
8806    /**
8807     * Return whether the backup service is enabled by the device owner.
8808     *
8809     * <p> Backup service manages all backup and restore mechanisms on the device.
8810     *
8811     * @return {@code true} if backup service is enabled, {@code false} otherwise.
8812     * @see #setBackupServiceEnabled
8813     */
8814    public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
8815        throwIfParentInstance("isBackupServiceEnabled");
8816        try {
8817            return mService.isBackupServiceEnabled(admin);
8818        } catch (RemoteException re) {
8819            throw re.rethrowFromSystemServer();
8820        }
8821    }
8822
8823    /**
8824     * Makes backups mandatory and enforces the usage of the specified backup transport.
8825     *
8826     * <p>When a {@code null} backup transport is specified, backups are made optional again.
8827     * <p>Only device owner can call this method.
8828     * <p>If backups were disabled and a non-null backup transport {@link ComponentName} is
8829     * specified, backups will be enabled.
8830     * <p> If the backup service is disabled after the mandatory backup transport has been set, the
8831     * mandatory backup transport is cleared.
8832     *
8833     * <p>NOTE: The method shouldn't be called on the main thread.
8834     *
8835     * @param admin admin Which {@link DeviceAdminReceiver} this request is associated with.
8836     * @param backupTransportComponent The backup transport layer to be used for mandatory backups.
8837     * @return {@code true} if the backup transport was successfully set; {@code false} otherwise.
8838     * @throws SecurityException if {@code admin} is not a device owner.
8839     * @hide
8840     */
8841    @WorkerThread
8842    public boolean setMandatoryBackupTransport(
8843            @NonNull ComponentName admin,
8844            @Nullable ComponentName backupTransportComponent) {
8845        throwIfParentInstance("setMandatoryBackupTransport");
8846        try {
8847            return mService.setMandatoryBackupTransport(admin, backupTransportComponent);
8848        } catch (RemoteException re) {
8849            throw re.rethrowFromSystemServer();
8850        }
8851    }
8852
8853    /**
8854     * Returns the backup transport which has to be used for backups if backups are mandatory or
8855     * {@code null} if backups are not mandatory.
8856     *
8857     * @return a {@link ComponentName} of the backup transport layer to be used if backups are
8858     *         mandatory or {@code null} if backups are not mandatory.
8859     * @hide
8860     */
8861    public ComponentName getMandatoryBackupTransport() {
8862        throwIfParentInstance("getMandatoryBackupTransport");
8863        try {
8864            return mService.getMandatoryBackupTransport();
8865        } catch (RemoteException re) {
8866            throw re.rethrowFromSystemServer();
8867        }
8868    }
8869
8870
8871    /**
8872     * Called by a device owner to control the network logging feature.
8873     *
8874     * <p> Network logs contain DNS lookup and connect() library call events. The following library
8875     *     functions are recorded while network logging is active:
8876     *     <ul>
8877     *       <li>{@code getaddrinfo()}</li>
8878     *       <li>{@code gethostbyname()}</li>
8879     *       <li>{@code connect()}</li>
8880     *     </ul>
8881     *
8882     * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
8883     *     full system call logging; event reporting is enabled by default for all processes but not
8884     *     strongly enforced.
8885     *     Events from applications using alternative implementations of libc, making direct kernel
8886     *     calls, or deliberately obfuscating traffic may not be recorded.
8887     *
8888     * <p> Some common network events may not be reported. For example:
8889     *     <ul>
8890     *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
8891     *           an alternative system for name resolution, and so avoid calling
8892     *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
8893     *       <li>Applications may use datagram sockets for performance reasons, for example
8894     *           for a game client. Calling {@code connect()} is unnecessary for this kind of
8895     *           socket, so it will not trigger a network event.</li>
8896     *     </ul>
8897     *
8898     * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
8899     *     always-on VPN service.
8900     *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
8901     *     and {@link android.net.VpnService} for details.
8902     *
8903     * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
8904     * are unaffiliated secondary users or profiles on the device, regardless of whether the
8905     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
8906     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
8907     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
8908     *
8909     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8910     * @param enabled whether network logging should be enabled or not.
8911     * @throws SecurityException if {@code admin} is not a device owner.
8912     * @see #setAffiliationIds
8913     * @see #retrieveNetworkLogs
8914     */
8915    public void setNetworkLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
8916        throwIfParentInstance("setNetworkLoggingEnabled");
8917        try {
8918            mService.setNetworkLoggingEnabled(admin, enabled);
8919        } catch (RemoteException re) {
8920            throw re.rethrowFromSystemServer();
8921        }
8922    }
8923
8924    /**
8925     * Return whether network logging is enabled by a device owner.
8926     *
8927     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
8928     * be {@code null} if the caller has MANAGE_USERS permission.
8929     * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
8930     * @throws SecurityException if {@code admin} is not a device owner and caller has
8931     * no MANAGE_USERS permission
8932     */
8933    public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
8934        throwIfParentInstance("isNetworkLoggingEnabled");
8935        try {
8936            return mService.isNetworkLoggingEnabled(admin);
8937        } catch (RemoteException re) {
8938            throw re.rethrowFromSystemServer();
8939        }
8940    }
8941
8942    /**
8943     * Called by device owner to retrieve the most recent batch of network logging events.
8944     * A device owner has to provide a batchToken provided as part of
8945     * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
8946     * token of the most recent available batch of logs, {@code null} will be returned.
8947     *
8948     * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
8949     *
8950     * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
8951     *
8952     * <p> Access to the logs is rate limited and this method will only return a new batch of logs
8953     * after the device device owner has been notified via
8954     * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
8955     *
8956     * <p>If a secondary user or profile is created, calling this method will throw a
8957     * {@link SecurityException} until all users become affiliated again. It will also no longer be
8958     * possible to retrieve the network logs batch with the most recent batchToken provided
8959     * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
8960     * {@link DevicePolicyManager#setAffiliationIds}.
8961     *
8962     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8963     * @param batchToken A token of the batch to retrieve
8964     * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
8965     *        {@code null} if the batch represented by batchToken is no longer available or if
8966     *        logging is disabled.
8967     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8968     * profile or secondary user that is not affiliated with the device.
8969     * @see #setAffiliationIds
8970     * @see DeviceAdminReceiver#onNetworkLogsAvailable
8971     */
8972    public @Nullable List<NetworkEvent> retrieveNetworkLogs(@NonNull ComponentName admin,
8973            long batchToken) {
8974        throwIfParentInstance("retrieveNetworkLogs");
8975        try {
8976            return mService.retrieveNetworkLogs(admin, batchToken);
8977        } catch (RemoteException re) {
8978            throw re.rethrowFromSystemServer();
8979        }
8980    }
8981
8982    /**
8983     * Called by a device owner to bind to a service from a profile owner or vice versa.
8984     * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
8985     * device/profile owners are allowed to bind to services of another profile/device owner.
8986     * <p>
8987     * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
8988     * Note that the {@link Context} used to obtain this
8989     * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
8990     * to bind to the {@link android.app.Service}.
8991     *
8992     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8993     * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
8994     *        explicit component name or a package name to match an
8995     *        {@link IntentFilter} published by a service.
8996     * @param conn Receives information as the service is started and stopped in main thread. This
8997     *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
8998     * @param flags Operation options for the binding operation. See
8999     *        {@link Context#bindService(Intent, ServiceConnection, int)}.
9000     * @param targetUser Which user to bind to. Must be one of the users returned by
9001     *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
9002     *        be thrown.
9003     * @return If you have successfully bound to the service, {@code true} is returned;
9004     *         {@code false} is returned if the connection is not made and you will not
9005     *         receive the service object.
9006     *
9007     * @see Context#bindService(Intent, ServiceConnection, int)
9008     * @see #getBindDeviceAdminTargetUsers(ComponentName)
9009     */
9010    public boolean bindDeviceAdminServiceAsUser(
9011            @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
9012            @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
9013        throwIfParentInstance("bindDeviceAdminServiceAsUser");
9014        // Keep this in sync with ContextImpl.bindServiceCommon.
9015        try {
9016            final IServiceConnection sd = mContext.getServiceDispatcher(
9017                    conn, mContext.getMainThreadHandler(), flags);
9018            serviceIntent.prepareToLeaveProcess(mContext);
9019            return mService.bindDeviceAdminServiceAsUser(admin,
9020                    mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
9021                    sd, flags, targetUser.getIdentifier());
9022        } catch (RemoteException re) {
9023            throw re.rethrowFromSystemServer();
9024        }
9025    }
9026
9027    /**
9028     * Returns the list of target users that the calling device or profile owner can use when
9029     * calling {@link #bindDeviceAdminServiceAsUser}.
9030     * <p>
9031     * A device owner can bind to a service from a profile owner and vice versa, provided that:
9032     * <ul>
9033     * <li>Both belong to the same package name.
9034     * <li>Both users are affiliated. See {@link #setAffiliationIds}.
9035     * </ul>
9036     */
9037    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
9038        throwIfParentInstance("getBindDeviceAdminTargetUsers");
9039        try {
9040            return mService.getBindDeviceAdminTargetUsers(admin);
9041        } catch (RemoteException re) {
9042            throw re.rethrowFromSystemServer();
9043        }
9044    }
9045
9046    /**
9047     * Called by the system to get the time at which the device owner last retrieved security
9048     * logging entries.
9049     *
9050     * @return the time at which the device owner most recently retrieved security logging entries,
9051     *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
9052     * @throws SecurityException if the caller is not the device owner, does not hold the
9053     *         MANAGE_USERS permission and is not the system.
9054     *
9055     * @hide
9056     */
9057    @TestApi
9058    public long getLastSecurityLogRetrievalTime() {
9059        try {
9060            return mService.getLastSecurityLogRetrievalTime();
9061        } catch (RemoteException re) {
9062            throw re.rethrowFromSystemServer();
9063        }
9064    }
9065
9066    /**
9067     * Called by the system to get the time at which the device owner last requested a bug report.
9068     *
9069     * @return the time at which the device owner most recently requested a bug report, in
9070     *         milliseconds since epoch; -1 if a bug report was never requested.
9071     * @throws SecurityException if the caller is not the device owner, does not hold the
9072     *         MANAGE_USERS permission and is not the system.
9073     *
9074     * @hide
9075     */
9076    @TestApi
9077    public long getLastBugReportRequestTime() {
9078        try {
9079            return mService.getLastBugReportRequestTime();
9080        } catch (RemoteException re) {
9081            throw re.rethrowFromSystemServer();
9082        }
9083    }
9084
9085    /**
9086     * Called by the system to get the time at which the device owner last retrieved network logging
9087     * events.
9088     *
9089     * @return the time at which the device owner most recently retrieved network logging events, in
9090     *         milliseconds since epoch; -1 if network logging events were never retrieved.
9091     * @throws SecurityException if the caller is not the device owner, does not hold the
9092     *         MANAGE_USERS permission and is not the system.
9093     *
9094     * @hide
9095     */
9096    @TestApi
9097    public long getLastNetworkLogRetrievalTime() {
9098        try {
9099            return mService.getLastNetworkLogRetrievalTime();
9100        } catch (RemoteException re) {
9101            throw re.rethrowFromSystemServer();
9102        }
9103    }
9104
9105    /**
9106     * Called by the system to find out whether the current user's IME was set by the device/profile
9107     * owner or the user.
9108     *
9109     * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
9110     *         otherwise.
9111     * @throws SecurityException if the caller is not the device owner/profile owner.
9112     *
9113     * @hide
9114     */
9115    @TestApi
9116    public boolean isCurrentInputMethodSetByOwner() {
9117        try {
9118            return mService.isCurrentInputMethodSetByOwner();
9119        } catch (RemoteException re) {
9120            throw re.rethrowFromSystemServer();
9121        }
9122    }
9123
9124    /**
9125     * Called by the system to get a list of CA certificates that were installed by the device or
9126     * profile owner.
9127     *
9128     * <p> The caller must be the target user's device owner/profile Owner or hold the
9129     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
9130     *
9131     * @param user The user for whom to retrieve information.
9132     * @return list of aliases identifying CA certificates installed by the device or profile owner
9133     * @throws SecurityException if the caller does not have permission to retrieve information
9134     *         about the given user's CA certificates.
9135     *
9136     * @hide
9137     */
9138    @TestApi
9139    public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
9140        try {
9141            return mService.getOwnerInstalledCaCerts(user).getList();
9142        } catch (RemoteException re) {
9143            throw re.rethrowFromSystemServer();
9144        }
9145    }
9146
9147    /**
9148     * Called by the device owner or profile owner to clear application user data of a given
9149     * package. The behaviour of this is equivalent to the target application calling
9150     * {@link android.app.ActivityManager#clearApplicationUserData()}.
9151     *
9152     * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
9153     * external storage or user dictionary. This data will not be wiped by calling this API.
9154     *
9155     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9156     * @param packageName The name of the package which will have its user data wiped.
9157     * @param executor The executor through which the listener should be invoked.
9158     * @param listener A callback object that will inform the caller when the clearing is done.
9159     * @throws SecurityException if the caller is not the device owner/profile owner.
9160     */
9161    public void clearApplicationUserData(@NonNull ComponentName admin,
9162            @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
9163            @NonNull OnClearApplicationUserDataListener listener) {
9164        throwIfParentInstance("clearAppData");
9165        Preconditions.checkNotNull(executor);
9166        Preconditions.checkNotNull(listener);
9167        try {
9168            mService.clearApplicationUserData(admin, packageName,
9169                    new IPackageDataObserver.Stub() {
9170                        public void onRemoveCompleted(String pkg, boolean succeeded) {
9171                            executor.execute(() ->
9172                                    listener.onApplicationUserDataCleared(pkg, succeeded));
9173                        }
9174                    });
9175        } catch (RemoteException re) {
9176            throw re.rethrowFromSystemServer();
9177        }
9178    }
9179
9180    /**
9181     * Called by a device owner to specify whether logout is enabled for all secondary users. The
9182     * system may show a logout button that stops the user and switches back to the primary user.
9183     *
9184     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9185     * @param enabled whether logout should be enabled or not.
9186     * @throws SecurityException if {@code admin} is not a device owner.
9187     */
9188    public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
9189        throwIfParentInstance("setLogoutEnabled");
9190        try {
9191            mService.setLogoutEnabled(admin, enabled);
9192        } catch (RemoteException re) {
9193            throw re.rethrowFromSystemServer();
9194        }
9195    }
9196
9197    /**
9198     * Returns whether logout is enabled by a device owner.
9199     *
9200     * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
9201     */
9202    public boolean isLogoutEnabled() {
9203        throwIfParentInstance("isLogoutEnabled");
9204        try {
9205            return mService.isLogoutEnabled();
9206        } catch (RemoteException re) {
9207            throw re.rethrowFromSystemServer();
9208        }
9209    }
9210
9211    /**
9212     * Callback used in {@link #clearApplicationUserData}
9213     * to indicate that the clearing of an application's user data is done.
9214     */
9215    public interface OnClearApplicationUserDataListener {
9216        /**
9217         * Method invoked when clearing the application user data has completed.
9218         *
9219         * @param packageName The name of the package which had its user data cleared.
9220         * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
9221         *                  apps and protected system packages.
9222         */
9223        void onApplicationUserDataCleared(String packageName, boolean succeeded);
9224    }
9225
9226    /**
9227     * Returns set of system apps that should be removed during provisioning.
9228     *
9229     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9230     * @param userId ID of the user to be provisioned.
9231     * @param provisioningAction action indicating type of provisioning, should be one of
9232     * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
9233     * {@link #ACTION_PROVISION_MANAGED_USER}.
9234     *
9235     * @hide
9236     */
9237    public Set<String> getDisallowedSystemApps(ComponentName admin, int userId,
9238            String provisioningAction) {
9239        try {
9240            return new ArraySet<>(
9241                    mService.getDisallowedSystemApps(admin, userId, provisioningAction));
9242        } catch (RemoteException re) {
9243            throw re.rethrowFromSystemServer();
9244        }
9245    }
9246
9247    /**
9248     * Changes the current administrator to another one. All policies from the current
9249     * administrator are migrated to the new administrator. The whole operation is atomic -
9250     * the transfer is either complete or not done at all.
9251     *
9252     * <p>Depending on the current administrator (device owner, profile owner), you have the
9253     * following expected behaviour:
9254     * <ul>
9255     *     <li>A device owner can only be transferred to a new device owner</li>
9256     *     <li>A profile owner can only be transferred to a new profile owner</li>
9257     * </ul>
9258     *
9259     * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
9260     * will be received in the
9261     * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
9262     * callback of the new administrator.
9263     *
9264     * <p>The transfer has failed if the original administrator is still the corresponding owner
9265     * after calling this method.
9266     *
9267     * <p>The incoming target administrator must have the
9268     * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
9269     * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
9270     * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
9271     * {@link IllegalArgumentException} will be thrown.
9272     *
9273     * @param admin which {@link DeviceAdminReceiver} this request is associated with
9274     * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
9275     * @param bundle data to be sent to the new administrator
9276     * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
9277     * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
9278     * are components in the same package or {@code target} is not an active admin
9279     */
9280    public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
9281            @Nullable PersistableBundle bundle) {
9282        throwIfParentInstance("transferOwnership");
9283        try {
9284            mService.transferOwnership(admin, target, bundle);
9285        } catch (RemoteException re) {
9286            throw re.rethrowFromSystemServer();
9287        }
9288    }
9289
9290    /**
9291     * Called by a device owner to specify the user session start message. This may be displayed
9292     * during a user switch.
9293     * <p>
9294     * The message should be limited to a short statement or it may be truncated.
9295     * <p>
9296     * If the message needs to be localized, it is the responsibility of the
9297     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9298     * and set a new version of this message accordingly.
9299     *
9300     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9301     * @param startUserSessionMessage message for starting user session, or {@code null} to use
9302     * system default message.
9303     * @throws SecurityException if {@code admin} is not a device owner.
9304     */
9305    public void setStartUserSessionMessage(
9306            @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
9307        throwIfParentInstance("setStartUserSessionMessage");
9308        try {
9309            mService.setStartUserSessionMessage(admin, startUserSessionMessage);
9310        } catch (RemoteException re) {
9311            throw re.rethrowFromSystemServer();
9312        }
9313    }
9314
9315    /**
9316     * Called by a device owner to specify the user session end message. This may be displayed
9317     * during a user switch.
9318     * <p>
9319     * The message should be limited to a short statement or it may be truncated.
9320     * <p>
9321     * If the message needs to be localized, it is the responsibility of the
9322     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9323     * and set a new version of this message accordingly.
9324     *
9325     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9326     * @param endUserSessionMessage message for ending user session, or {@code null} to use system
9327     * default message.
9328     * @throws SecurityException if {@code admin} is not a device owner.
9329     */
9330    public void setEndUserSessionMessage(
9331            @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
9332        throwIfParentInstance("setEndUserSessionMessage");
9333        try {
9334            mService.setEndUserSessionMessage(admin, endUserSessionMessage);
9335        } catch (RemoteException re) {
9336            throw re.rethrowFromSystemServer();
9337        }
9338    }
9339
9340    /**
9341     * Returns the user session start message.
9342     *
9343     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9344     * @throws SecurityException if {@code admin} is not a device owner.
9345     */
9346    public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
9347        throwIfParentInstance("getStartUserSessionMessage");
9348        try {
9349            return mService.getStartUserSessionMessage(admin);
9350        } catch (RemoteException re) {
9351            throw re.rethrowFromSystemServer();
9352        }
9353    }
9354
9355    /**
9356     * Returns the user session end message.
9357     *
9358     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9359     * @throws SecurityException if {@code admin} is not a device owner.
9360     */
9361    public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
9362        throwIfParentInstance("getEndUserSessionMessage");
9363        try {
9364            return mService.getEndUserSessionMessage(admin);
9365        } catch (RemoteException re) {
9366            throw re.rethrowFromSystemServer();
9367        }
9368    }
9369
9370    /**
9371     * Called by device owner to add an override APN.
9372     *
9373     * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
9374     * override APN. Update the existing conflicted APN with
9375     * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
9376     * <p>Two override APNs are considered to conflict when all the following APIs return
9377     * the same values on both override APNs:
9378     * <ul>
9379     *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
9380     *   <li>{@link ApnSetting#getApnName()}</li>
9381     *   <li>{@link ApnSetting#getProxyAddress()}</li>
9382     *   <li>{@link ApnSetting#getProxyPort()}</li>
9383     *   <li>{@link ApnSetting#getMmsProxyAddress()}</li>
9384     *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
9385     *   <li>{@link ApnSetting#getMmsc()}</li>
9386     *   <li>{@link ApnSetting#isEnabled()}</li>
9387     *   <li>{@link ApnSetting#getMvnoType()}</li>
9388     *   <li>{@link ApnSetting#getProtocol()}</li>
9389     *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
9390     * </ul>
9391     *
9392     * @param admin which {@link DeviceAdminReceiver} this request is associated with
9393     * @param apnSetting the override APN to insert
9394     * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
9395     *         the database.
9396     * @throws SecurityException if {@code admin} is not a device owner.
9397     *
9398     * @see #setOverrideApnsEnabled(ComponentName, boolean)
9399     */
9400    public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
9401        throwIfParentInstance("addOverrideApn");
9402        if (mService != null) {
9403            try {
9404                return mService.addOverrideApn(admin, apnSetting);
9405            } catch (RemoteException e) {
9406                throw e.rethrowFromSystemServer();
9407            }
9408        }
9409        return -1;
9410    }
9411
9412    /**
9413     * Called by device owner to update an override APN.
9414     *
9415     * <p>This method may returns {@code false} if there is no override APN with the given
9416     * {@code apnId}.
9417     * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
9418     * existing override APN. Update the existing conflicted APN instead.
9419     * <p>See {@link #addOverrideApn} for the definition of conflict.
9420     *
9421     * @param admin which {@link DeviceAdminReceiver} this request is associated with
9422     * @param apnId the {@code id} of the override APN to update
9423     * @param apnSetting the override APN to update
9424     * @return {@code true} if the required override APN is successfully updated,
9425     *         {@code false} otherwise.
9426     * @throws SecurityException if {@code admin} is not a device owner.
9427     *
9428     * @see #setOverrideApnsEnabled(ComponentName, boolean)
9429     */
9430    public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
9431            @NonNull ApnSetting apnSetting) {
9432        throwIfParentInstance("updateOverrideApn");
9433        if (mService != null) {
9434            try {
9435                return mService.updateOverrideApn(admin, apnId, apnSetting);
9436            } catch (RemoteException e) {
9437                throw e.rethrowFromSystemServer();
9438            }
9439        }
9440        return false;
9441    }
9442
9443    /**
9444     * Called by device owner to remove an override APN.
9445     *
9446     * <p>This method may returns {@code false} if there is no override APN with the given
9447     * {@code apnId}.
9448     *
9449     * @param admin which {@link DeviceAdminReceiver} this request is associated with
9450     * @param apnId the {@code id} of the override APN to remove
9451     * @return {@code true} if the required override APN is successfully removed, {@code false}
9452     *         otherwise.
9453     * @throws SecurityException if {@code admin} is not a device owner.
9454     *
9455     * @see #setOverrideApnsEnabled(ComponentName, boolean)
9456     */
9457    public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
9458        throwIfParentInstance("removeOverrideApn");
9459        if (mService != null) {
9460            try {
9461                return mService.removeOverrideApn(admin, apnId);
9462            } catch (RemoteException e) {
9463                throw e.rethrowFromSystemServer();
9464            }
9465        }
9466        return false;
9467    }
9468
9469    /**
9470     * Called by device owner to get all override APNs inserted by device owner.
9471     *
9472     * @param admin which {@link DeviceAdminReceiver} this request is associated with
9473     * @return A list of override APNs inserted by device owner.
9474     * @throws SecurityException if {@code admin} is not a device owner.
9475     *
9476     * @see #setOverrideApnsEnabled(ComponentName, boolean)
9477     */
9478    public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
9479        throwIfParentInstance("getOverrideApns");
9480        if (mService != null) {
9481            try {
9482                return mService.getOverrideApns(admin);
9483            } catch (RemoteException e) {
9484                throw e.rethrowFromSystemServer();
9485            }
9486        }
9487        return Collections.emptyList();
9488    }
9489
9490    /**
9491     * Called by device owner to set if override APNs should be enabled.
9492     * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
9493     * modified by the device owner. When enabled, only override APNs are in use, any other APNs
9494     * are ignored.
9495     *
9496     * @param admin which {@link DeviceAdminReceiver} this request is associated with
9497     * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
9498     * @throws SecurityException if {@code admin} is not a device owner.
9499     */
9500    public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
9501        throwIfParentInstance("setOverrideApnEnabled");
9502        if (mService != null) {
9503            try {
9504                mService.setOverrideApnsEnabled(admin, enabled);
9505            } catch (RemoteException e) {
9506                throw e.rethrowFromSystemServer();
9507            }
9508        }
9509    }
9510
9511    /**
9512     * Called by device owner to check if override APNs are currently enabled.
9513     *
9514     * @param admin which {@link DeviceAdminReceiver} this request is associated with
9515     * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
9516     * @throws SecurityException if {@code admin} is not a device owner.
9517     *
9518     * @see #setOverrideApnsEnabled(ComponentName, boolean)
9519     */
9520    public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
9521        throwIfParentInstance("isOverrideApnEnabled");
9522        if (mService != null) {
9523            try {
9524                return mService.isOverrideApnEnabled(admin);
9525            } catch (RemoteException e) {
9526                throw e.rethrowFromSystemServer();
9527            }
9528        }
9529        return false;
9530    }
9531
9532    /**
9533     * Returns the data passed from the current administrator to the new administrator during an
9534     * ownership transfer. This is the same {@code bundle} passed in
9535     * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
9536     * persisted until the profile owner or device owner is removed.
9537     *
9538     * <p>This is the same <code>bundle</code> received in the
9539     * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
9540     * Use this method to retrieve it after the transfer as long as the new administrator is the
9541     * active device or profile owner.
9542     *
9543     * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
9544     *
9545     * @see #transferOwnership
9546     * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
9547     * @throws SecurityException if the caller is not a device or profile owner.
9548     */
9549    @Nullable
9550    public PersistableBundle getTransferOwnershipBundle() {
9551        throwIfParentInstance("getTransferOwnershipBundle");
9552        try {
9553            return mService.getTransferOwnershipBundle();
9554        } catch (RemoteException re) {
9555            throw re.rethrowFromSystemServer();
9556        }
9557    }
9558}
9559