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