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