DevicePolicyManager.java revision ec68b46bc85b2317053da7e2933876fc6e51ac2f
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.PackageManager;
43import android.content.pm.PackageManager.NameNotFoundException;
44import android.content.pm.ParceledListSlice;
45import android.content.pm.UserInfo;
46import android.graphics.Bitmap;
47import android.net.ProxyInfo;
48import android.net.Uri;
49import android.os.Bundle;
50import android.os.Parcelable;
51import android.os.PersistableBundle;
52import android.os.Process;
53import android.os.RemoteCallback;
54import android.os.RemoteException;
55import android.os.UserHandle;
56import android.os.UserManager;
57import android.provider.ContactsContract.Directory;
58import android.provider.Settings;
59import android.security.Credentials;
60import android.service.restrictions.RestrictionsReceiver;
61import android.telephony.TelephonyManager;
62import android.util.ArraySet;
63import android.util.Log;
64
65import com.android.internal.annotations.VisibleForTesting;
66import com.android.org.conscrypt.TrustedCertificateStore;
67
68import java.io.ByteArrayInputStream;
69import java.io.IOException;
70import java.lang.annotation.Retention;
71import java.lang.annotation.RetentionPolicy;
72import java.net.InetSocketAddress;
73import java.net.Proxy;
74import java.security.KeyFactory;
75import java.security.NoSuchAlgorithmException;
76import java.security.PrivateKey;
77import java.security.cert.Certificate;
78import java.security.cert.CertificateException;
79import java.security.cert.CertificateFactory;
80import java.security.cert.X509Certificate;
81import java.security.spec.InvalidKeySpecException;
82import java.security.spec.PKCS8EncodedKeySpec;
83import java.util.ArrayList;
84import java.util.Arrays;
85import java.util.Collections;
86import java.util.List;
87import java.util.Set;
88
89/**
90 * Public interface for managing policies enforced on a device. Most clients of this class must be
91 * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
92 * administrator</a>. Additionally, a device administrator may be registered as either a profile or
93 * device owner. A given method is accessible to all device administrators unless the documentation
94 * for that method specifies that it is restricted to either device or profile owners. Any
95 * application calling an api may only pass as an argument a device administrator component it
96 * owns. Otherwise, a {@link SecurityException} will be thrown.
97 * <div class="special reference">
98 * <h3>Developer Guides</h3>
99 * <p>
100 * For more information about managing policies for device administration, read the <a href=
101 * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
102 * guide. </div>
103 */
104@SystemService(Context.DEVICE_POLICY_SERVICE)
105public class DevicePolicyManager {
106    private static String TAG = "DevicePolicyManager";
107
108    private final Context mContext;
109    private final IDevicePolicyManager mService;
110    private final boolean mParentInstance;
111
112    /** @hide */
113    public DevicePolicyManager(Context context, IDevicePolicyManager service) {
114        this(context, service, false);
115    }
116
117    /** @hide */
118    @VisibleForTesting
119    protected DevicePolicyManager(Context context, IDevicePolicyManager service,
120            boolean parentInstance) {
121        mContext = context;
122        mService = service;
123        mParentInstance = parentInstance;
124    }
125
126    /** @hide test will override it. */
127    @VisibleForTesting
128    protected int myUserId() {
129        return UserHandle.myUserId();
130    }
131
132    /**
133     * Activity action: Starts the provisioning flow which sets up a managed profile.
134     *
135     * <p>A managed profile allows data separation for example for the usage of a
136     * device as a personal and corporate device. The user which provisioning is started from and
137     * the managed profile share a launcher.
138     *
139     * <p>This intent will typically be sent by a mobile device management application (MDM).
140     * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
141     * control over the profile.
142     *
143     * <p>It is possible to check if provisioning is allowed or not by querying the method
144     * {@link #isProvisioningAllowed(String)}.
145     *
146     * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
147     * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
148     * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
149     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
150     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
151     *
152     * <p>The intent may also contain the following extras:
153     * <ul>
154     * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
155     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
156     * {@link android.os.Build.VERSION_CODES#N}</li>
157     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
158     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
159     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
160     * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
161     * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
162     * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
163     * </ul>
164     *
165     * <p>When managed provisioning has completed, broadcasts are sent to the application specified
166     * in the provisioning intent. The
167     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
168     * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
169     * the primary profile.
170     *
171     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
172     * completed, along with the above broadcast, activity intent
173     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the application specified in
174     * the provisioning intent.
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 application on the profile that requested provisioning. In
862     * the device owner case the profile is the primary user.
863     *
864     * @see #ACTION_PROVISION_MANAGED_PROFILE
865     * @see #ACTION_PROVISION_MANAGED_DEVICE
866     */
867    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
868    public static final String ACTION_PROVISIONING_SUCCESSFUL =
869            "android.app.action.PROVISIONING_SUCCESSFUL";
870
871    /**
872     * A boolean extra indicating whether device encryption can be skipped as part of device owner
873     * or managed profile provisioning.
874     *
875     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
876     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
877     *
878     * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
879     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
880     */
881    public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
882             "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
883
884    /**
885     * A {@link Uri} extra pointing to a logo image. This image will be shown during the
886     * provisioning. If this extra is not passed, a default image will be shown.
887     * <h5>The following URI schemes are accepted:</h5>
888     * <ul>
889     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
890     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
891     * </ul>
892     *
893     * <p> It is the responsibility of the caller to provide an image with a reasonable
894     * pixel density for the device.
895     *
896     * <p> If a content: URI is passed, the intent should have the flag
897     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
898     * {@link android.content.ClipData} of the intent too.
899     *
900     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
901     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
902     */
903    public static final String EXTRA_PROVISIONING_LOGO_URI =
904            "android.app.extra.PROVISIONING_LOGO_URI";
905
906    /**
907     * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
908     * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
909     * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
910     * content.
911     *
912     * <p> The extra typically contains one disclaimer from the company of mobile device
913     * management application (MDM), and one disclaimer from the organization.
914     *
915     * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
916     *
917     * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
918     *
919     * <p> Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
920     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
921     */
922    public static final String EXTRA_PROVISIONING_DISCLAIMERS =
923            "android.app.extra.PROVISIONING_DISCLAIMERS";
924
925    /**
926     * A String extra of localized disclaimer header.
927     *
928     * <p> The extra is typically the company name of mobile device management application (MDM)
929     * or the organization name.
930     *
931     * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
932     *
933     * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
934     * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
935     * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
936     *
937     * <pre>
938     *  &lt;meta-data
939     *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
940     *      android:resource="@string/disclaimer_header"
941     * /&gt;</pre>
942     */
943    public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
944            "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
945
946    /**
947     * A {@link Uri} extra pointing to disclaimer content.
948     *
949     * <h5>The following URI schemes are accepted:</h5>
950     * <ul>
951     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
952     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
953     * </ul>
954     *
955     * <p> Styled text is supported in the disclaimer content. The content is parsed by
956     * {@link android.text.Html#fromHtml(String)} and displayed in a
957     * {@link android.widget.TextView}.
958     *
959     * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
960     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
961     * {@link android.content.ClipData} of the intent too.
962     *
963     * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
964     *
965     * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
966     * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
967     * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
968     *
969     * <pre>
970     *  &lt;meta-data
971     *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
972     *      android:resource="@string/disclaimer_content"
973     * /&gt;</pre>
974     */
975    public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
976            "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
977
978    /**
979     * A boolean extra indicating if user setup should be skipped, for when provisioning is started
980     * during setup-wizard.
981     *
982     * <p>If unspecified, defaults to {@code true} to match the behavior in
983     * {@link android.os.Build.VERSION_CODES#M} and earlier.
984     *
985     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or
986     * {@link #ACTION_PROVISION_MANAGED_USER}.
987     *
988     * @hide
989     */
990    public static final String EXTRA_PROVISIONING_SKIP_USER_SETUP =
991            "android.app.extra.PROVISIONING_SKIP_USER_SETUP";
992
993    /**
994     * A boolean extra indicating if the user consent steps from the provisioning flow should be
995     * skipped. If unspecified, defaults to {@code false}.
996     *
997     * It can only be used by an existing device owner trying to create a managed profile via
998     * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
999     */
1000    public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1001            "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1002
1003    /**
1004     * This MIME type is used for starting the device owner provisioning.
1005     *
1006     * <p>During device owner provisioning a device admin app is set as the owner of the device.
1007     * A device owner has full control over the device. The device owner can not be modified by the
1008     * user and the only way of resetting the device is if the device owner app calls a factory
1009     * reset.
1010     *
1011     * <p> A typical use case would be a device that is owned by a company, but used by either an
1012     * employee or client.
1013     *
1014     * <p> The NFC message must be sent to an unprovisioned device.
1015     *
1016     * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1017     * contains the following properties:
1018     * <ul>
1019     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1020     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1021     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1022     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1023     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1024     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1025     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1026     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1027     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1028     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1029     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1030     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1031     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1032     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1033     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1034     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from
1035     * {@link android.os.Build.VERSION_CODES#M} </li></ul>
1036     *
1037     * <p>
1038     * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1039     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1040     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1041     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1042     */
1043    public static final String MIME_TYPE_PROVISIONING_NFC
1044        = "application/com.android.managedprovisioning";
1045
1046    /**
1047     * Activity action: ask the user to add a new device administrator to the system.
1048     * The desired policy is the ComponentName of the policy in the
1049     * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
1050     * bring the user through adding the device administrator to the system (or
1051     * allowing them to reject it).
1052     *
1053     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1054     * field to provide the user with additional explanation (in addition
1055     * to your component's description) about what is being added.
1056     *
1057     * <p>If your administrator is already active, this will ordinarily return immediately (without
1058     * user intervention).  However, if your administrator has been updated and is requesting
1059     * additional uses-policy flags, the user will be presented with the new list.  New policies
1060     * will not be available to the updated administrator until the user has accepted the new list.
1061     */
1062    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1063    public static final String ACTION_ADD_DEVICE_ADMIN
1064            = "android.app.action.ADD_DEVICE_ADMIN";
1065
1066    /**
1067     * @hide
1068     * Activity action: ask the user to add a new device administrator as the profile owner
1069     * for this user. Only system apps can launch this intent.
1070     *
1071     * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
1072     * extra field. This will invoke a UI to bring the user through adding the profile owner admin
1073     * to remotely control restrictions on the user.
1074     *
1075     * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
1076     * result of whether or not the user approved the action. If approved, the result will
1077     * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
1078     * as a profile owner.
1079     *
1080     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1081     * field to provide the user with additional explanation (in addition
1082     * to your component's description) about what is being added.
1083     *
1084     * <p>If there is already a profile owner active or the caller is not a system app, the
1085     * operation will return a failure result.
1086     */
1087    @SystemApi
1088    public static final String ACTION_SET_PROFILE_OWNER
1089            = "android.app.action.SET_PROFILE_OWNER";
1090
1091    /**
1092     * @hide
1093     * Name of the profile owner admin that controls the user.
1094     */
1095    @SystemApi
1096    public static final String EXTRA_PROFILE_OWNER_NAME
1097            = "android.app.extra.PROFILE_OWNER_NAME";
1098
1099    /**
1100     * Broadcast action: send when any policy admin changes a policy.
1101     * This is generally used to find out when a new policy is in effect.
1102     *
1103     * @hide
1104     */
1105    public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1106            = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
1107
1108    /**
1109     * Broadcast action: sent when the device owner is set, changed or cleared.
1110     *
1111     * This broadcast is sent only to the primary user.
1112     * @see #ACTION_PROVISION_MANAGED_DEVICE
1113     */
1114    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1115    public static final String ACTION_DEVICE_OWNER_CHANGED
1116            = "android.app.action.DEVICE_OWNER_CHANGED";
1117
1118    /**
1119     * The ComponentName of the administrator component.
1120     *
1121     * @see #ACTION_ADD_DEVICE_ADMIN
1122     */
1123    public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
1124
1125    /**
1126     * An optional CharSequence providing additional explanation for why the
1127     * admin is being added.
1128     *
1129     * @see #ACTION_ADD_DEVICE_ADMIN
1130     */
1131    public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
1132
1133    /**
1134     * Constant to indicate the feature of disabling the camera. Used as argument to
1135     * {@link #createAdminSupportIntent(String)}.
1136     * @see #setCameraDisabled(ComponentName, boolean)
1137     */
1138    public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
1139
1140    /**
1141     * Constant to indicate the feature of disabling screen captures. Used as argument to
1142     * {@link #createAdminSupportIntent(String)}.
1143     * @see #setScreenCaptureDisabled(ComponentName, boolean)
1144     */
1145    public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
1146
1147    /**
1148     * A String indicating a specific restricted feature. Can be a user restriction from the
1149     * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1150     * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
1151     * @see #createAdminSupportIntent(String)
1152     * @hide
1153     */
1154    @TestApi
1155    public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1156
1157    /**
1158     * Activity action: have the user enter a new password. This activity should
1159     * be launched after using {@link #setPasswordQuality(ComponentName, int)},
1160     * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
1161     * enter a new password that meets the current requirements. You can use
1162     * {@link #isActivePasswordSufficient()} to determine whether you need to
1163     * have the user select a new password in order to meet the current
1164     * constraints. Upon being resumed from this activity, you can check the new
1165     * password characteristics to see if they are sufficient.
1166     *
1167     * If the intent is launched from within a managed profile with a profile
1168     * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1169     * this will trigger entering a new password for the parent of the profile.
1170     * For all other cases it will trigger entering a new password for the user
1171     * or profile it is launched from.
1172     *
1173     * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1174     */
1175    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1176    public static final String ACTION_SET_NEW_PASSWORD
1177            = "android.app.action.SET_NEW_PASSWORD";
1178
1179    /**
1180     * Activity action: have the user enter a new password for the parent profile.
1181     * If the intent is launched from within a managed profile, this will trigger
1182     * entering a new password for the parent of the profile. In all other cases
1183     * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
1184     */
1185    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1186    public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1187            = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1188
1189    /**
1190     * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1191     * Network logging was enabled and the user tapped the notification.
1192     * <p class="note">This is a protected intent that can only be sent by the system.</p>
1193     * @hide
1194     */
1195    public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1196            = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1197
1198    /**
1199     * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1200     * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1201     * {@link #EXTRA_DELEGATION_SCOPES} key.
1202     *
1203     * <p class=”note”> Note: This is a protected intent that can only be sent by the system.</p>
1204     */
1205    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1206    public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1207            "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1208
1209    /**
1210     * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1211     * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1212     */
1213    public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1214
1215    /**
1216     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1217     * the parent profile to access intents sent from the managed profile.
1218     * That is, when an app in the managed profile calls
1219     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1220     * matching activity in the parent profile.
1221     */
1222    public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1223
1224    /**
1225     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1226     * the managed profile to access intents sent from the parent profile.
1227     * That is, when an app in the parent profile calls
1228     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1229     * matching activity in the managed profile.
1230     */
1231    public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1232
1233    /**
1234     * Broadcast action: notify that a new local system update policy has been set by the device
1235     * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1236     */
1237    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1238    public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1239            = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1240
1241    /**
1242     * Permission policy to prompt user for new permission requests for runtime permissions.
1243     * Already granted or denied permissions are not affected by this.
1244     */
1245    public static final int PERMISSION_POLICY_PROMPT = 0;
1246
1247    /**
1248     * Permission policy to always grant new permission requests for runtime permissions.
1249     * Already granted or denied permissions are not affected by this.
1250     */
1251    public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1252
1253    /**
1254     * Permission policy to always deny new permission requests for runtime permissions.
1255     * Already granted or denied permissions are not affected by this.
1256     */
1257    public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1258
1259    /**
1260     * Runtime permission state: The user can manage the permission
1261     * through the UI.
1262     */
1263    public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1264
1265    /**
1266     * Runtime permission state: The permission is granted to the app
1267     * and the user cannot manage the permission through the UI.
1268     */
1269    public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1270
1271    /**
1272     * Runtime permission state: The permission is denied to the app
1273     * and the user cannot manage the permission through the UI.
1274     */
1275    public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1276
1277    /**
1278     * Delegation of certificate installation and management. This scope grants access to the
1279     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1280     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1281     */
1282    public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1283
1284    /**
1285     * Delegation of application restrictions management. This scope grants access to the
1286     * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1287     */
1288    public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1289
1290    /**
1291     * Delegation of application uninstall block. This scope grants access to the
1292     * {@link #setUninstallBlocked} API.
1293     */
1294    public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1295
1296    /**
1297     * Delegation of permission policy and permission grant state. This scope grants access to the
1298     * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1299     * and {@link #setPermissionGrantState} APIs.
1300     */
1301    public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1302
1303    /**
1304     * Delegation of package access state. This scope grants access to the
1305     * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1306     * {@link #setPackagesSuspended} APIs.
1307     */
1308    public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1309
1310    /**
1311     * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1312     * API.
1313     */
1314    public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1315
1316    /**
1317     * Delegation of management of uninstalled packages. This scope grants access to the
1318     * {@code #setKeepUninstalledPackages} and {@code #getKeepUninstalledPackages} APIs.
1319     * @hide
1320     */
1321    public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1322            "delegation-keep-uninstalled-packages";
1323
1324    /**
1325     * No management for current user in-effect. This is the default.
1326     * @hide
1327     */
1328    @SystemApi
1329    public static final int STATE_USER_UNMANAGED = 0;
1330
1331    /**
1332     * Management partially setup, user setup needs to be completed.
1333     * @hide
1334     */
1335    @SystemApi
1336    public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1337
1338    /**
1339     * Management partially setup, user setup completed.
1340     * @hide
1341     */
1342    @SystemApi
1343    public static final int STATE_USER_SETUP_COMPLETE = 2;
1344
1345    /**
1346     * Management setup and active on current user.
1347     * @hide
1348     */
1349    @SystemApi
1350    public static final int STATE_USER_SETUP_FINALIZED = 3;
1351
1352    /**
1353     * Management partially setup on a managed profile.
1354     * @hide
1355     */
1356    @SystemApi
1357    public static final int STATE_USER_PROFILE_COMPLETE = 4;
1358
1359    /**
1360     * @hide
1361     */
1362    @IntDef({STATE_USER_UNMANAGED, STATE_USER_SETUP_INCOMPLETE, STATE_USER_SETUP_COMPLETE,
1363            STATE_USER_SETUP_FINALIZED, STATE_USER_PROFILE_COMPLETE})
1364    @Retention(RetentionPolicy.SOURCE)
1365    public @interface UserProvisioningState {}
1366
1367    /**
1368     * Result code for {@link #checkProvisioningPreCondition}.
1369     *
1370     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1371     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1372     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when provisioning is allowed.
1373     *
1374     * @hide
1375     */
1376    public static final int CODE_OK = 0;
1377
1378    /**
1379     * Result code for {@link #checkProvisioningPreCondition}.
1380     *
1381     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1382     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the device already has a device
1383     * owner.
1384     *
1385     * @hide
1386     */
1387    public static final int CODE_HAS_DEVICE_OWNER = 1;
1388
1389    /**
1390     * Result code for {@link #checkProvisioningPreCondition}.
1391     *
1392     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1393     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user has a profile owner and for
1394     * {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
1395     *
1396     * @hide
1397     */
1398    public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
1399
1400    /**
1401     * Result code for {@link #checkProvisioningPreCondition}.
1402     *
1403     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1404     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user isn't running.
1405     *
1406     * @hide
1407     */
1408    public static final int CODE_USER_NOT_RUNNING = 3;
1409
1410    /**
1411     * Result code for {@link #checkProvisioningPreCondition}.
1412     *
1413     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1414     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the device has already been setup and
1415     * for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
1416     *
1417     * @hide
1418     */
1419    public static final int CODE_USER_SETUP_COMPLETED = 4;
1420
1421    /**
1422     * Code used to indicate that the device also has a user other than the system user.
1423     *
1424     * @hide
1425     */
1426    public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
1427
1428    /**
1429     * Code used to indicate that device has an account that prevents provisioning.
1430     *
1431     * @hide
1432     */
1433    public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
1434
1435    /**
1436     * Result code for {@link #checkProvisioningPreCondition}.
1437     *
1438     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1439     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the user is not a system user.
1440     *
1441     * @hide
1442     */
1443    public static final int CODE_NOT_SYSTEM_USER = 7;
1444
1445    /**
1446     * Result code for {@link #checkProvisioningPreCondition}.
1447     *
1448     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1449     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} and {@link #ACTION_PROVISION_MANAGED_USER}
1450     * when the device is a watch and is already paired.
1451     *
1452     * @hide
1453     */
1454    public static final int CODE_HAS_PAIRED = 8;
1455
1456    /**
1457     * Result code for {@link #checkProvisioningPreCondition}.
1458     *
1459     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
1460     * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
1461     *
1462     * @see {@link PackageManager#FEATURE_MANAGED_USERS}
1463     * @hide
1464     */
1465    public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
1466
1467    /**
1468     * Result code for {@link #checkProvisioningPreCondition}.
1469     *
1470     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user.
1471     *
1472     * @hide
1473     */
1474    public static final int CODE_SYSTEM_USER = 10;
1475
1476    /**
1477     * Result code for {@link #checkProvisioningPreCondition}.
1478     *
1479     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
1480     * managed profiles.
1481     *
1482     * @hide
1483     */
1484    public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
1485
1486    /**
1487     * Result code for {@link #checkProvisioningPreCondition}.
1488     *
1489     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} and
1490     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices not running with split system
1491     * user.
1492     *
1493     * @hide
1494     */
1495    public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
1496
1497    /**
1498     * Result code for {@link #checkProvisioningPreCondition}.
1499     *
1500     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1501     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1502     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices which do no support device
1503     * admins.
1504     *
1505     * @hide
1506     */
1507    public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
1508
1509    /**
1510     * Result code for {@link #checkProvisioningPreCondition}.
1511     *
1512     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the device the user is a
1513     * system user on a split system user device.
1514     *
1515     * @hide
1516     */
1517    public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
1518
1519    /**
1520     * Result code for {@link #checkProvisioningPreCondition}.
1521     *
1522     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when adding a managed profile is
1523     * disallowed by {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
1524     *
1525     * @hide
1526     */
1527    public static final int CODE_ADD_MANAGED_PROFILE_DISALLOWED = 15;
1528
1529    /**
1530     * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
1531     * conditions.
1532     *
1533     * @hide
1534     */
1535    @Retention(RetentionPolicy.SOURCE)
1536    @IntDef({CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
1537            CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
1538            CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
1539            CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
1540            CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER, CODE_ADD_MANAGED_PROFILE_DISALLOWED})
1541    public @interface ProvisioningPreCondition {}
1542
1543    /**
1544     * Service action: Action for a service that device owner and profile owner can optionally
1545     * own.  If a device owner or a profile owner has such a service, the system tries to keep
1546     * a bound connection to it, in order to keep their process always running.
1547     * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
1548     * permission.
1549     */
1550    @SdkConstant(SdkConstantType.SERVICE_ACTION)
1551    public static final String ACTION_DEVICE_ADMIN_SERVICE
1552            = "android.app.action.DEVICE_ADMIN_SERVICE";
1553
1554    /**
1555     * Return true if the given administrator component is currently active (enabled) in the system.
1556     *
1557     * @param admin The administrator component to check for.
1558     * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
1559     *         otherwise
1560     */
1561    public boolean isAdminActive(@NonNull ComponentName admin) {
1562        throwIfParentInstance("isAdminActive");
1563        return isAdminActiveAsUser(admin, myUserId());
1564    }
1565
1566    /**
1567     * @see #isAdminActive(ComponentName)
1568     * @hide
1569     */
1570    public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
1571        if (mService != null) {
1572            try {
1573                return mService.isAdminActive(admin, userId);
1574            } catch (RemoteException e) {
1575                throw e.rethrowFromSystemServer();
1576            }
1577        }
1578        return false;
1579    }
1580
1581    /**
1582     * Return true if the given administrator component is currently being removed
1583     * for the user.
1584     * @hide
1585     */
1586    public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
1587        if (mService != null) {
1588            try {
1589                return mService.isRemovingAdmin(admin, userId);
1590            } catch (RemoteException e) {
1591                throw e.rethrowFromSystemServer();
1592            }
1593        }
1594        return false;
1595    }
1596
1597    /**
1598     * Return a list of all currently active device administrators' component
1599     * names.  If there are no administrators {@code null} may be
1600     * returned.
1601     */
1602    public @Nullable List<ComponentName> getActiveAdmins() {
1603        throwIfParentInstance("getActiveAdmins");
1604        return getActiveAdminsAsUser(myUserId());
1605    }
1606
1607    /**
1608     * @see #getActiveAdmins()
1609     * @hide
1610     */
1611    public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
1612        if (mService != null) {
1613            try {
1614                return mService.getActiveAdmins(userId);
1615            } catch (RemoteException e) {
1616                throw e.rethrowFromSystemServer();
1617            }
1618        }
1619        return null;
1620    }
1621
1622    /**
1623     * Used by package administration code to determine if a package can be stopped
1624     * or uninstalled.
1625     * @hide
1626     */
1627    @SystemApi
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 #resetPassword}: don't allow other admins to change
2713     * 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 #resetPassword}: don't ask for user credentials on device boot.
2719     * If the flag is set, the device can be booted without asking for user password.
2720     * The absence of this flag does not change the current boot requirements. This flag
2721     * can be set by the device owner only. If the app is not the device owner, the flag
2722     * is ignored. Once the flag is set, it cannot be reverted back without resetting the
2723     * device to factory defaults.
2724     */
2725    public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
2726
2727    /**
2728     * Force a new device unlock password (the password needed to access the entire device, not for
2729     * individual accounts) on the user. This takes effect immediately.
2730     * <p>
2731     * <em>For device owner and profile owners targeting SDK level
2732     * {@link android.os.Build.VERSION_CODES#O} or above, this API is no longer available and will
2733     * throw {@link SecurityException}. Please use the new API {@link #resetPasswordWithToken}
2734     * instead. </em>
2735     * <p>
2736     * <em>Note: This API has been limited as of {@link android.os.Build.VERSION_CODES#N} for
2737     * device admins that are not device owner and not profile owner.
2738     * The password can now only be changed if there is currently no password set.  Device owner
2739     * and profile owner can still do this when user is unlocked and does not have a managed
2740     * profile.</em>
2741     * <p>
2742     * The given password must be sufficient for the current password quality and length constraints
2743     * as returned by {@link #getPasswordQuality(ComponentName)} and
2744     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
2745     * it will be rejected and false returned. Note that the password may be a stronger quality
2746     * (containing alphanumeric characters when the requested quality is only numeric), in which
2747     * case the currently active quality will be increased to match.
2748     * <p>
2749     * Calling with a null or empty password will clear any existing PIN, pattern or password if the
2750     * current password constraints allow it. <em>Note: This will not work in
2751     * {@link android.os.Build.VERSION_CODES#N} and later for managed profiles, or for device admins
2752     * that are not device owner or profile owner.  Once set, the password cannot be changed to null
2753     * or empty except by these admins.</em>
2754     * <p>
2755     * The calling device admin must have requested
2756     * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
2757     * not, a security exception will be thrown.
2758     *
2759     * @param password The new password for the user. Null or empty clears the password.
2760     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
2761     *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
2762     * @return Returns true if the password was applied, or false if it is not acceptable for the
2763     *         current constraints or if the user has not been decrypted yet.
2764     * @throws SecurityException if the calling application does not own an active administrator
2765     *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
2766     * @throws IllegalStateException if the calling user is locked or has a managed profile.
2767     * @throws IllegalArgumentException if the password does not meet system requirements.
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 IllegalArgumentException if the supplied token is invalid.
2810     * @throws SecurityException
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     */
2830    public boolean clearResetPasswordToken(ComponentName admin) {
2831        throwIfParentInstance("clearResetPasswordToken");
2832        if (mService != null) {
2833            try {
2834                return mService.clearResetPasswordToken(admin);
2835            } catch (RemoteException e) {
2836                throw e.rethrowFromSystemServer();
2837            }
2838        }
2839        return false;
2840    }
2841
2842    /**
2843     * Called by a profile or device owner to check if the current reset password token is active.
2844     *
2845     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2846     * @return true if the token is active, false otherwise.
2847     * @throws IllegalStateException if no token has been set.
2848     */
2849    public boolean isResetPasswordTokenActive(ComponentName admin) {
2850        throwIfParentInstance("isResetPasswordTokenActive");
2851        if (mService != null) {
2852            try {
2853                return mService.isResetPasswordTokenActive(admin);
2854            } catch (RemoteException e) {
2855                throw e.rethrowFromSystemServer();
2856            }
2857        }
2858        return false;
2859    }
2860
2861    /**
2862     * Called by device or profile owner to force set a new device unlock password or a managed
2863     * profile challenge on current user. This takes effect immediately.
2864     * <p>
2865     * Unlike {@link #resetPassword}, this API can change the password even before the user or
2866     * device is unlocked or decrypted. The supplied token must have been previously provisioned via
2867     * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
2868     * <p>
2869     * The given password must be sufficient for the current password quality and length constraints
2870     * as returned by {@link #getPasswordQuality(ComponentName)} and
2871     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
2872     * it will be rejected and false returned. Note that the password may be a stronger quality
2873     * (containing alphanumeric characters when the requested quality is only numeric), in which
2874     * case the currently active quality will be increased to match.
2875     * <p>
2876     * Calling with a null or empty password will clear any existing PIN, pattern or password if the
2877     * current password constraints allow it.
2878     *
2879     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2880     * @param password The new password for the user. Null or empty clears the password.
2881     * @param token the password reset token previously provisioned by #setResetPasswordToken.
2882     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
2883     *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
2884     * @return Returns true if the password was applied, or false if it is not acceptable for the
2885     *         current constraints.
2886     * @throws SecurityException if the calling application does not own an active administrator
2887     *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
2888     * @throws IllegalStateException if the provided token is not valid.
2889     * @throws IllegalArgumentException if the password does not meet system requirements.
2890     */
2891    public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
2892            byte[] token, int flags) {
2893        throwIfParentInstance("resetPassword");
2894        if (mService != null) {
2895            try {
2896                return mService.resetPasswordWithToken(admin, password, token, flags);
2897            } catch (RemoteException e) {
2898                throw e.rethrowFromSystemServer();
2899            }
2900        }
2901        return false;
2902    }
2903
2904    /**
2905     * Called by an application that is administering the device to set the maximum time for user
2906     * activity until the device will lock. This limits the length that the user can set. It takes
2907     * effect immediately.
2908     * <p>
2909     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
2910     * to be able to call this method; if it has not, a security exception will be thrown.
2911     * <p>
2912     * This method can be called on the {@link DevicePolicyManager} instance returned by
2913     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2914     * profile.
2915     *
2916     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2917     * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
2918     *            is no restriction.
2919     * @throws SecurityException if {@code admin} is not an active administrator or it does not use
2920     *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
2921     */
2922    public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
2923        if (mService != null) {
2924            try {
2925                mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
2926            } catch (RemoteException e) {
2927                throw e.rethrowFromSystemServer();
2928            }
2929        }
2930    }
2931
2932    /**
2933     * Retrieve the current maximum time to unlock for a particular admin or all admins that set
2934     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2935     * a separate challenge are not taken into account.
2936     *
2937     * <p>This method can be called on the {@link DevicePolicyManager} instance
2938     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2939     * restrictions on the parent profile.
2940     *
2941     * @param admin The name of the admin component to check, or {@code null} to aggregate
2942     * all admins.
2943     * @return time in milliseconds for the given admin or the minimum value (strictest) of
2944     * all admins if admin is null. Returns 0 if there are no restrictions.
2945     */
2946    public long getMaximumTimeToLock(@Nullable ComponentName admin) {
2947        return getMaximumTimeToLock(admin, myUserId());
2948    }
2949
2950    /** @hide per-user version */
2951    public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
2952        if (mService != null) {
2953            try {
2954                return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
2955            } catch (RemoteException e) {
2956                throw e.rethrowFromSystemServer();
2957            }
2958        }
2959        return 0;
2960    }
2961
2962    /**
2963     * Returns maximum time to lock that applied by all profiles in this user. We do this because we
2964     * do not have a separate timeout to lock for work challenge only.
2965     *
2966     * @hide
2967     */
2968    public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
2969        if (mService != null) {
2970            try {
2971                return mService.getMaximumTimeToLockForUserAndProfiles(userHandle);
2972            } catch (RemoteException e) {
2973                throw e.rethrowFromSystemServer();
2974            }
2975        }
2976        return 0;
2977    }
2978
2979    /**
2980     * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
2981     * strong auth (e.g. fingerprint, trust agents) times out, i.e. the user has to use a strong
2982     * authentication method like password, pin or pattern.
2983     *
2984     * <p>This timeout is used internally to reset the timer to require strong auth again after
2985     * specified timeout each time it has been successfully used.
2986     *
2987     * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
2988     *
2989     * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
2990     *
2991     * <p>The calling device admin must be a device or profile owner. If it is not,
2992     * a {@link SecurityException} will be thrown.
2993     *
2994     * <p>The calling device admin can verify the value it has set by calling
2995     * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
2996     *
2997     * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
2998     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2999     * profile.
3000     *
3001     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3002     * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
3003     *         with strong authentication method. A value of 0 means the admin is not participating
3004     *         in controlling the timeout.
3005     *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
3006     *         72 hours, respectively. Though discouraged, the admin may choose to require strong
3007     *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
3008     *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3009     *
3010     * @throws SecurityException if {@code admin} is not a device or profile owner.
3011     */
3012    public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
3013            long timeoutMs) {
3014        if (mService != null) {
3015            try {
3016                mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
3017            } catch (RemoteException e) {
3018                throw e.rethrowFromSystemServer();
3019            }
3020        }
3021    }
3022
3023    /**
3024     * Determine for how long the user will be able to use secondary, non strong auth for
3025     * authentication, since last strong method authentication (password, pin or pattern) was used.
3026     * After the returned timeout the user is required to use strong authentication method.
3027     *
3028     * <p>This method can be called on the {@link DevicePolicyManager} instance
3029     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3030     * restrictions on the parent profile.
3031     *
3032     * @param admin The name of the admin component to check, or {@code null} to aggregate
3033     *         accross all participating admins.
3034     * @return The timeout in milliseconds or 0 if not configured for the provided admin.
3035     */
3036    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
3037        return getRequiredStrongAuthTimeout(admin, myUserId());
3038    }
3039
3040    /** @hide per-user version */
3041    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
3042        if (mService != null) {
3043            try {
3044                return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
3045            } catch (RemoteException e) {
3046                throw e.rethrowFromSystemServer();
3047            }
3048        }
3049        return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
3050    }
3051
3052    /**
3053     * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
3054     * keyring. The user's credential will need to be entered again in order to derive the
3055     * credential encryption key that will be stored back in the keyring for future use.
3056     * <p>
3057     * This flag can only be used by a profile owner when locking a managed profile when
3058     * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3059     * <p>
3060     * In order to secure user data, the user will be stopped and restarted so apps should wait
3061     * until they are next run to perform further actions.
3062     */
3063    public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
3064
3065    /** @hide */
3066    @Retention(RetentionPolicy.SOURCE)
3067    @IntDef(flag=true, value={FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY})
3068    public @interface LockNowFlag {}
3069
3070    /**
3071     * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3072     * this call.
3073     * <p>
3074     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3075     * to be able to call this method; if it has not, a security exception will be thrown.
3076     * <p>
3077     * This method can be called on the {@link DevicePolicyManager} instance returned by
3078     * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3079     * <p>
3080     * Equivalent to calling {@link #lockNow(int)} with no flags.
3081     *
3082     * @throws SecurityException if the calling application does not own an active administrator
3083     *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3084     */
3085    public void lockNow() {
3086        lockNow(0);
3087    }
3088
3089    /**
3090     * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3091     * this call.
3092     * <p>
3093     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3094     * to be able to call this method; if it has not, a security exception will be thrown.
3095     * <p>
3096     * This method can be called on the {@link DevicePolicyManager} instance returned by
3097     * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3098     *
3099     * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
3100     * @throws SecurityException if the calling application does not own an active administrator
3101     *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
3102     *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
3103     *             that is not a profile
3104     *             owner of a managed profile.
3105     * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
3106     *             passed when locking the parent profile.
3107     * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
3108     *             flag is passed when {@link #getStorageEncryptionStatus} does not return
3109     *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3110     */
3111    public void lockNow(@LockNowFlag int flags) {
3112        if (mService != null) {
3113            try {
3114                mService.lockNow(flags, mParentInstance);
3115            } catch (RemoteException e) {
3116                throw e.rethrowFromSystemServer();
3117            }
3118        }
3119    }
3120
3121    /**
3122     * Flag for {@link #wipeData(int)}: also erase the device's external
3123     * storage (such as SD cards).
3124     */
3125    public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
3126
3127    /**
3128     * Flag for {@link #wipeData(int)}: also erase the factory reset protection
3129     * data.
3130     *
3131     * <p>This flag may only be set by device owner admins; if it is set by
3132     * other admins a {@link SecurityException} will be thrown.
3133     */
3134    public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
3135
3136    /**
3137     * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
3138     * other users will remain unaffected. Calling from the primary user will cause the device to
3139     * reboot, erasing all device data - including all the secondary users and their data - while
3140     * booting up.
3141     * <p>
3142     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
3143     * be able to call this method; if it has not, a security exception will be thrown.
3144     *
3145     * @param flags Bit mask of additional options: currently supported flags are
3146     *            {@link #WIPE_EXTERNAL_STORAGE} and {@link #WIPE_RESET_PROTECTION_DATA}.
3147     * @throws SecurityException if the calling application does not own an active administrator
3148     *             that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
3149     */
3150    public void wipeData(int flags) {
3151        throwIfParentInstance("wipeData");
3152        if (mService != null) {
3153            try {
3154                mService.wipeData(flags);
3155            } catch (RemoteException e) {
3156                throw e.rethrowFromSystemServer();
3157            }
3158        }
3159    }
3160
3161    /**
3162     * Called by an application that is administering the device to set the
3163     * global proxy and exclusion list.
3164     * <p>
3165     * The calling device admin must have requested
3166     * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
3167     * this method; if it has not, a security exception will be thrown.
3168     * Only the first device admin can set the proxy. If a second admin attempts
3169     * to set the proxy, the {@link ComponentName} of the admin originally setting the
3170     * proxy will be returned. If successful in setting the proxy, {@code null} will
3171     * be returned.
3172     * The method can be called repeatedly by the device admin alrady setting the
3173     * proxy to update the proxy and exclusion list.
3174     *
3175     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3176     * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
3177     *            Pass Proxy.NO_PROXY to reset the proxy.
3178     * @param exclusionList a list of domains to be excluded from the global proxy.
3179     * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
3180     *            of the device admin that sets the proxy.
3181     * @hide
3182     */
3183    public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
3184            List<String> exclusionList ) {
3185        throwIfParentInstance("setGlobalProxy");
3186        if (proxySpec == null) {
3187            throw new NullPointerException();
3188        }
3189        if (mService != null) {
3190            try {
3191                String hostSpec;
3192                String exclSpec;
3193                if (proxySpec.equals(Proxy.NO_PROXY)) {
3194                    hostSpec = null;
3195                    exclSpec = null;
3196                } else {
3197                    if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
3198                        throw new IllegalArgumentException();
3199                    }
3200                    InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
3201                    String hostName = sa.getHostName();
3202                    int port = sa.getPort();
3203                    StringBuilder hostBuilder = new StringBuilder();
3204                    hostSpec = hostBuilder.append(hostName)
3205                        .append(":").append(Integer.toString(port)).toString();
3206                    if (exclusionList == null) {
3207                        exclSpec = "";
3208                    } else {
3209                        StringBuilder listBuilder = new StringBuilder();
3210                        boolean firstDomain = true;
3211                        for (String exclDomain : exclusionList) {
3212                            if (!firstDomain) {
3213                                listBuilder = listBuilder.append(",");
3214                            } else {
3215                                firstDomain = false;
3216                            }
3217                            listBuilder = listBuilder.append(exclDomain.trim());
3218                        }
3219                        exclSpec = listBuilder.toString();
3220                    }
3221                    if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
3222                            != android.net.Proxy.PROXY_VALID)
3223                        throw new IllegalArgumentException();
3224                }
3225                return mService.setGlobalProxy(admin, hostSpec, exclSpec);
3226            } catch (RemoteException e) {
3227                throw e.rethrowFromSystemServer();
3228            }
3229        }
3230        return null;
3231    }
3232
3233    /**
3234     * Set a network-independent global HTTP proxy. This is not normally what you want for typical
3235     * HTTP proxies - they are generally network dependent. However if you're doing something
3236     * unusual like general internal filtering this may be useful. On a private network where the
3237     * proxy is not accessible, you may break HTTP using this.
3238     * <p>
3239     * This method requires the caller to be the device owner.
3240     * <p>
3241     * This proxy is only a recommendation and it is possible that some apps will ignore it.
3242     *
3243     * @see ProxyInfo
3244     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3245     * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
3246     *            {@code null} value will clear the global HTTP proxy.
3247     * @throws SecurityException if {@code admin} is not the device owner.
3248     */
3249    public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
3250            proxyInfo) {
3251        throwIfParentInstance("setRecommendedGlobalProxy");
3252        if (mService != null) {
3253            try {
3254                mService.setRecommendedGlobalProxy(admin, proxyInfo);
3255            } catch (RemoteException e) {
3256                throw e.rethrowFromSystemServer();
3257            }
3258        }
3259    }
3260
3261    /**
3262     * Returns the component name setting the global proxy.
3263     * @return ComponentName object of the device admin that set the global proxy, or {@code null}
3264     *         if no admin has set the proxy.
3265     * @hide
3266     */
3267    public @Nullable ComponentName getGlobalProxyAdmin() {
3268        if (mService != null) {
3269            try {
3270                return mService.getGlobalProxyAdmin(myUserId());
3271            } catch (RemoteException e) {
3272                throw e.rethrowFromSystemServer();
3273            }
3274        }
3275        return null;
3276    }
3277
3278    /**
3279     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3280     * indicating that encryption is not supported.
3281     */
3282    public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
3283
3284    /**
3285     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3286     * indicating that encryption is supported, but is not currently active.
3287     */
3288    public static final int ENCRYPTION_STATUS_INACTIVE = 1;
3289
3290    /**
3291     * Result code for {@link #getStorageEncryptionStatus}:
3292     * indicating that encryption is not currently active, but is currently
3293     * being activated.  This is only reported by devices that support
3294     * encryption of data and only when the storage is currently
3295     * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
3296     * to become encrypted will never return this value.
3297     */
3298    public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
3299
3300    /**
3301     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3302     * indicating that encryption is active.
3303     * <p>
3304     * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3305     */
3306    public static final int ENCRYPTION_STATUS_ACTIVE = 3;
3307
3308    /**
3309     * Result code for {@link #getStorageEncryptionStatus}:
3310     * indicating that encryption is active, but an encryption key has not
3311     * been set by the user.
3312     */
3313    public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
3314
3315    /**
3316     * Result code for {@link #getStorageEncryptionStatus}:
3317     * indicating that encryption is active and the encryption key is tied to the user or profile.
3318     * <p>
3319     * This value is only returned to apps targeting API level 24 and above. For apps targeting
3320     * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
3321     * encryption key is specific to the user or profile.
3322     */
3323    public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
3324
3325    /**
3326     * Activity action: begin the process of encrypting data on the device.  This activity should
3327     * be launched after using {@link #setStorageEncryption} to request encryption be activated.
3328     * After resuming from this activity, use {@link #getStorageEncryption}
3329     * to check encryption status.  However, on some devices this activity may never return, as
3330     * it may trigger a reboot and in some cases a complete data wipe of the device.
3331     */
3332    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3333    public static final String ACTION_START_ENCRYPTION
3334            = "android.app.action.START_ENCRYPTION";
3335    /**
3336     * Widgets are enabled in keyguard
3337     */
3338    public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
3339
3340    /**
3341     * Disable all keyguard widgets. Has no effect.
3342     */
3343    public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
3344
3345    /**
3346     * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
3347     */
3348    public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
3349
3350    /**
3351     * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3352     */
3353    public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
3354
3355    /**
3356     * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3357     */
3358    public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
3359
3360    /**
3361     * Ignore trust agent state on secure keyguard screens
3362     * (e.g. PIN/Pattern/Password).
3363     */
3364    public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
3365
3366    /**
3367     * Disable fingerprint sensor on keyguard secure screens (e.g. PIN/Pattern/Password).
3368     */
3369    public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
3370
3371    /**
3372     * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
3373     */
3374    public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
3375
3376    /**
3377     * Disable all current and future keyguard customizations.
3378     */
3379    public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
3380
3381    /**
3382     * Keyguard features that when set on a managed profile that doesn't have its own challenge will
3383     * affect the profile's parent user. These can also be set on the managed profile's parent
3384     * {@link DevicePolicyManager} instance.
3385     *
3386     * @hide
3387     */
3388    public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
3389            DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
3390            | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
3391
3392    /**
3393     * Called by an application that is administering the device to request that the storage system
3394     * be encrypted.
3395     * <p>
3396     * When multiple device administrators attempt to control device encryption, the most secure,
3397     * supported setting will always be used. If any device administrator requests device
3398     * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
3399     * device encryption while another device administrator has enabled it, the call to disable will
3400     * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
3401     * <p>
3402     * This policy controls encryption of the secure (application data) storage area. Data written
3403     * to other storage areas may or may not be encrypted, and this policy does not require or
3404     * control the encryption of any other storage areas. There is one exception: If
3405     * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
3406     * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
3407     * written to disk within the encrypted storage area.
3408     * <p>
3409     * Important Note: On some devices, it is possible to encrypt storage without requiring the user
3410     * to create a device PIN or Password. In this case, the storage is encrypted, but the
3411     * encryption key may not be fully secured. For maximum security, the administrator should also
3412     * require (and check for) a pattern, PIN, or password.
3413     *
3414     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3415     * @param encrypt true to request encryption, false to release any previous request
3416     * @return the new request status (for all active admins) - will be one of
3417     *         {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, or
3418     *         {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value of the requests; Use
3419     *         {@link #getStorageEncryptionStatus()} to query the actual device state.
3420     * @throws SecurityException if {@code admin} is not an active administrator or does not use
3421     *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
3422     */
3423    public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
3424        throwIfParentInstance("setStorageEncryption");
3425        if (mService != null) {
3426            try {
3427                return mService.setStorageEncryption(admin, encrypt);
3428            } catch (RemoteException e) {
3429                throw e.rethrowFromSystemServer();
3430            }
3431        }
3432        return ENCRYPTION_STATUS_UNSUPPORTED;
3433    }
3434
3435    /**
3436     * Called by an application that is administering the device to
3437     * determine the requested setting for secure storage.
3438     *
3439     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
3440     * this will return the requested encryption setting as an aggregate of all active
3441     * administrators.
3442     * @return true if the admin(s) are requesting encryption, false if not.
3443     */
3444    public boolean getStorageEncryption(@Nullable ComponentName admin) {
3445        throwIfParentInstance("getStorageEncryption");
3446        if (mService != null) {
3447            try {
3448                return mService.getStorageEncryption(admin, myUserId());
3449            } catch (RemoteException e) {
3450                throw e.rethrowFromSystemServer();
3451            }
3452        }
3453        return false;
3454    }
3455
3456    /**
3457     * Called by an application that is administering the device to
3458     * determine the current encryption status of the device.
3459     * <p>
3460     * Depending on the returned status code, the caller may proceed in different
3461     * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
3462     * storage system does not support encryption.  If the
3463     * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
3464     * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
3465     * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
3466     * storage system has enabled encryption but no password is set so further action
3467     * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
3468     * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
3469     * no further action is required.
3470     *
3471     * @return current status of encryption. The value will be one of
3472     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
3473     * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
3474     * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3475     */
3476    public int getStorageEncryptionStatus() {
3477        throwIfParentInstance("getStorageEncryptionStatus");
3478        return getStorageEncryptionStatus(myUserId());
3479    }
3480
3481    /** @hide per-user version */
3482    public int getStorageEncryptionStatus(int userHandle) {
3483        if (mService != null) {
3484            try {
3485                return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
3486            } catch (RemoteException e) {
3487                throw e.rethrowFromSystemServer();
3488            }
3489        }
3490        return ENCRYPTION_STATUS_UNSUPPORTED;
3491    }
3492
3493    /**
3494     * Mark a CA certificate as approved by the device user. This means that they have been notified
3495     * of the installation, were made aware of the risks, viewed the certificate and still wanted to
3496     * keep the certificate on the device.
3497     *
3498     * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
3499     * this certificate.
3500     *
3501     * @hide
3502     */
3503    public boolean approveCaCert(String alias, int userHandle, boolean approval) {
3504        if (mService != null) {
3505            try {
3506                return mService.approveCaCert(alias, userHandle, approval);
3507            } catch (RemoteException e) {
3508                throw e.rethrowFromSystemServer();
3509            }
3510        }
3511        return false;
3512    }
3513
3514    /**
3515     * Check whether a CA certificate has been approved by the device user.
3516     *
3517     * @hide
3518     */
3519    public boolean isCaCertApproved(String alias, int userHandle) {
3520        if (mService != null) {
3521            try {
3522                return mService.isCaCertApproved(alias, userHandle);
3523            } catch (RemoteException e) {
3524                throw e.rethrowFromSystemServer();
3525            }
3526        }
3527        return false;
3528    }
3529
3530    /**
3531     * Installs the given certificate as a user CA.
3532     *
3533     * The caller must be a profile or device owner on that user, or a delegate package given the
3534     * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3535     * security exception will be thrown.
3536     *
3537     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3538     *              {@code null} if calling from a delegated certificate installer.
3539     * @param certBuffer encoded form of the certificate to install.
3540     *
3541     * @return false if the certBuffer cannot be parsed or installation is
3542     *         interrupted, true otherwise.
3543     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3544     *         owner.
3545     * @see #setDelegatedScopes
3546     * @see #DELEGATION_CERT_INSTALL
3547     */
3548    public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3549        throwIfParentInstance("installCaCert");
3550        if (mService != null) {
3551            try {
3552                return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
3553            } catch (RemoteException e) {
3554                throw e.rethrowFromSystemServer();
3555            }
3556        }
3557        return false;
3558    }
3559
3560    /**
3561     * Uninstalls the given certificate from trusted user CAs, if present.
3562     *
3563     * The caller must be a profile or device owner on that user, or a delegate package given the
3564     * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3565     * security exception will be thrown.
3566     *
3567     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3568     *              {@code null} if calling from a delegated certificate installer.
3569     * @param certBuffer encoded form of the certificate to remove.
3570     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3571     *         owner.
3572     * @see #setDelegatedScopes
3573     * @see #DELEGATION_CERT_INSTALL
3574     */
3575    public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3576        throwIfParentInstance("uninstallCaCert");
3577        if (mService != null) {
3578            try {
3579                final String alias = getCaCertAlias(certBuffer);
3580                mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
3581            } catch (CertificateException e) {
3582                Log.w(TAG, "Unable to parse certificate", e);
3583            } catch (RemoteException e) {
3584                throw e.rethrowFromSystemServer();
3585            }
3586        }
3587    }
3588
3589    /**
3590     * Returns all CA certificates that are currently trusted, excluding system CA certificates.
3591     * If a user has installed any certificates by other means than device policy these will be
3592     * included too.
3593     *
3594     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3595     *              {@code null} if calling from a delegated certificate installer.
3596     * @return a List of byte[] arrays, each encoding one user CA certificate.
3597     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3598     *         owner.
3599     */
3600    public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
3601        final List<byte[]> certs = new ArrayList<byte[]>();
3602        throwIfParentInstance("getInstalledCaCerts");
3603        if (mService != null) {
3604            try {
3605                mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
3606                final TrustedCertificateStore certStore = new TrustedCertificateStore();
3607                for (String alias : certStore.userAliases()) {
3608                    try {
3609                        certs.add(certStore.getCertificate(alias).getEncoded());
3610                    } catch (CertificateException ce) {
3611                        Log.w(TAG, "Could not encode certificate: " + alias, ce);
3612                    }
3613                }
3614            } catch (RemoteException re) {
3615                throw re.rethrowFromSystemServer();
3616            }
3617        }
3618        return certs;
3619    }
3620
3621    /**
3622     * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
3623     * means other than device policy will also be removed, except for system CA certificates.
3624     *
3625     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3626     *              {@code null} if calling from a delegated certificate installer.
3627     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3628     *         owner.
3629     */
3630    public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
3631        throwIfParentInstance("uninstallAllUserCaCerts");
3632        if (mService != null) {
3633            try {
3634                mService.uninstallCaCerts(admin, mContext.getPackageName(),
3635                        new TrustedCertificateStore().userAliases() .toArray(new String[0]));
3636            } catch (RemoteException re) {
3637                throw re.rethrowFromSystemServer();
3638            }
3639        }
3640    }
3641
3642    /**
3643     * Returns whether this certificate is installed as a trusted CA.
3644     *
3645     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3646     *              {@code null} if calling from a delegated certificate installer.
3647     * @param certBuffer encoded form of the certificate to look up.
3648     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3649     *         owner.
3650     */
3651    public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
3652        throwIfParentInstance("hasCaCertInstalled");
3653        if (mService != null) {
3654            try {
3655                mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
3656                return getCaCertAlias(certBuffer) != null;
3657            } catch (RemoteException re) {
3658                throw re.rethrowFromSystemServer();
3659            } catch (CertificateException ce) {
3660                Log.w(TAG, "Could not parse certificate", ce);
3661            }
3662        }
3663        return false;
3664    }
3665
3666    /**
3667     * Called by a device or profile owner, or delegated certificate installer, to install a
3668     * certificate and corresponding private key. All apps within the profile will be able to access
3669     * the certificate and use the private key, given direct user approval.
3670     *
3671     * <p>Access to the installed credentials will not be granted to the caller of this API without
3672     * direct user approval. This is for security - should a certificate installer become
3673     * compromised, certificates it had already installed will be protected.
3674     *
3675     * <p>If the installer must have access to the credentials, call
3676     * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
3677     *
3678     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3679     *            {@code null} if calling from a delegated certificate installer.
3680     * @param privKey The private key to install.
3681     * @param cert The certificate to install.
3682     * @param alias The private key alias under which to install the certificate. If a certificate
3683     * with that alias already exists, it will be overwritten.
3684     * @return {@code true} if the keys were installed, {@code false} otherwise.
3685     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3686     *         owner.
3687     * @see #setDelegatedScopes
3688     * @see #DELEGATION_CERT_INSTALL
3689     */
3690    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
3691            @NonNull Certificate cert, @NonNull String alias) {
3692        return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
3693    }
3694
3695    /**
3696     * Called by a device or profile owner, or delegated certificate installer, to install a
3697     * certificate chain and corresponding private key for the leaf certificate. All apps within the
3698     * profile will be able to access the certificate chain and use the private key, given direct
3699     * user approval.
3700     *
3701     * <p>The caller of this API may grant itself access to the certificate and private key
3702     * immediately, without user approval. It is a best practice not to request this unless strictly
3703     * necessary since it opens up additional security vulnerabilities.
3704     *
3705     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3706     *        {@code null} if calling from a delegated certificate installer.
3707     * @param privKey The private key to install.
3708     * @param certs The certificate chain to install. The chain should start with the leaf
3709     *        certificate and include the chain of trust in order. This will be returned by
3710     *        {@link android.security.KeyChain#getCertificateChain}.
3711     * @param alias The private key alias under which to install the certificate. If a certificate
3712     *        with that alias already exists, it will be overwritten.
3713     * @param requestAccess {@code true} to request that the calling app be granted access to the
3714     *        credentials immediately. Otherwise, access to the credentials will be gated by user
3715     *        approval.
3716     * @return {@code true} if the keys were installed, {@code false} otherwise.
3717     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3718     *         owner.
3719     * @see android.security.KeyChain#getCertificateChain
3720     * @see #setDelegatedScopes
3721     * @see #DELEGATION_CERT_INSTALL
3722     */
3723    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
3724            @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
3725        throwIfParentInstance("installKeyPair");
3726        try {
3727            final byte[] pemCert = Credentials.convertToPem(certs[0]);
3728            byte[] pemChain = null;
3729            if (certs.length > 1) {
3730                pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
3731            }
3732            final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
3733                    .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
3734            return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
3735                    pemChain, alias, requestAccess);
3736        } catch (RemoteException e) {
3737            throw e.rethrowFromSystemServer();
3738        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
3739            Log.w(TAG, "Failed to obtain private key material", e);
3740        } catch (CertificateException | IOException e) {
3741            Log.w(TAG, "Could not pem-encode certificate", e);
3742        }
3743        return false;
3744    }
3745
3746    /**
3747     * Called by a device or profile owner, or delegated certificate installer, to remove a
3748     * certificate and private key pair installed under a given alias.
3749     *
3750     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3751     *        {@code null} if calling from a delegated certificate installer.
3752     * @param alias The private key alias under which the certificate is installed.
3753     * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
3754     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3755     *         owner.
3756     * @see #setDelegatedScopes
3757     * @see #DELEGATION_CERT_INSTALL
3758     */
3759    public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
3760        throwIfParentInstance("removeKeyPair");
3761        try {
3762            return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
3763        } catch (RemoteException e) {
3764            throw e.rethrowFromSystemServer();
3765        }
3766    }
3767
3768    /**
3769     * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
3770     * doesn't exist.
3771     */
3772    private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
3773        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
3774        final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
3775                              new ByteArrayInputStream(certBuffer));
3776        return new TrustedCertificateStore().getCertificateAlias(cert);
3777    }
3778
3779    /**
3780     * Called by a profile owner or device owner to grant access to privileged certificate
3781     * manipulation APIs to a third-party certificate installer app. Granted APIs include
3782     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
3783     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
3784     * <p>
3785     * Delegated certificate installer is a per-user state. The delegated access is persistent until
3786     * it is later cleared by calling this method with a null value or uninstallling the certificate
3787     * installer.
3788     * <p>
3789     * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
3790     * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
3791     * supplied certificate installer package must be installed when calling this API, otherwise an
3792     * {@link IllegalArgumentException} will be thrown.
3793     *
3794     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3795     * @param installerPackage The package name of the certificate installer which will be given
3796     *            access. If {@code null} is given the current package will be cleared.
3797     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3798     *
3799     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
3800     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
3801     */
3802    @Deprecated
3803    public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
3804            installerPackage) throws SecurityException {
3805        throwIfParentInstance("setCertInstallerPackage");
3806        if (mService != null) {
3807            try {
3808                mService.setCertInstallerPackage(admin, installerPackage);
3809            } catch (RemoteException e) {
3810                throw e.rethrowFromSystemServer();
3811            }
3812        }
3813    }
3814
3815    /**
3816     * Called by a profile owner or device owner to retrieve the certificate installer for the user,
3817     * or {@code null} if none is set. If there are multiple delegates this function will return one
3818     * of them.
3819     *
3820     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3821     * @return The package name of the current delegated certificate installer, or {@code null} if
3822     *         none is set.
3823     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3824     *
3825     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
3826     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
3827     */
3828    @Deprecated
3829    public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
3830            throws SecurityException {
3831        throwIfParentInstance("getCertInstallerPackage");
3832        if (mService != null) {
3833            try {
3834                return mService.getCertInstallerPackage(admin);
3835            } catch (RemoteException e) {
3836                throw e.rethrowFromSystemServer();
3837            }
3838        }
3839        return null;
3840    }
3841
3842    /**
3843     * Called by a profile owner or device owner to grant access to privileged APIs to another app.
3844     * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
3845     * constants.
3846     * <p>
3847     * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
3848     * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
3849     * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
3850     * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
3851     * <p>
3852     * Delegated scopes are a per-user state. The delegated access is persistent until it is later
3853     * cleared by calling this method with an empty {@code scopes} list or uninstalling the
3854     * {@code delegatePackage}.
3855     *
3856     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3857     * @param delegatePackage The package name of the app which will be given access.
3858     * @param scopes The groups of privileged APIs whose access should be granted to
3859     *            {@code delegatedPackage}.
3860     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3861     */
3862     public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
3863            @NonNull List<String> scopes) {
3864        throwIfParentInstance("setDelegatedScopes");
3865        if (mService != null) {
3866            try {
3867                mService.setDelegatedScopes(admin, delegatePackage, scopes);
3868            } catch (RemoteException e) {
3869                throw e.rethrowFromSystemServer();
3870            }
3871        }
3872    }
3873
3874    /**
3875     * Called by a profile owner or device owner to retrieve a list of the scopes given to a
3876     * delegate package. Other apps can use this method to retrieve their own delegated scopes by
3877     * passing {@code null} for {@code admin} and their own package name as
3878     * {@code delegatedPackage}.
3879     *
3880     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3881     *            {@code null} if the caller is {@code delegatedPackage}.
3882     * @param delegatedPackage The package name of the app whose scopes should be retrieved.
3883     * @return A list containing the scopes given to {@code delegatedPackage}.
3884     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3885     */
3886     @NonNull
3887     public List<String> getDelegatedScopes(@Nullable ComponentName admin,
3888             @NonNull String delegatedPackage) {
3889         throwIfParentInstance("getDelegatedScopes");
3890         if (mService != null) {
3891             try {
3892                 return mService.getDelegatedScopes(admin, delegatedPackage);
3893             } catch (RemoteException e) {
3894                 throw e.rethrowFromSystemServer();
3895             }
3896         }
3897         return null;
3898    }
3899
3900    /**
3901     * Called by a profile owner or device owner to retrieve a list of delegate packages that were
3902     * granted a delegation scope.
3903     *
3904     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3905     * @param delegationScope The scope whose delegates should be retrieved.
3906     * @return A list of package names of the current delegated packages for
3907               {@code delegationScope}.
3908     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3909     */
3910     @Nullable
3911     public List<String> getDelegatePackages(@NonNull ComponentName admin,
3912             @NonNull String delegationScope) {
3913        throwIfParentInstance("getDelegatePackages");
3914        if (mService != null) {
3915            try {
3916                return mService.getDelegatePackages(admin, delegationScope);
3917            } catch (RemoteException e) {
3918                throw e.rethrowFromSystemServer();
3919            }
3920        }
3921        return null;
3922    }
3923
3924    /**
3925     * Called by a device or profile owner to configure an always-on VPN connection through a
3926     * specific application for the current user.
3927     *
3928     * @deprecated this version only exists for compability with previous developer preview builds.
3929     *             TODO: delete once there are no longer any live references.
3930     * @hide
3931     */
3932    @Deprecated
3933    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage)
3934            throws NameNotFoundException, UnsupportedOperationException {
3935        setAlwaysOnVpnPackage(admin, vpnPackage, /* lockdownEnabled */ true);
3936    }
3937
3938    /**
3939     * Called by a device or profile owner to configure an always-on VPN connection through a
3940     * specific application for the current user. This connection is automatically granted and
3941     * persisted after a reboot.
3942     * <p>
3943     * The designated package should declare a {@link android.net.VpnService} in its manifest
3944     * guarded by {@link android.Manifest.permission#BIND_VPN_SERVICE}, otherwise the call will
3945     * fail.
3946     *
3947     * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
3948     *        remove an existing always-on VPN configuration.
3949     * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
3950     *        {@code false} otherwise. This carries the risk that any failure of the VPN provider
3951     *        could break networking for all apps. This has no effect when clearing.
3952     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3953     * @throws NameNotFoundException if {@code vpnPackage} is not installed.
3954     * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
3955     *         set as always-on, or if always-on VPN is not available.
3956     */
3957    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
3958            boolean lockdownEnabled)
3959            throws NameNotFoundException, UnsupportedOperationException {
3960        throwIfParentInstance("setAlwaysOnVpnPackage");
3961        if (mService != null) {
3962            try {
3963                if (!mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled)) {
3964                    throw new NameNotFoundException(vpnPackage);
3965                }
3966            } catch (RemoteException e) {
3967                throw e.rethrowFromSystemServer();
3968            }
3969        }
3970    }
3971
3972    /**
3973     * Called by a device or profile owner to read the name of the package administering an
3974     * always-on VPN connection for the current user. If there is no such package, or the always-on
3975     * VPN is provided by the system instead of by an application, {@code null} will be returned.
3976     *
3977     * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
3978     *         is set.
3979     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3980     */
3981    public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
3982        throwIfParentInstance("getAlwaysOnVpnPackage");
3983        if (mService != null) {
3984            try {
3985                return mService.getAlwaysOnVpnPackage(admin);
3986            } catch (RemoteException e) {
3987                throw e.rethrowFromSystemServer();
3988            }
3989        }
3990        return null;
3991    }
3992
3993    /**
3994     * Called by an application that is administering the device to disable all cameras on the
3995     * device, for this user. After setting this, no applications running as this user will be able
3996     * to access any cameras on the device.
3997     * <p>
3998     * If the caller is device owner, then the restriction will be applied to all users.
3999     * <p>
4000     * The calling device admin must have requested
4001     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
4002     * not, a security exception will be thrown.
4003     *
4004     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4005     * @param disabled Whether or not the camera should be disabled.
4006     * @throws SecurityException if {@code admin} is not an active administrator or does not use
4007     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
4008     */
4009    public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
4010        throwIfParentInstance("setCameraDisabled");
4011        if (mService != null) {
4012            try {
4013                mService.setCameraDisabled(admin, disabled);
4014            } catch (RemoteException e) {
4015                throw e.rethrowFromSystemServer();
4016            }
4017        }
4018    }
4019
4020    /**
4021     * Determine whether or not the device's cameras have been disabled for this user,
4022     * either by the calling admin, if specified, or all admins.
4023     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4024     * have disabled the camera
4025     */
4026    public boolean getCameraDisabled(@Nullable ComponentName admin) {
4027        throwIfParentInstance("getCameraDisabled");
4028        return getCameraDisabled(admin, myUserId());
4029    }
4030
4031    /** @hide per-user version */
4032    public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
4033        if (mService != null) {
4034            try {
4035                return mService.getCameraDisabled(admin, userHandle);
4036            } catch (RemoteException e) {
4037                throw e.rethrowFromSystemServer();
4038            }
4039        }
4040        return false;
4041    }
4042
4043    /**
4044     * Called by a device owner to request a bugreport.
4045     * <p>
4046     * If the device contains secondary users or profiles, they must be affiliated with the device
4047     * owner user. Otherwise a {@link SecurityException} will be thrown. See
4048     * {@link #setAffiliationIds}.
4049     *
4050     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4051     * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
4052     *         wasn't triggered because a previous bugreport operation is still active (either the
4053     *         bugreport is still running or waiting for the user to share or decline)
4054     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
4055     *         profile or secondary user that is not affiliated with the device owner user.
4056     */
4057    public boolean requestBugreport(@NonNull ComponentName admin) {
4058        throwIfParentInstance("requestBugreport");
4059        if (mService != null) {
4060            try {
4061                return mService.requestBugreport(admin);
4062            } catch (RemoteException e) {
4063                throw e.rethrowFromSystemServer();
4064            }
4065        }
4066        return false;
4067    }
4068
4069    /**
4070     * Determine whether or not creating a guest user has been disabled for the device
4071     *
4072     * @hide
4073     */
4074    public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
4075        // Currently guest users can always be created if multi-user is enabled
4076        // TODO introduce a policy for guest user creation
4077        return false;
4078    }
4079
4080    /**
4081     * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
4082     * screen capture also prevents the content from being shown on display devices that do not have
4083     * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
4084     * secure surfaces and secure displays.
4085     * <p>
4086     * The calling device admin must be a device or profile owner. If it is not, a security
4087     * exception will be thrown.
4088     * <p>
4089     * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
4090     * assist requests for all activities of the relevant user.
4091     *
4092     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4093     * @param disabled Whether screen capture is disabled or not.
4094     * @throws SecurityException if {@code admin} is not a device or profile owner.
4095     */
4096    public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
4097        throwIfParentInstance("setScreenCaptureDisabled");
4098        if (mService != null) {
4099            try {
4100                mService.setScreenCaptureDisabled(admin, disabled);
4101            } catch (RemoteException e) {
4102                throw e.rethrowFromSystemServer();
4103            }
4104        }
4105    }
4106
4107    /**
4108     * Determine whether or not screen capture has been disabled by the calling
4109     * admin, if specified, or all admins.
4110     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4111     * have disabled screen capture.
4112     */
4113    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
4114        throwIfParentInstance("getScreenCaptureDisabled");
4115        return getScreenCaptureDisabled(admin, myUserId());
4116    }
4117
4118    /** @hide per-user version */
4119    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
4120        if (mService != null) {
4121            try {
4122                return mService.getScreenCaptureDisabled(admin, userHandle);
4123            } catch (RemoteException e) {
4124                throw e.rethrowFromSystemServer();
4125            }
4126        }
4127        return false;
4128    }
4129
4130    /**
4131     * Called by a device or profile owner to set whether auto time is required. If auto time is
4132     * required, no user will be able set the date and time and network date and time will be used.
4133     * <p>
4134     * Note: if auto time is required the user can still manually set the time zone.
4135     * <p>
4136     * The calling device admin must be a device or profile owner. If it is not, a security
4137     * exception will be thrown.
4138     *
4139     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4140     * @param required Whether auto time is set required or not.
4141     * @throws SecurityException if {@code admin} is not a device owner.
4142     */
4143    public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
4144        throwIfParentInstance("setAutoTimeRequired");
4145        if (mService != null) {
4146            try {
4147                mService.setAutoTimeRequired(admin, required);
4148            } catch (RemoteException e) {
4149                throw e.rethrowFromSystemServer();
4150            }
4151        }
4152    }
4153
4154    /**
4155     * @return true if auto time is required.
4156     */
4157    public boolean getAutoTimeRequired() {
4158        throwIfParentInstance("getAutoTimeRequired");
4159        if (mService != null) {
4160            try {
4161                return mService.getAutoTimeRequired();
4162            } catch (RemoteException e) {
4163                throw e.rethrowFromSystemServer();
4164            }
4165        }
4166        return false;
4167    }
4168
4169    /**
4170     * Called by a device owner to set whether all users created on the device should be ephemeral.
4171     * <p>
4172     * The system user is exempt from this policy - it is never ephemeral.
4173     * <p>
4174     * The calling device admin must be the device owner. If it is not, a security exception will be
4175     * thrown.
4176     *
4177     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4178     * @param forceEphemeralUsers If true, all the existing users will be deleted and all
4179     *            subsequently created users will be ephemeral.
4180     * @throws SecurityException if {@code admin} is not a device owner.
4181     * @hide
4182     */
4183    public void setForceEphemeralUsers(
4184            @NonNull ComponentName admin, boolean forceEphemeralUsers) {
4185        throwIfParentInstance("setForceEphemeralUsers");
4186        if (mService != null) {
4187            try {
4188                mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
4189            } catch (RemoteException e) {
4190                throw e.rethrowFromSystemServer();
4191            }
4192        }
4193    }
4194
4195    /**
4196     * @return true if all users are created ephemeral.
4197     * @throws SecurityException if {@code admin} is not a device owner.
4198     * @hide
4199     */
4200    public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
4201        throwIfParentInstance("getForceEphemeralUsers");
4202        if (mService != null) {
4203            try {
4204                return mService.getForceEphemeralUsers(admin);
4205            } catch (RemoteException e) {
4206                throw e.rethrowFromSystemServer();
4207            }
4208        }
4209        return false;
4210    }
4211
4212    /**
4213     * Called by an application that is administering the device to disable keyguard customizations,
4214     * such as widgets. After setting this, keyguard features will be disabled according to the
4215     * provided feature list.
4216     * <p>
4217     * The calling device admin must have requested
4218     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
4219     * if it has not, a security exception will be thrown.
4220     * <p>
4221     * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
4222     * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
4223     * profile owner of a managed profile can set:
4224     * <ul>
4225     * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
4226     * is no separate challenge set on the managed profile.
4227     * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT} which affects the managed profile challenge if
4228     * there is one, or the parent user otherwise.
4229     * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
4230     * by applications in the managed profile.
4231     * </ul>
4232     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and {@link #KEYGUARD_DISABLE_FINGERPRINT} can also be
4233     * set on the {@link DevicePolicyManager} instance returned by
4234     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4235     * profile.
4236     * <p>
4237     * Requests to disable other features on a managed profile will be ignored.
4238     * <p>
4239     * The admin can check which features have been disabled by calling
4240     * {@link #getKeyguardDisabledFeatures(ComponentName)}
4241     *
4242     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4243     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
4244     *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
4245     *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
4246     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
4247     *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
4248     *            {@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
4249     * @throws SecurityException if {@code admin} is not an active administrator or does not user
4250     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
4251     */
4252    public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
4253        if (mService != null) {
4254            try {
4255                mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
4256            } catch (RemoteException e) {
4257                throw e.rethrowFromSystemServer();
4258            }
4259        }
4260    }
4261
4262    /**
4263     * Determine whether or not features have been disabled in keyguard either by the calling
4264     * admin, if specified, or all admins that set restrictions on this user and its participating
4265     * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
4266     *
4267     * <p>This method can be called on the {@link DevicePolicyManager} instance
4268     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4269     * restrictions on the parent profile.
4270     *
4271     * @param admin The name of the admin component to check, or {@code null} to check whether any
4272     * admins have disabled features in keyguard.
4273     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
4274     * for a list.
4275     */
4276    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
4277        return getKeyguardDisabledFeatures(admin, myUserId());
4278    }
4279
4280    /** @hide per-user version */
4281    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
4282        if (mService != null) {
4283            try {
4284                return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
4285            } catch (RemoteException e) {
4286                throw e.rethrowFromSystemServer();
4287            }
4288        }
4289        return KEYGUARD_DISABLE_FEATURES_NONE;
4290    }
4291
4292    /**
4293     * @hide
4294     */
4295    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
4296            int userHandle) {
4297        if (mService != null) {
4298            try {
4299                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
4300            } catch (RemoteException e) {
4301                throw e.rethrowFromSystemServer();
4302            }
4303        }
4304    }
4305
4306    /**
4307     * @hide
4308     */
4309    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
4310        setActiveAdmin(policyReceiver, refreshing, myUserId());
4311    }
4312
4313    /**
4314     * @hide
4315     */
4316    public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
4317        if (mService != null) {
4318            try {
4319                mService.getRemoveWarning(admin, result, myUserId());
4320            } catch (RemoteException e) {
4321                throw e.rethrowFromSystemServer();
4322            }
4323        }
4324    }
4325
4326    /**
4327     * @hide
4328     */
4329    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
4330        if (mService != null) {
4331            try {
4332                mService.setActivePasswordState(metrics, userHandle);
4333            } catch (RemoteException e) {
4334                throw e.rethrowFromSystemServer();
4335            }
4336        }
4337    }
4338
4339    /**
4340     * @hide
4341     */
4342    public void reportPasswordChanged(@UserIdInt int userId) {
4343        if (mService != null) {
4344            try {
4345                mService.reportPasswordChanged(userId);
4346            } catch (RemoteException e) {
4347                throw e.rethrowFromSystemServer();
4348            }
4349        }
4350    }
4351
4352    /**
4353     * @hide
4354     */
4355    public void reportFailedPasswordAttempt(int userHandle) {
4356        if (mService != null) {
4357            try {
4358                mService.reportFailedPasswordAttempt(userHandle);
4359            } catch (RemoteException e) {
4360                throw e.rethrowFromSystemServer();
4361            }
4362        }
4363    }
4364
4365    /**
4366     * @hide
4367     */
4368    public void reportSuccessfulPasswordAttempt(int userHandle) {
4369        if (mService != null) {
4370            try {
4371                mService.reportSuccessfulPasswordAttempt(userHandle);
4372            } catch (RemoteException e) {
4373                throw e.rethrowFromSystemServer();
4374            }
4375        }
4376    }
4377
4378    /**
4379     * @hide
4380     */
4381    public void reportFailedFingerprintAttempt(int userHandle) {
4382        if (mService != null) {
4383            try {
4384                mService.reportFailedFingerprintAttempt(userHandle);
4385            } catch (RemoteException e) {
4386                throw e.rethrowFromSystemServer();
4387            }
4388        }
4389    }
4390
4391    /**
4392     * @hide
4393     */
4394    public void reportSuccessfulFingerprintAttempt(int userHandle) {
4395        if (mService != null) {
4396            try {
4397                mService.reportSuccessfulFingerprintAttempt(userHandle);
4398            } catch (RemoteException e) {
4399                throw e.rethrowFromSystemServer();
4400            }
4401        }
4402    }
4403
4404    /**
4405     * Should be called when keyguard has been dismissed.
4406     * @hide
4407     */
4408    public void reportKeyguardDismissed(int userHandle) {
4409        if (mService != null) {
4410            try {
4411                mService.reportKeyguardDismissed(userHandle);
4412            } catch (RemoteException e) {
4413                throw e.rethrowFromSystemServer();
4414            }
4415        }
4416    }
4417
4418    /**
4419     * Should be called when keyguard view has been shown to the user.
4420     * @hide
4421     */
4422    public void reportKeyguardSecured(int userHandle) {
4423        if (mService != null) {
4424            try {
4425                mService.reportKeyguardSecured(userHandle);
4426            } catch (RemoteException e) {
4427                throw e.rethrowFromSystemServer();
4428            }
4429        }
4430    }
4431
4432    /**
4433     * @hide
4434     * Sets the given package as the device owner.
4435     * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
4436     * @param who the component name to be registered as device owner.
4437     * @return whether the package was successfully registered as the device owner.
4438     * @throws IllegalArgumentException if the package name is null or invalid
4439     * @throws IllegalStateException If the preconditions mentioned are not met.
4440     */
4441    public boolean setDeviceOwner(ComponentName who) {
4442        return setDeviceOwner(who, null);
4443    }
4444
4445    /**
4446     * @hide
4447     */
4448    public boolean setDeviceOwner(ComponentName who, int userId)  {
4449        return setDeviceOwner(who, null, userId);
4450    }
4451
4452    /**
4453     * @hide
4454     */
4455    public boolean setDeviceOwner(ComponentName who, String ownerName) {
4456        return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
4457    }
4458
4459    /**
4460     * @hide
4461     * Sets the given package as the device owner. The package must already be installed. There
4462     * must not already be a device owner.
4463     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
4464     * this method.
4465     * Calling this after the setup phase of the primary user has completed is allowed only if
4466     * the caller is the shell uid, and there are no additional users and no accounts.
4467     * @param who the component name to be registered as device owner.
4468     * @param ownerName the human readable name of the institution that owns this device.
4469     * @param userId ID of the user on which the device owner runs.
4470     * @return whether the package was successfully registered as the device owner.
4471     * @throws IllegalArgumentException if the package name is null or invalid
4472     * @throws IllegalStateException If the preconditions mentioned are not met.
4473     */
4474    public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
4475            throws IllegalArgumentException, IllegalStateException {
4476        if (mService != null) {
4477            try {
4478                return mService.setDeviceOwner(who, ownerName, userId);
4479            } catch (RemoteException re) {
4480                throw re.rethrowFromSystemServer();
4481            }
4482        }
4483        return false;
4484    }
4485
4486    /**
4487     * Used to determine if a particular package has been registered as a Device Owner app.
4488     * A device owner app is a special device admin that cannot be deactivated by the user, once
4489     * activated as a device admin. It also cannot be uninstalled. To check whether a particular
4490     * package is currently registered as the device owner app, pass in the package name from
4491     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
4492     * admin apps that want to check whether they are also registered as the device owner app. The
4493     * exact mechanism by which a device admin app is registered as a device owner app is defined by
4494     * the setup process.
4495     * @param packageName the package name of the app, to compare with the registered device owner
4496     * app, if any.
4497     * @return whether or not the package is registered as the device owner app.
4498     */
4499    public boolean isDeviceOwnerApp(String packageName) {
4500        throwIfParentInstance("isDeviceOwnerApp");
4501        return isDeviceOwnerAppOnCallingUser(packageName);
4502    }
4503
4504    /**
4505     * @return true if a package is registered as device owner, only when it's running on the
4506     * calling user.
4507     *
4508     * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
4509     * @hide
4510     */
4511    public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
4512        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
4513    }
4514
4515    /**
4516     * @return true if a package is registered as device owner, even if it's running on a different
4517     * user.
4518     *
4519     * <p>Requires the MANAGE_USERS permission.
4520     *
4521     * @hide
4522     */
4523    public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
4524        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
4525    }
4526
4527    /**
4528     * @return device owner component name, only when it's running on the calling user.
4529     *
4530     * @hide
4531     */
4532    public ComponentName getDeviceOwnerComponentOnCallingUser() {
4533        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
4534    }
4535
4536    /**
4537     * @return device owner component name, even if it's running on a different user.
4538     *
4539     * <p>Requires the MANAGE_USERS permission.
4540     *
4541     * @hide
4542     */
4543    @SystemApi
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    public @Nullable String getDeviceOwner() {
4628        throwIfParentInstance("getDeviceOwner");
4629        final ComponentName name = getDeviceOwnerComponentOnCallingUser();
4630        return name != null ? name.getPackageName() : null;
4631    }
4632
4633    /**
4634     * Called by the system to find out whether the device is managed by a Device Owner.
4635     *
4636     * @return whether the device is managed by a Device Owner.
4637     * @throws SecurityException if the caller is not the device owner, does not hold the
4638     *         MANAGE_USERS permission and is not the system.
4639     *
4640     * @hide
4641     */
4642    @SystemApi
4643    @TestApi
4644    public boolean isDeviceManaged() {
4645        try {
4646            return mService.hasDeviceOwner();
4647        } catch (RemoteException re) {
4648            throw re.rethrowFromSystemServer();
4649        }
4650    }
4651
4652    /**
4653     * Returns the device owner name.  Note this method *will* return the device owner
4654     * name when it's running on a different user.
4655     *
4656     * <p>Requires the MANAGE_USERS permission.
4657     *
4658     * @hide
4659     */
4660    @SystemApi
4661    public String getDeviceOwnerNameOnAnyUser() {
4662        throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
4663        if (mService != null) {
4664            try {
4665                return mService.getDeviceOwnerName();
4666            } catch (RemoteException re) {
4667                throw re.rethrowFromSystemServer();
4668            }
4669        }
4670        return null;
4671    }
4672
4673    /**
4674     * @hide
4675     * @deprecated Do not use
4676     * @removed
4677     */
4678    @Deprecated
4679    @SystemApi
4680    @SuppressLint("Doclava125")
4681    public @Nullable String getDeviceInitializerApp() {
4682        return null;
4683    }
4684
4685    /**
4686     * @hide
4687     * @deprecated Do not use
4688     * @removed
4689     */
4690    @Deprecated
4691    @SystemApi
4692    @SuppressLint("Doclava125")
4693    public @Nullable ComponentName getDeviceInitializerComponent() {
4694        return null;
4695    }
4696
4697    /**
4698     * @hide
4699     * @deprecated Use #ACTION_SET_PROFILE_OWNER
4700     * Sets the given component as an active admin and registers the package as the profile
4701     * owner for this user. The package must already be installed and there shouldn't be
4702     * an existing profile owner registered for this user. Also, this method must be called
4703     * before the user setup has been completed.
4704     * <p>
4705     * This method can only be called by system apps that hold MANAGE_USERS permission and
4706     * MANAGE_DEVICE_ADMINS permission.
4707     * @param admin The component to register as an active admin and profile owner.
4708     * @param ownerName The user-visible name of the entity that is managing this user.
4709     * @return whether the admin was successfully registered as the profile owner.
4710     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
4711     *         the user has already been set up.
4712     */
4713    @Deprecated
4714    @SystemApi
4715    @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
4716    public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
4717            throws IllegalArgumentException {
4718        throwIfParentInstance("setActiveProfileOwner");
4719        if (mService != null) {
4720            try {
4721                final int myUserId = myUserId();
4722                mService.setActiveAdmin(admin, false, myUserId);
4723                return mService.setProfileOwner(admin, ownerName, myUserId);
4724            } catch (RemoteException re) {
4725                throw re.rethrowFromSystemServer();
4726            }
4727        }
4728        return false;
4729    }
4730
4731    /**
4732     * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
4733     * a SecurityException will be thrown. This method is not available to managed profile owners.
4734     * <p>
4735     * While some policies previously set by the profile owner will be cleared by this method, it is
4736     * a best-effort process and some other policies will still remain in place after the profile
4737     * owner is cleared.
4738     *
4739     * @param admin The component to remove as the profile owner.
4740     * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
4741     * being called from a managed profile.
4742     *
4743     * @deprecated This method is expected to be used for testing purposes only. The profile owner
4744     * will lose control of the user and its data after calling it. In order to protect any
4745     * sensitive data that remains on this user, it is advised that the profile owner deletes it
4746     * instead of calling this method. See {@link #wipeData(int)}.
4747     */
4748    @Deprecated
4749    public void clearProfileOwner(@NonNull ComponentName admin) {
4750        throwIfParentInstance("clearProfileOwner");
4751        if (mService != null) {
4752            try {
4753                mService.clearProfileOwner(admin);
4754            } catch (RemoteException re) {
4755                throw re.rethrowFromSystemServer();
4756            }
4757        }
4758    }
4759
4760    /**
4761     * @hide
4762     * Checks whether the user was already setup.
4763     */
4764    public boolean hasUserSetupCompleted() {
4765        if (mService != null) {
4766            try {
4767                return mService.hasUserSetupCompleted();
4768            } catch (RemoteException re) {
4769                throw re.rethrowFromSystemServer();
4770            }
4771        }
4772        return true;
4773    }
4774
4775    /**
4776     * @hide
4777     * Sets the given component as the profile owner of the given user profile. The package must
4778     * already be installed. There must not already be a profile owner for this user.
4779     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
4780     * this method.
4781     * Calling this after the setup phase of the specified user has completed is allowed only if:
4782     * - the caller is SYSTEM_UID.
4783     * - or the caller is the shell uid, and there are no accounts on the specified user.
4784     * @param admin the component name to be registered as profile owner.
4785     * @param ownerName the human readable name of the organisation associated with this DPM.
4786     * @param userHandle the userId to set the profile owner for.
4787     * @return whether the component was successfully registered as the profile owner.
4788     * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
4789     * preconditions mentioned are not met.
4790     */
4791    public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
4792            int userHandle) throws IllegalArgumentException {
4793        if (mService != null) {
4794            try {
4795                if (ownerName == null) {
4796                    ownerName = "";
4797                }
4798                return mService.setProfileOwner(admin, ownerName, userHandle);
4799            } catch (RemoteException re) {
4800                throw re.rethrowFromSystemServer();
4801            }
4802        }
4803        return false;
4804    }
4805
4806    /**
4807     * Sets the device owner information to be shown on the lock screen.
4808     * <p>
4809     * If the device owner information is {@code null} or empty then the device owner info is
4810     * cleared and the user owner info is shown on the lock screen if it is set.
4811     * <p>
4812     * If the device owner information contains only whitespaces then the message on the lock screen
4813     * will be blank and the user will not be allowed to change it.
4814     * <p>
4815     * If the device owner information needs to be localized, it is the responsibility of the
4816     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
4817     * and set a new version of this string accordingly.
4818     *
4819     * @param admin The name of the admin component to check.
4820     * @param info Device owner information which will be displayed instead of the user owner info.
4821     * @throws SecurityException if {@code admin} is not a device owner.
4822     */
4823    public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
4824        throwIfParentInstance("setDeviceOwnerLockScreenInfo");
4825        if (mService != null) {
4826            try {
4827                mService.setDeviceOwnerLockScreenInfo(admin, info);
4828            } catch (RemoteException re) {
4829                throw re.rethrowFromSystemServer();
4830            }
4831        }
4832    }
4833
4834    /**
4835     * @return The device owner information. If it is not set returns {@code null}.
4836     */
4837    public CharSequence getDeviceOwnerLockScreenInfo() {
4838        throwIfParentInstance("getDeviceOwnerLockScreenInfo");
4839        if (mService != null) {
4840            try {
4841                return mService.getDeviceOwnerLockScreenInfo();
4842            } catch (RemoteException re) {
4843                throw re.rethrowFromSystemServer();
4844            }
4845        }
4846        return null;
4847    }
4848
4849    /**
4850     * Called by device or profile owners to suspend packages for this user. This function can be
4851     * called by a device owner, profile owner, or by a delegate given the
4852     * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
4853     * <p>
4854     * A suspended package will not be able to start activities. Its notifications will be hidden,
4855     * it will not show up in recents, will not be able to show toasts or dialogs or ring the
4856     * device.
4857     * <p>
4858     * The package must already be installed. If the package is uninstalled while suspended the
4859     * package will no longer be suspended. The admin can block this by using
4860     * {@link #setUninstallBlocked}.
4861     *
4862     * @param admin The name of the admin component to check, or {@code null} if the caller is a
4863     *            package access delegate.
4864     * @param packageNames The package names to suspend or unsuspend.
4865     * @param suspended If set to {@code true} than the packages will be suspended, if set to
4866     *            {@code false} the packages will be unsuspended.
4867     * @return an array of package names for which the suspended status is not set as requested in
4868     *         this method.
4869     * @throws SecurityException if {@code admin} is not a device or profile owner.
4870     * @see #setDelegatedScopes
4871     * @see #DELEGATION_PACKAGE_ACCESS
4872     */
4873    public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
4874            @NonNull String[] packageNames, boolean suspended) {
4875        throwIfParentInstance("setPackagesSuspended");
4876        if (mService != null) {
4877            try {
4878                return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
4879                        suspended);
4880            } catch (RemoteException re) {
4881                throw re.rethrowFromSystemServer();
4882            }
4883        }
4884        return packageNames;
4885    }
4886
4887    /**
4888     * Determine if a package is suspended. This function can be called by a device owner, profile
4889     * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
4890     * {@link #setDelegatedScopes}.
4891     *
4892     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4893     *            {@code null} if the caller is a package access delegate.
4894     * @param packageName The name of the package to retrieve the suspended status of.
4895     * @return {@code true} if the package is suspended or {@code false} if the package is not
4896     *         suspended, could not be found or an error occurred.
4897     * @throws SecurityException if {@code admin} is not a device or profile owner.
4898     * @throws NameNotFoundException if the package could not be found.
4899     * @see #setDelegatedScopes
4900     * @see #DELEGATION_PACKAGE_ACCESS
4901     */
4902    public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
4903            throws NameNotFoundException {
4904        throwIfParentInstance("isPackageSuspended");
4905        if (mService != null) {
4906            try {
4907                return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
4908            } catch (RemoteException e) {
4909                throw e.rethrowFromSystemServer();
4910            } catch (IllegalArgumentException ex) {
4911                throw new NameNotFoundException(packageName);
4912            }
4913        }
4914        return false;
4915    }
4916
4917    /**
4918     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
4919     * be used. Only the profile owner can call this.
4920     *
4921     * @see #isProfileOwnerApp
4922     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4923     * @throws SecurityException if {@code admin} is not a profile owner.
4924     */
4925    public void setProfileEnabled(@NonNull ComponentName admin) {
4926        throwIfParentInstance("setProfileEnabled");
4927        if (mService != null) {
4928            try {
4929                mService.setProfileEnabled(admin);
4930            } catch (RemoteException e) {
4931                throw e.rethrowFromSystemServer();
4932            }
4933        }
4934    }
4935
4936    /**
4937     * Sets the name of the profile. In the device owner case it sets the name of the user which it
4938     * is called from. Only a profile owner or device owner can call this. If this is never called
4939     * by the profile or device owner, the name will be set to default values.
4940     *
4941     * @see #isProfileOwnerApp
4942     * @see #isDeviceOwnerApp
4943     * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
4944     * @param profileName The name of the profile.
4945     * @throws SecurityException if {@code admin} is not a device or profile owner.
4946     */
4947    public void setProfileName(@NonNull ComponentName admin, String profileName) {
4948        throwIfParentInstance("setProfileName");
4949        if (mService != null) {
4950            try {
4951                mService.setProfileName(admin, profileName);
4952            } catch (RemoteException e) {
4953                throw e.rethrowFromSystemServer();
4954            }
4955        }
4956    }
4957
4958    /**
4959     * Used to determine if a particular package is registered as the profile owner for the
4960     * user. A profile owner is a special device admin that has additional privileges
4961     * within the profile.
4962     *
4963     * @param packageName The package name of the app to compare with the registered profile owner.
4964     * @return Whether or not the package is registered as the profile owner.
4965     */
4966    public boolean isProfileOwnerApp(String packageName) {
4967        throwIfParentInstance("isProfileOwnerApp");
4968        if (mService != null) {
4969            try {
4970                ComponentName profileOwner = mService.getProfileOwner(myUserId());
4971                return profileOwner != null
4972                        && profileOwner.getPackageName().equals(packageName);
4973            } catch (RemoteException re) {
4974                throw re.rethrowFromSystemServer();
4975            }
4976        }
4977        return false;
4978    }
4979
4980    /**
4981     * @hide
4982     * @return the packageName of the owner of the given user profile or {@code null} if no profile
4983     * owner has been set for that user.
4984     * @throws IllegalArgumentException if the userId is invalid.
4985     */
4986    @SystemApi
4987    public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
4988        throwIfParentInstance("getProfileOwner");
4989        return getProfileOwnerAsUser(Process.myUserHandle().getIdentifier());
4990    }
4991
4992    /**
4993     * @see #getProfileOwner()
4994     * @hide
4995     */
4996    public @Nullable ComponentName getProfileOwnerAsUser(final int userId)
4997            throws IllegalArgumentException {
4998        if (mService != null) {
4999            try {
5000                return mService.getProfileOwner(userId);
5001            } catch (RemoteException re) {
5002                throw re.rethrowFromSystemServer();
5003            }
5004        }
5005        return null;
5006    }
5007
5008    /**
5009     * @hide
5010     * @return the human readable name of the organisation associated with this DPM or {@code null}
5011     *         if one is not set.
5012     * @throws IllegalArgumentException if the userId is invalid.
5013     */
5014    public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
5015        if (mService != null) {
5016            try {
5017                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
5018            } catch (RemoteException re) {
5019                throw re.rethrowFromSystemServer();
5020            }
5021        }
5022        return null;
5023    }
5024
5025    /**
5026     * @hide
5027     * @param userId The user for whom to fetch the profile owner name, if any.
5028     * @return the human readable name of the organisation associated with this profile owner or
5029     *         null if one is not set.
5030     * @throws IllegalArgumentException if the userId is invalid.
5031     */
5032    @SystemApi
5033    public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
5034        throwIfParentInstance("getProfileOwnerNameAsUser");
5035        if (mService != null) {
5036            try {
5037                return mService.getProfileOwnerName(userId);
5038            } catch (RemoteException re) {
5039                throw re.rethrowFromSystemServer();
5040            }
5041        }
5042        return null;
5043    }
5044
5045    /**
5046     * Called by a profile owner or device owner to add a default intent handler activity for
5047     * intents that match a certain intent filter. This activity will remain the default intent
5048     * handler even if the set of potential event handlers for the intent filter changes and if the
5049     * intent preferences are reset.
5050     * <p>
5051     * The default disambiguation mechanism takes over if the activity is not installed (anymore).
5052     * When the activity is (re)installed, it is automatically reset as default intent handler for
5053     * the filter.
5054     * <p>
5055     * The calling device admin must be a profile owner or device owner. If it is not, a security
5056     * exception will be thrown.
5057     *
5058     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5059     * @param filter The IntentFilter for which a default handler is added.
5060     * @param activity The Activity that is added as default intent handler.
5061     * @throws SecurityException if {@code admin} is not a device or profile owner.
5062     */
5063    public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
5064            @NonNull ComponentName activity) {
5065        throwIfParentInstance("addPersistentPreferredActivity");
5066        if (mService != null) {
5067            try {
5068                mService.addPersistentPreferredActivity(admin, filter, activity);
5069            } catch (RemoteException e) {
5070                throw e.rethrowFromSystemServer();
5071            }
5072        }
5073    }
5074
5075    /**
5076     * Called by a profile owner or device owner to remove all persistent intent handler preferences
5077     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
5078     * <p>
5079     * The calling device admin must be a profile owner. If it is not, a security exception will be
5080     * thrown.
5081     *
5082     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5083     * @param packageName The name of the package for which preferences are removed.
5084     * @throws SecurityException if {@code admin} is not a device or profile owner.
5085     */
5086    public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
5087            String packageName) {
5088        throwIfParentInstance("clearPackagePersistentPreferredActivities");
5089        if (mService != null) {
5090            try {
5091                mService.clearPackagePersistentPreferredActivities(admin, packageName);
5092            } catch (RemoteException e) {
5093                throw e.rethrowFromSystemServer();
5094            }
5095        }
5096    }
5097
5098    /**
5099     * Called by a profile owner or device owner to grant permission to a package to manage
5100     * application restrictions for the calling user via {@link #setApplicationRestrictions} and
5101     * {@link #getApplicationRestrictions}.
5102     * <p>
5103     * This permission is persistent until it is later cleared by calling this method with a
5104     * {@code null} value or uninstalling the managing package.
5105     * <p>
5106     * The supplied application restriction managing package must be installed when calling this
5107     * API, otherwise an {@link NameNotFoundException} will be thrown.
5108     *
5109     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5110     * @param packageName The package name which will be given access to application restrictions
5111     *            APIs. If {@code null} is given the current package will be cleared.
5112     * @throws SecurityException if {@code admin} is not a device or profile owner.
5113     * @throws NameNotFoundException if {@code packageName} is not found
5114     *
5115     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5116     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5117     */
5118    @Deprecated
5119    public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
5120            @Nullable String packageName) throws NameNotFoundException {
5121        throwIfParentInstance("setApplicationRestrictionsManagingPackage");
5122        if (mService != null) {
5123            try {
5124                if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
5125                    throw new NameNotFoundException(packageName);
5126                }
5127            } catch (RemoteException e) {
5128                throw e.rethrowFromSystemServer();
5129            }
5130        }
5131    }
5132
5133    /**
5134     * Called by a profile owner or device owner to retrieve the application restrictions managing
5135     * package for the current user, or {@code null} if none is set. If there are multiple
5136     * delegates this function will return one of them.
5137     *
5138     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5139     * @return The package name allowed to manage application restrictions on the current user, or
5140     *         {@code null} if none is set.
5141     * @throws SecurityException if {@code admin} is not a device or profile owner.
5142     *
5143     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5144     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5145     */
5146    @Deprecated
5147    @Nullable
5148    public String getApplicationRestrictionsManagingPackage(
5149            @NonNull ComponentName admin) {
5150        throwIfParentInstance("getApplicationRestrictionsManagingPackage");
5151        if (mService != null) {
5152            try {
5153                return mService.getApplicationRestrictionsManagingPackage(admin);
5154            } catch (RemoteException e) {
5155                throw e.rethrowFromSystemServer();
5156            }
5157        }
5158        return null;
5159    }
5160
5161    /**
5162     * Called by any application to find out whether it has been granted permission via
5163     * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
5164     * for the calling user.
5165     *
5166     * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
5167     * that method.
5168     *
5169     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
5170     * instead.
5171     */
5172    @Deprecated
5173    public boolean isCallerApplicationRestrictionsManagingPackage() {
5174        throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
5175        if (mService != null) {
5176            try {
5177                return mService.isCallerApplicationRestrictionsManagingPackage(
5178                        mContext.getPackageName());
5179            } catch (RemoteException e) {
5180                throw e.rethrowFromSystemServer();
5181            }
5182        }
5183        return false;
5184    }
5185
5186    /**
5187     * Sets the application restrictions for a given target application running in the calling user.
5188     * <p>
5189     * The caller must be a profile or device owner on that user, or the package allowed to manage
5190     * application restrictions via {@link #setDelegatedScopes} with the
5191     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
5192     * <p>
5193     * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
5194     * <ul>
5195     * <li>{@code boolean}
5196     * <li>{@code int}
5197     * <li>{@code String} or {@code String[]}
5198     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
5199     * </ul>
5200     * <p>
5201     * If the restrictions are not available yet, but may be applied in the near future, the caller
5202     * can notify the target application of that by adding
5203     * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
5204     * <p>
5205     * The application restrictions are only made visible to the target application via
5206     * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
5207     * owner, and the application restrictions managing package via
5208     * {@link #getApplicationRestrictions}.
5209     *
5210     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
5211     *
5212     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5213     *            {@code null} if called by the application restrictions managing package.
5214     * @param packageName The name of the package to update restricted settings for.
5215     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
5216     *            set of active restrictions.
5217     * @throws SecurityException if {@code admin} is not a device or profile owner.
5218     * @see #setDelegatedScopes
5219     * @see #DELEGATION_APP_RESTRICTIONS
5220     * @see UserManager#KEY_RESTRICTIONS_PENDING
5221     */
5222    @WorkerThread
5223    public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
5224            Bundle settings) {
5225        throwIfParentInstance("setApplicationRestrictions");
5226        if (mService != null) {
5227            try {
5228                mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
5229                        settings);
5230            } catch (RemoteException e) {
5231                throw e.rethrowFromSystemServer();
5232            }
5233        }
5234    }
5235
5236    /**
5237     * Sets a list of configuration features to enable for a TrustAgent component. This is meant to
5238     * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
5239     * agents but those enabled by this function call. If flag
5240     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
5241     * <p>
5242     * The calling device admin must have requested
5243     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
5244     * if not, a security exception will be thrown.
5245     * <p>
5246     * This method can be called on the {@link DevicePolicyManager} instance returned by
5247     * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
5248     * the parent profile.
5249     *
5250     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5251     * @param target Component name of the agent to be enabled.
5252     * @param configuration TrustAgent-specific feature bundle. If null for any admin, agent will be
5253     *            strictly disabled according to the state of the
5254     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS} flag.
5255     *            <p>
5256     *            If {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is set and options is not null for all
5257     *            admins, then it's up to the TrustAgent itself to aggregate the values from all
5258     *            device admins.
5259     *            <p>
5260     *            Consult documentation for the specific TrustAgent to determine legal options
5261     *            parameters.
5262     * @throws SecurityException if {@code admin} is not an active administrator or does not use
5263     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
5264     */
5265    public void setTrustAgentConfiguration(@NonNull ComponentName admin,
5266            @NonNull ComponentName target, PersistableBundle configuration) {
5267        if (mService != null) {
5268            try {
5269                mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
5270            } catch (RemoteException e) {
5271                throw e.rethrowFromSystemServer();
5272            }
5273        }
5274    }
5275
5276    /**
5277     * Gets configuration for the given trust agent based on aggregating all calls to
5278     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
5279     * all device admins.
5280     * <p>
5281     * This method can be called on the {@link DevicePolicyManager} instance returned by
5282     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
5283     * on the parent profile.
5284     *
5285     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
5286     * this function returns a list of configurations for all admins that declare
5287     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
5288     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
5289     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
5290     * for this {@param agent} or calls it with a null configuration, null is returned.
5291     * @param agent Which component to get enabled features for.
5292     * @return configuration for the given trust agent.
5293     */
5294    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5295            @Nullable ComponentName admin, @NonNull ComponentName agent) {
5296        return getTrustAgentConfiguration(admin, agent, myUserId());
5297    }
5298
5299    /** @hide per-user version */
5300    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5301            @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
5302        if (mService != null) {
5303            try {
5304                return mService.getTrustAgentConfiguration(admin, agent, userHandle,
5305                        mParentInstance);
5306            } catch (RemoteException e) {
5307                throw e.rethrowFromSystemServer();
5308            }
5309        }
5310        return new ArrayList<PersistableBundle>(); // empty list
5311    }
5312
5313    /**
5314     * Called by a profile owner of a managed profile to set whether caller-Id information from the
5315     * managed profile will be shown in the parent profile, for incoming calls.
5316     * <p>
5317     * The calling device admin must be a profile owner. If it is not, a security exception will be
5318     * thrown.
5319     *
5320     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5321     * @param disabled If true caller-Id information in the managed profile is not displayed.
5322     * @throws SecurityException if {@code admin} is not a device or profile owner.
5323     */
5324    public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
5325        throwIfParentInstance("setCrossProfileCallerIdDisabled");
5326        if (mService != null) {
5327            try {
5328                mService.setCrossProfileCallerIdDisabled(admin, disabled);
5329            } catch (RemoteException e) {
5330                throw e.rethrowFromSystemServer();
5331            }
5332        }
5333    }
5334
5335    /**
5336     * Called by a profile owner of a managed profile to determine whether or not caller-Id
5337     * information has been disabled.
5338     * <p>
5339     * The calling device admin must be a profile owner. If it is not, a security exception will be
5340     * thrown.
5341     *
5342     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5343     * @throws SecurityException if {@code admin} is not a device or profile owner.
5344     */
5345    public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
5346        throwIfParentInstance("getCrossProfileCallerIdDisabled");
5347        if (mService != null) {
5348            try {
5349                return mService.getCrossProfileCallerIdDisabled(admin);
5350            } catch (RemoteException e) {
5351                throw e.rethrowFromSystemServer();
5352            }
5353        }
5354        return false;
5355    }
5356
5357    /**
5358     * Determine whether or not caller-Id information has been disabled.
5359     *
5360     * @param userHandle The user for whom to check the caller-id permission
5361     * @hide
5362     */
5363    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
5364        if (mService != null) {
5365            try {
5366                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
5367            } catch (RemoteException e) {
5368                throw e.rethrowFromSystemServer();
5369            }
5370        }
5371        return false;
5372    }
5373
5374    /**
5375     * Called by a profile owner of a managed profile to set whether contacts search from the
5376     * managed profile will be shown in the parent profile, for incoming calls.
5377     * <p>
5378     * The calling device admin must be a profile owner. If it is not, a security exception will be
5379     * thrown.
5380     *
5381     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5382     * @param disabled If true contacts search in the managed profile is not displayed.
5383     * @throws SecurityException if {@code admin} is not a device or profile owner.
5384     */
5385    public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
5386            boolean disabled) {
5387        throwIfParentInstance("setCrossProfileContactsSearchDisabled");
5388        if (mService != null) {
5389            try {
5390                mService.setCrossProfileContactsSearchDisabled(admin, disabled);
5391            } catch (RemoteException e) {
5392                throw e.rethrowFromSystemServer();
5393            }
5394        }
5395    }
5396
5397    /**
5398     * Called by a profile owner of a managed profile to determine whether or not contacts search
5399     * has been disabled.
5400     * <p>
5401     * The calling device admin must be a profile owner. If it is not, a security exception will be
5402     * thrown.
5403     *
5404     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5405     * @throws SecurityException if {@code admin} is not a device or profile owner.
5406     */
5407    public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
5408        throwIfParentInstance("getCrossProfileContactsSearchDisabled");
5409        if (mService != null) {
5410            try {
5411                return mService.getCrossProfileContactsSearchDisabled(admin);
5412            } catch (RemoteException e) {
5413                throw e.rethrowFromSystemServer();
5414            }
5415        }
5416        return false;
5417    }
5418
5419
5420    /**
5421     * Determine whether or not contacts search has been disabled.
5422     *
5423     * @param userHandle The user for whom to check the contacts search permission
5424     * @hide
5425     */
5426    public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
5427        if (mService != null) {
5428            try {
5429                return mService
5430                        .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
5431            } catch (RemoteException e) {
5432                throw e.rethrowFromSystemServer();
5433            }
5434        }
5435        return false;
5436    }
5437
5438    /**
5439     * Start Quick Contact on the managed profile for the user, if the policy allows.
5440     *
5441     * @hide
5442     */
5443    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5444            boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
5445        if (mService != null) {
5446            try {
5447                mService.startManagedQuickContact(actualLookupKey, actualContactId,
5448                        isContactIdIgnored, directoryId, originalIntent);
5449            } catch (RemoteException e) {
5450                throw e.rethrowFromSystemServer();
5451            }
5452        }
5453    }
5454
5455    /**
5456     * Start Quick Contact on the managed profile for the user, if the policy allows.
5457     * @hide
5458     */
5459    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5460            Intent originalIntent) {
5461        startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
5462                originalIntent);
5463    }
5464
5465    /**
5466     * Called by a profile owner of a managed profile to set whether bluetooth devices can access
5467     * enterprise contacts.
5468     * <p>
5469     * The calling device admin must be a profile owner. If it is not, a security exception will be
5470     * thrown.
5471     * <p>
5472     * This API works on managed profile only.
5473     *
5474     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5475     * @param disabled If true, bluetooth devices cannot access enterprise contacts.
5476     * @throws SecurityException if {@code admin} is not a device or profile owner.
5477     */
5478    public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
5479        throwIfParentInstance("setBluetoothContactSharingDisabled");
5480        if (mService != null) {
5481            try {
5482                mService.setBluetoothContactSharingDisabled(admin, disabled);
5483            } catch (RemoteException e) {
5484                throw e.rethrowFromSystemServer();
5485            }
5486        }
5487    }
5488
5489    /**
5490     * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
5491     * cannot access enterprise contacts.
5492     * <p>
5493     * The calling device admin must be a profile owner. If it is not, a security exception will be
5494     * thrown.
5495     * <p>
5496     * This API works on managed profile only.
5497     *
5498     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5499     * @throws SecurityException if {@code admin} is not a device or profile owner.
5500     */
5501    public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
5502        throwIfParentInstance("getBluetoothContactSharingDisabled");
5503        if (mService != null) {
5504            try {
5505                return mService.getBluetoothContactSharingDisabled(admin);
5506            } catch (RemoteException e) {
5507                throw e.rethrowFromSystemServer();
5508            }
5509        }
5510        return true;
5511    }
5512
5513    /**
5514     * Determine whether or not Bluetooth devices cannot access contacts.
5515     * <p>
5516     * This API works on managed profile UserHandle only.
5517     *
5518     * @param userHandle The user for whom to check the caller-id permission
5519     * @hide
5520     */
5521    public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
5522        if (mService != null) {
5523            try {
5524                return mService.getBluetoothContactSharingDisabledForUser(userHandle
5525                        .getIdentifier());
5526            } catch (RemoteException e) {
5527                throw e.rethrowFromSystemServer();
5528            }
5529        }
5530        return true;
5531    }
5532
5533    /**
5534     * Called by the profile owner of a managed profile so that some intents sent in the managed
5535     * profile can also be resolved in the parent, or vice versa. Only activity intents are
5536     * supported.
5537     *
5538     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5539     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
5540     *            other profile
5541     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
5542     *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
5543     * @throws SecurityException if {@code admin} is not a device or profile owner.
5544     */
5545    public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
5546        throwIfParentInstance("addCrossProfileIntentFilter");
5547        if (mService != null) {
5548            try {
5549                mService.addCrossProfileIntentFilter(admin, filter, flags);
5550            } catch (RemoteException e) {
5551                throw e.rethrowFromSystemServer();
5552            }
5553        }
5554    }
5555
5556    /**
5557     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
5558     * that go from the managed profile to the parent, or from the parent to the managed profile.
5559     * Only removes those that have been set by the profile owner.
5560     *
5561     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5562     * @throws SecurityException if {@code admin} is not a device or profile owner.
5563     */
5564    public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
5565        throwIfParentInstance("clearCrossProfileIntentFilters");
5566        if (mService != null) {
5567            try {
5568                mService.clearCrossProfileIntentFilters(admin);
5569            } catch (RemoteException e) {
5570                throw e.rethrowFromSystemServer();
5571            }
5572        }
5573    }
5574
5575    /**
5576     * Called by a profile or device owner to set the permitted accessibility services. When set by
5577     * a device owner or profile owner the restriction applies to all profiles of the user the
5578     * device owner or profile owner is an admin for. By default the user can use any accessiblity
5579     * service. When zero or more packages have been added, accessiblity services that are not in
5580     * the list and not part of the system can not be enabled by the user.
5581     * <p>
5582     * Calling with a null value for the list disables the restriction so that all services can be
5583     * used, calling with an empty list only allows the builtin system's services.
5584     * <p>
5585     * System accessibility services are always available to the user the list can't modify this.
5586     *
5587     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5588     * @param packageNames List of accessibility service package names.
5589     * @return true if setting the restriction succeeded. It fail if there is one or more non-system
5590     *         accessibility services enabled, that are not in the list.
5591     * @throws SecurityException if {@code admin} is not a device or profile owner.
5592     */
5593    public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
5594            List<String> packageNames) {
5595        throwIfParentInstance("setPermittedAccessibilityServices");
5596        if (mService != null) {
5597            try {
5598                return mService.setPermittedAccessibilityServices(admin, packageNames);
5599            } catch (RemoteException e) {
5600                throw e.rethrowFromSystemServer();
5601            }
5602        }
5603        return false;
5604    }
5605
5606    /**
5607     * Returns the list of permitted accessibility services set by this device or profile owner.
5608     * <p>
5609     * An empty list means no accessibility services except system services are allowed. Null means
5610     * all accessibility services are allowed.
5611     *
5612     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5613     * @return List of accessiblity service package names.
5614     * @throws SecurityException if {@code admin} is not a device or profile owner.
5615     */
5616    public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
5617        throwIfParentInstance("getPermittedAccessibilityServices");
5618        if (mService != null) {
5619            try {
5620                return mService.getPermittedAccessibilityServices(admin);
5621            } catch (RemoteException e) {
5622                throw e.rethrowFromSystemServer();
5623            }
5624        }
5625        return null;
5626    }
5627
5628    /**
5629     * Called by the system to check if a specific accessibility service is disabled by admin.
5630     *
5631     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5632     * @param packageName Accessibility service package name that needs to be checked.
5633     * @param userHandle user id the admin is running as.
5634     * @return true if the accessibility service is permitted, otherwise false.
5635     *
5636     * @hide
5637     */
5638    public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
5639            @NonNull String packageName, int userHandle) {
5640        if (mService != null) {
5641            try {
5642                return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
5643                        userHandle);
5644            } catch (RemoteException e) {
5645                throw e.rethrowFromSystemServer();
5646            }
5647        }
5648        return false;
5649    }
5650
5651    /**
5652     * Returns the list of accessibility services permitted by the device or profiles
5653     * owners of this user.
5654     *
5655     * <p>Null means all accessibility services are allowed, if a non-null list is returned
5656     * it will contain the intersection of the permitted lists for any device or profile
5657     * owners that apply to this user. It will also include any system accessibility services.
5658     *
5659     * @param userId which user to check for.
5660     * @return List of accessiblity service package names.
5661     * @hide
5662     */
5663     @SystemApi
5664     public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
5665        throwIfParentInstance("getPermittedAccessibilityServices");
5666        if (mService != null) {
5667            try {
5668                return mService.getPermittedAccessibilityServicesForUser(userId);
5669            } catch (RemoteException e) {
5670                throw e.rethrowFromSystemServer();
5671            }
5672        }
5673        return null;
5674     }
5675
5676    /**
5677     * Called by a profile or device owner to set the permitted input methods services. When set by
5678     * a device owner or profile owner the restriction applies to all profiles of the user the
5679     * device owner or profile owner is an admin for. By default the user can use any input method.
5680     * When zero or more packages have been added, input method that are not in the list and not
5681     * part of the system can not be enabled by the user. This method will fail if it is called for
5682     * a admin that is not for the foreground user or a profile of the foreground user.
5683     * <p>
5684     * Calling with a null value for the list disables the restriction so that all input methods can
5685     * be used, calling with an empty list disables all but the system's own input methods.
5686     * <p>
5687     * System input methods are always available to the user this method can't modify this.
5688     *
5689     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5690     * @param packageNames List of input method package names.
5691     * @return true if setting the restriction succeeded. It will fail if there are one or more
5692     *         non-system input methods currently enabled that are not in the packageNames list.
5693     * @throws SecurityException if {@code admin} is not a device or profile owner.
5694     */
5695    public boolean setPermittedInputMethods(
5696            @NonNull ComponentName admin, List<String> packageNames) {
5697        throwIfParentInstance("setPermittedInputMethods");
5698        if (mService != null) {
5699            try {
5700                return mService.setPermittedInputMethods(admin, packageNames);
5701            } catch (RemoteException e) {
5702                throw e.rethrowFromSystemServer();
5703            }
5704        }
5705        return false;
5706    }
5707
5708
5709    /**
5710     * Returns the list of permitted input methods set by this device or profile owner.
5711     * <p>
5712     * An empty list means no input methods except system input methods are allowed. Null means all
5713     * input methods are allowed.
5714     *
5715     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5716     * @return List of input method package names.
5717     * @throws SecurityException if {@code admin} is not a device or profile owner.
5718     */
5719    public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
5720        throwIfParentInstance("getPermittedInputMethods");
5721        if (mService != null) {
5722            try {
5723                return mService.getPermittedInputMethods(admin);
5724            } catch (RemoteException e) {
5725                throw e.rethrowFromSystemServer();
5726            }
5727        }
5728        return null;
5729    }
5730
5731    /**
5732     * Called by the system to check if a specific input method is disabled by admin.
5733     *
5734     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5735     * @param packageName Input method package name that needs to be checked.
5736     * @param userHandle user id the admin is running as.
5737     * @return true if the input method is permitted, otherwise false.
5738     *
5739     * @hide
5740     */
5741    public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
5742            @NonNull String packageName, int userHandle) {
5743        if (mService != null) {
5744            try {
5745                return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
5746            } catch (RemoteException e) {
5747                throw e.rethrowFromSystemServer();
5748            }
5749        }
5750        return false;
5751    }
5752
5753    /**
5754     * Returns the list of input methods permitted by the device or profiles
5755     * owners of the current user.  (*Not* calling user, due to a limitation in InputMethodManager.)
5756     *
5757     * <p>Null means all input methods are allowed, if a non-null list is returned
5758     * it will contain the intersection of the permitted lists for any device or profile
5759     * owners that apply to this user. It will also include any system input methods.
5760     *
5761     * @return List of input method package names.
5762     * @hide
5763     */
5764    @SystemApi
5765    public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
5766        throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
5767        if (mService != null) {
5768            try {
5769                return mService.getPermittedInputMethodsForCurrentUser();
5770            } catch (RemoteException e) {
5771                throw e.rethrowFromSystemServer();
5772            }
5773        }
5774        return null;
5775    }
5776
5777    /**
5778     * Called by a profile owner of a managed profile to set the packages that are allowed to use
5779     * a {@link android.service.notification.NotificationListenerService} in the primary user to
5780     * see notifications from the managed profile. By default all packages are permitted by this
5781     * policy. When zero or more packages have been added, notification listeners installed on the
5782     * primary user that are not in the list and are not part of the system won't receive events
5783     * for managed profile notifications.
5784     * <p>
5785     * Calling with a {@code null} value for the list disables the restriction so that all
5786     * notification listener services be used. Calling with an empty list disables all but the
5787     * system's own notification listeners. System notification listener services are always
5788     * available to the user.
5789     * <p>
5790     * If a device or profile owner want to stop notification listeners in their user from seeing
5791     * that user's notifications they should prevent that service from running instead (e.g. via
5792     * {@link #setApplicationHidden(ComponentName, String, boolean)})
5793     *
5794     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5795     * @param packageList List of package names to whitelist
5796     * @return true if setting the restriction succeeded. It will fail if called outside a managed
5797     * profile
5798     * @throws SecurityException if {@code admin} is not a profile owner.
5799     *
5800     * @see android.service.notification.NotificationListenerService
5801     */
5802    public boolean setPermittedCrossProfileNotificationListeners(
5803            @NonNull ComponentName admin, @Nullable List<String> packageList) {
5804        throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
5805        if (mService != null) {
5806            try {
5807                return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
5808            } catch (RemoteException e) {
5809                throw e.rethrowFromSystemServer();
5810            }
5811        }
5812        return false;
5813    }
5814
5815    /**
5816     * Returns the list of packages installed on the primary user that allowed to use a
5817     * {@link android.service.notification.NotificationListenerService} to receive
5818     * notifications from this managed profile, as set by the profile owner.
5819     * <p>
5820     * An empty list means no notification listener services except system ones are allowed.
5821     * A {@code null} return value indicates that all notification listeners are allowed.
5822     */
5823    public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
5824            @NonNull ComponentName admin) {
5825        throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
5826        if (mService != null) {
5827            try {
5828                return mService.getPermittedCrossProfileNotificationListeners(admin);
5829            } catch (RemoteException e) {
5830                throw e.rethrowFromSystemServer();
5831            }
5832        }
5833        return null;
5834    }
5835
5836    /**
5837     * Returns true if {@code NotificationListenerServices} from the given package are allowed to
5838     * receive events for notifications from the given user id. Can only be called by the system uid
5839     *
5840     * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
5841     *
5842     * @hide
5843     */
5844    public boolean isNotificationListenerServicePermitted(
5845            @NonNull String packageName, @UserIdInt int userId) {
5846        if (mService != null) {
5847            try {
5848                return mService.isNotificationListenerServicePermitted(packageName, userId);
5849            } catch (RemoteException e) {
5850                throw e.rethrowFromSystemServer();
5851            }
5852        }
5853        return true;
5854    }
5855
5856    /**
5857     * Get the list of apps to keep around as APKs even if no user has currently installed it. This
5858     * function can be called by a device owner or by a delegate given the
5859     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
5860     * <p>
5861     * Please note that packages returned in this method are not automatically pre-cached.
5862     *
5863     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5864     *            {@code null} if the caller is a keep uninstalled packages delegate.
5865     * @return List of package names to keep cached.
5866     * @see #setDelegatedScopes
5867     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
5868     * @hide
5869     */
5870    public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
5871        throwIfParentInstance("getKeepUninstalledPackages");
5872        if (mService != null) {
5873            try {
5874                return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
5875            } catch (RemoteException e) {
5876                throw e.rethrowFromSystemServer();
5877            }
5878        }
5879        return null;
5880    }
5881
5882    /**
5883     * Set a list of apps to keep around as APKs even if no user has currently installed it. This
5884     * function can be called by a device owner or by a delegate given the
5885     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
5886     *
5887     * <p>Please note that setting this policy does not imply that specified apps will be
5888     * automatically pre-cached.</p>
5889     *
5890     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5891     *            {@code null} if the caller is a keep uninstalled packages delegate.
5892     * @param packageNames List of package names to keep cached.
5893     * @throws SecurityException if {@code admin} is not a device owner.
5894     * @see #setDelegatedScopes
5895     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
5896     * @hide
5897     */
5898    public void setKeepUninstalledPackages(@Nullable ComponentName admin,
5899            @NonNull List<String> packageNames) {
5900        throwIfParentInstance("setKeepUninstalledPackages");
5901        if (mService != null) {
5902            try {
5903                mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
5904            } catch (RemoteException e) {
5905                throw e.rethrowFromSystemServer();
5906            }
5907        }
5908    }
5909
5910    /**
5911     * Called by a device owner to create a user with the specified name. The UserHandle returned
5912     * by this method should not be persisted as user handles are recycled as users are removed and
5913     * created. If you need to persist an identifier for this user, use
5914     * {@link UserManager#getSerialNumberForUser}.
5915     *
5916     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5917     * @param name the user's name
5918     * @see UserHandle
5919     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
5920     *         user could not be created.
5921     *
5922     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
5923     * @removed From {@link android.os.Build.VERSION_CODES#N}
5924     */
5925    @Deprecated
5926    public @Nullable UserHandle createUser(@NonNull ComponentName admin, String name) {
5927        return null;
5928    }
5929
5930    /**
5931     * Called by a device owner to create a user with the specified name. The UserHandle returned
5932     * by this method should not be persisted as user handles are recycled as users are removed and
5933     * created. If you need to persist an identifier for this user, use
5934     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
5935     * immediately.
5936     *
5937     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
5938     * as registered as an active admin on the new user.  The profile owner package will be
5939     * installed on the new user if it already is installed on the device.
5940     *
5941     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
5942     * profileOwnerComponent when onEnable is called.
5943     *
5944     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5945     * @param name the user's name
5946     * @param ownerName the human readable name of the organisation associated with this DPM.
5947     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
5948     *      the user.
5949     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
5950     *      on the new user.
5951     * @see UserHandle
5952     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
5953     *         user could not be created.
5954     *
5955     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
5956     * @removed From {@link android.os.Build.VERSION_CODES#N}
5957     */
5958    @Deprecated
5959    public @Nullable UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
5960            String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
5961        return null;
5962    }
5963
5964    /**
5965      * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
5966      */
5967    public static final int SKIP_SETUP_WIZARD = 0x0001;
5968
5969    /**
5970     * Flag used by {@link #createAndManageUser} to specify that the user should be created
5971     * ephemeral.
5972     * @hide
5973     */
5974    public static final int MAKE_USER_EPHEMERAL = 0x0002;
5975
5976    /**
5977     * Called by a device owner to create a user with the specified name and a given component of
5978     * the calling package as profile owner. The UserHandle returned by this method should not be
5979     * persisted as user handles are recycled as users are removed and created. If you need to
5980     * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
5981     * user will not be started in the background.
5982     * <p>
5983     * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
5984     * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
5985     * be registered as an active admin on the new user. The profile owner package will be installed
5986     * on the new user.
5987     * <p>
5988     * If the adminExtras are not null, they will be stored on the device until the user is started
5989     * for the first time. Then the extras will be passed to the admin when onEnable is called.
5990     *
5991     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5992     * @param name The user's name.
5993     * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
5994     *            same package as admin, otherwise no user is created and an
5995     *            IllegalArgumentException is thrown.
5996     * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
5997     *            user.
5998     * @param flags {@link #SKIP_SETUP_WIZARD} is supported.
5999     * @see UserHandle
6000     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6001     *         user could not be created.
6002     * @throws SecurityException if {@code admin} is not a device owner.
6003     */
6004    public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
6005            @NonNull String name,
6006            @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
6007            int flags) {
6008        throwIfParentInstance("createAndManageUser");
6009        try {
6010            return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
6011        } catch (RemoteException re) {
6012            throw re.rethrowFromSystemServer();
6013        }
6014    }
6015
6016    /**
6017     * Called by a device owner to remove a user and all associated data. The primary user can not
6018     * be removed.
6019     *
6020     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6021     * @param userHandle the user to remove.
6022     * @return {@code true} if the user was removed, {@code false} otherwise.
6023     * @throws SecurityException if {@code admin} is not a device owner.
6024     */
6025    public boolean removeUser(@NonNull ComponentName admin, UserHandle userHandle) {
6026        throwIfParentInstance("removeUser");
6027        try {
6028            return mService.removeUser(admin, userHandle);
6029        } catch (RemoteException re) {
6030            throw re.rethrowFromSystemServer();
6031        }
6032    }
6033
6034    /**
6035     * Called by a device owner to switch the specified user to the foreground.
6036     *
6037     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6038     * @param userHandle the user to switch to; null will switch to primary.
6039     * @return {@code true} if the switch was successful, {@code false} otherwise.
6040     * @throws SecurityException if {@code admin} is not a device owner.
6041     * @see Intent#ACTION_USER_FOREGROUND
6042     */
6043    public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
6044        throwIfParentInstance("switchUser");
6045        try {
6046            return mService.switchUser(admin, userHandle);
6047        } catch (RemoteException re) {
6048            throw re.rethrowFromSystemServer();
6049        }
6050    }
6051
6052    /**
6053     * Retrieves the application restrictions for a given target application running in the calling
6054     * user.
6055     * <p>
6056     * The caller must be a profile or device owner on that user, or the package allowed to manage
6057     * application restrictions via {@link #setDelegatedScopes} with the
6058     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
6059     *
6060     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
6061     *
6062     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6063     *            {@code null} if called by the application restrictions managing package.
6064     * @param packageName The name of the package to fetch restricted settings of.
6065     * @return {@link Bundle} of settings corresponding to what was set last time
6066     *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
6067     *         {@link Bundle} if no restrictions have been set.
6068     * @throws SecurityException if {@code admin} is not a device or profile owner.
6069     * @see #setDelegatedScopes
6070     * @see #DELEGATION_APP_RESTRICTIONS
6071     */
6072    @WorkerThread
6073    public @NonNull Bundle getApplicationRestrictions(
6074            @Nullable ComponentName admin, String packageName) {
6075        throwIfParentInstance("getApplicationRestrictions");
6076        if (mService != null) {
6077            try {
6078                return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
6079                        packageName);
6080            } catch (RemoteException e) {
6081                throw e.rethrowFromSystemServer();
6082            }
6083        }
6084        return null;
6085    }
6086
6087    /**
6088     * Called by a profile or device owner to set a user restriction specified by the key.
6089     * <p>
6090     * The calling device admin must be a profile or device owner; if it is not, a security
6091     * exception will be thrown.
6092     *
6093     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6094     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6095     *            for the list of keys.
6096     * @throws SecurityException if {@code admin} is not a device or profile owner.
6097     */
6098    public void addUserRestriction(@NonNull ComponentName admin, String key) {
6099        throwIfParentInstance("addUserRestriction");
6100        if (mService != null) {
6101            try {
6102                mService.setUserRestriction(admin, key, true);
6103            } catch (RemoteException e) {
6104                throw e.rethrowFromSystemServer();
6105            }
6106        }
6107    }
6108
6109    /**
6110     * Called by a profile or device owner to clear a user restriction specified by the key.
6111     * <p>
6112     * The calling device admin must be a profile or device owner; if it is not, a security
6113     * exception will be thrown.
6114     *
6115     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6116     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6117     *            for the list of keys.
6118     * @throws SecurityException if {@code admin} is not a device or profile owner.
6119     */
6120    public void clearUserRestriction(@NonNull ComponentName admin, String key) {
6121        throwIfParentInstance("clearUserRestriction");
6122        if (mService != null) {
6123            try {
6124                mService.setUserRestriction(admin, key, false);
6125            } catch (RemoteException e) {
6126                throw e.rethrowFromSystemServer();
6127            }
6128        }
6129    }
6130
6131    /**
6132     * Called by a profile or device owner to get user restrictions set with
6133     * {@link #addUserRestriction(ComponentName, String)}.
6134     * <p>
6135     * The target user may have more restrictions set by the system or other device owner / profile
6136     * owner. To get all the user restrictions currently set, use
6137     * {@link UserManager#getUserRestrictions()}.
6138     *
6139     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6140     * @throws SecurityException if {@code admin} is not a device or profile owner.
6141     */
6142    public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
6143        throwIfParentInstance("getUserRestrictions");
6144        Bundle ret = null;
6145        if (mService != null) {
6146            try {
6147                ret = mService.getUserRestrictions(admin);
6148            } catch (RemoteException e) {
6149                throw e.rethrowFromSystemServer();
6150            }
6151        }
6152        return ret == null ? new Bundle() : ret;
6153    }
6154
6155    /**
6156     * Called by any app to display a support dialog when a feature was disabled by an admin.
6157     * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
6158     * display the dialog. It will tell the user that the feature indicated by {@code restriction}
6159     * was disabled by an admin, and include a link for more information. The default content of
6160     * the dialog can be changed by the restricting admin via
6161     * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
6162     * set (i.e. the feature is available), then the return value will be {@code null}.
6163     * @param restriction Indicates for which feature the dialog should be displayed. Can be a
6164     *            user restriction from {@link UserManager}, e.g.
6165     *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
6166     *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
6167     * @return Intent An intent to be used to start the dialog-activity if the restriction is
6168     *            set by an admin, or null if the restriction does not exist or no admin set it.
6169     */
6170    public Intent createAdminSupportIntent(@NonNull String restriction) {
6171        throwIfParentInstance("createAdminSupportIntent");
6172        if (mService != null) {
6173            try {
6174                return mService.createAdminSupportIntent(restriction);
6175            } catch (RemoteException e) {
6176                throw e.rethrowFromSystemServer();
6177            }
6178        }
6179        return null;
6180    }
6181
6182    /**
6183     * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
6184     * actual package file remain. This function can be called by a device owner, profile owner, or
6185     * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6186     * {@link #setDelegatedScopes}.
6187     *
6188     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6189     *            {@code null} if the caller is a package access delegate.
6190     * @param packageName The name of the package to hide or unhide.
6191     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
6192     *            unhidden.
6193     * @return boolean Whether the hidden setting of the package was successfully updated.
6194     * @throws SecurityException if {@code admin} is not a device or profile owner.
6195     * @see #setDelegatedScopes
6196     * @see #DELEGATION_PACKAGE_ACCESS
6197     */
6198    public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
6199            boolean hidden) {
6200        throwIfParentInstance("setApplicationHidden");
6201        if (mService != null) {
6202            try {
6203                return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
6204                        hidden);
6205            } catch (RemoteException e) {
6206                throw e.rethrowFromSystemServer();
6207            }
6208        }
6209        return false;
6210    }
6211
6212    /**
6213     * Determine if a package is hidden. This function can be called by a device owner, profile
6214     * owner, or 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 retrieve the hidden status of.
6220     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
6221     * @throws SecurityException if {@code admin} is not a device or profile owner.
6222     * @see #setDelegatedScopes
6223     * @see #DELEGATION_PACKAGE_ACCESS
6224     */
6225    public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
6226        throwIfParentInstance("isApplicationHidden");
6227        if (mService != null) {
6228            try {
6229                return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName);
6230            } catch (RemoteException e) {
6231                throw e.rethrowFromSystemServer();
6232            }
6233        }
6234        return false;
6235    }
6236
6237    /**
6238     * Re-enable a system app that was disabled by default when the user was initialized. This
6239     * function can be called by a device owner, profile owner, or by a delegate given the
6240     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6241     *
6242     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6243     *            {@code null} if the caller is an enable system app delegate.
6244     * @param packageName The package to be re-enabled in the calling profile.
6245     * @throws SecurityException if {@code admin} is not a device or profile owner.
6246     * @see #setDelegatedScopes
6247     * @see #DELEGATION_PACKAGE_ACCESS
6248     */
6249    public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
6250        throwIfParentInstance("enableSystemApp");
6251        if (mService != null) {
6252            try {
6253                mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
6254            } catch (RemoteException e) {
6255                throw e.rethrowFromSystemServer();
6256            }
6257        }
6258    }
6259
6260    /**
6261     * Re-enable system apps by intent that were disabled by default when the user was initialized.
6262     * This function can be called by a device owner, profile owner, or by a delegate given the
6263     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6264     *
6265     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6266     *            {@code null} if the caller is an enable system app delegate.
6267     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
6268     *            intent will be re-enabled in the calling profile.
6269     * @return int The number of activities that matched the intent and were installed.
6270     * @throws SecurityException if {@code admin} is not a device or profile owner.
6271     * @see #setDelegatedScopes
6272     * @see #DELEGATION_PACKAGE_ACCESS
6273     */
6274    public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
6275        throwIfParentInstance("enableSystemApp");
6276        if (mService != null) {
6277            try {
6278                return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
6279            } catch (RemoteException e) {
6280                throw e.rethrowFromSystemServer();
6281            }
6282        }
6283        return 0;
6284    }
6285
6286    /**
6287     * Called by a device owner or profile owner to disable account management for a specific type
6288     * of account.
6289     * <p>
6290     * The calling device admin must be a device owner or profile owner. If it is not, a security
6291     * exception will be thrown.
6292     * <p>
6293     * When account management is disabled for an account type, adding or removing an account of
6294     * that type will not be possible.
6295     * <p>
6296     * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
6297     * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
6298     * management for a specific type is disabled.
6299     *
6300     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6301     * @param accountType For which account management is disabled or enabled.
6302     * @param disabled The boolean indicating that account management will be disabled (true) or
6303     *            enabled (false).
6304     * @throws SecurityException if {@code admin} is not a device or profile owner.
6305     */
6306    public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
6307            boolean disabled) {
6308        throwIfParentInstance("setAccountManagementDisabled");
6309        if (mService != null) {
6310            try {
6311                mService.setAccountManagementDisabled(admin, accountType, disabled);
6312            } catch (RemoteException e) {
6313                throw e.rethrowFromSystemServer();
6314            }
6315        }
6316    }
6317
6318    /**
6319     * Gets the array of accounts for which account management is disabled by the profile owner.
6320     *
6321     * <p> Account management can be disabled/enabled by calling
6322     * {@link #setAccountManagementDisabled}.
6323     *
6324     * @return a list of account types for which account management has been disabled.
6325     *
6326     * @see #setAccountManagementDisabled
6327     */
6328    public @Nullable String[] getAccountTypesWithManagementDisabled() {
6329        throwIfParentInstance("getAccountTypesWithManagementDisabled");
6330        return getAccountTypesWithManagementDisabledAsUser(myUserId());
6331    }
6332
6333    /**
6334     * @see #getAccountTypesWithManagementDisabled()
6335     * @hide
6336     */
6337    public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
6338        if (mService != null) {
6339            try {
6340                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
6341            } catch (RemoteException e) {
6342                throw e.rethrowFromSystemServer();
6343            }
6344        }
6345
6346        return null;
6347    }
6348
6349    /**
6350     * Sets which packages may enter lock task mode.
6351     * <p>
6352     * Any packages that share uid with an allowed package will also be allowed to activate lock
6353     * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
6354     * package list results in locked tasks belonging to those packages to be finished.
6355     * <p>
6356     * This function can only be called by the device owner or by a profile owner of a user/profile
6357     * that is affiliated with the device owner user. See {@link #setAffiliationIds}. Any packages
6358     * set via this method will be cleared if the user becomes unaffiliated.
6359     *
6360     * @param packages The list of packages allowed to enter lock task mode
6361     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6362     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
6363     * an affiliated user or profile.
6364     * @see Activity#startLockTask()
6365     * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
6366     * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
6367     * @see UserManager#DISALLOW_CREATE_WINDOWS
6368     */
6369    public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
6370            throws SecurityException {
6371        throwIfParentInstance("setLockTaskPackages");
6372        if (mService != null) {
6373            try {
6374                mService.setLockTaskPackages(admin, packages);
6375            } catch (RemoteException e) {
6376                throw e.rethrowFromSystemServer();
6377            }
6378        }
6379    }
6380
6381    /**
6382     * Returns the list of packages allowed to start the lock task mode.
6383     *
6384     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
6385     * an affiliated user or profile.
6386     * @see #setLockTaskPackages
6387     */
6388    public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
6389        throwIfParentInstance("getLockTaskPackages");
6390        if (mService != null) {
6391            try {
6392                return mService.getLockTaskPackages(admin);
6393            } catch (RemoteException e) {
6394                throw e.rethrowFromSystemServer();
6395            }
6396        }
6397        return new String[0];
6398    }
6399
6400    /**
6401     * This function lets the caller know whether the given component is allowed to start the
6402     * lock task mode.
6403     * @param pkg The package to check
6404     */
6405    public boolean isLockTaskPermitted(String pkg) {
6406        throwIfParentInstance("isLockTaskPermitted");
6407        if (mService != null) {
6408            try {
6409                return mService.isLockTaskPermitted(pkg);
6410            } catch (RemoteException e) {
6411                throw e.rethrowFromSystemServer();
6412            }
6413        }
6414        return false;
6415    }
6416
6417    /**
6418     * Called by device owners to update {@link Settings.Global} settings. Validation that the value
6419     * of the setting is in the correct form for the setting type should be performed by the caller.
6420     * <p>
6421     * The settings that can be updated with this method are:
6422     * <ul>
6423     * <li>{@link Settings.Global#ADB_ENABLED}</li>
6424     * <li>{@link Settings.Global#AUTO_TIME}</li>
6425     * <li>{@link Settings.Global#AUTO_TIME_ZONE}</li>
6426     * <li>{@link Settings.Global#DATA_ROAMING}</li>
6427     * <li>{@link Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
6428     * <li>{@link Settings.Global#WIFI_SLEEP_POLICY}</li>
6429     * <li>{@link Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only available from
6430     * {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
6431     * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
6432     * <li>{@link Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This setting is only
6433     * available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
6434     * </ul>
6435     * <p>
6436     * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
6437     * <ul>
6438     * <li>{@link Settings.Global#BLUETOOTH_ON}. Use
6439     * {@link android.bluetooth.BluetoothAdapter#enable()} and
6440     * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
6441     * <li>{@link Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
6442     * <li>{@link Settings.Global#MODE_RINGER}. Use
6443     * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
6444     * <li>{@link Settings.Global#NETWORK_PREFERENCE}</li>
6445     * <li>{@link Settings.Global#WIFI_ON}. Use
6446     * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
6447     * </ul>
6448     *
6449     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6450     * @param setting The name of the setting to update.
6451     * @param value The value to update the setting to.
6452     * @throws SecurityException if {@code admin} is not a device owner.
6453     */
6454    public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
6455        throwIfParentInstance("setGlobalSetting");
6456        if (mService != null) {
6457            try {
6458                mService.setGlobalSetting(admin, setting, value);
6459            } catch (RemoteException e) {
6460                throw e.rethrowFromSystemServer();
6461            }
6462        }
6463    }
6464
6465    /**
6466     * Called by profile or device owners to update {@link Settings.Secure} settings. Validation
6467     * that the value of the setting is in the correct form for the setting type should be performed
6468     * by the caller.
6469     * <p>
6470     * The settings that can be updated by a profile or device owner with this method are:
6471     * <ul>
6472     * <li>{@link Settings.Secure#DEFAULT_INPUT_METHOD}</li>
6473     * <li>{@link Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
6474     * </ul>
6475     * <p>
6476     * A device owner can additionally update the following settings:
6477     * <ul>
6478     * <li>{@link Settings.Secure#LOCATION_MODE}</li>
6479     * </ul>
6480     *
6481     * <strong>Note: Starting from Android O, apps should no longer call this method with the
6482     * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
6483     * deprecated. Instead, device owners or profile owners should use the restriction
6484     * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
6485     * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
6486     * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
6487     * an {@link UnsupportedOperationException} is thrown.
6488     * </strong>
6489     *
6490     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6491     * @param setting The name of the setting to update.
6492     * @param value The value to update the setting to.
6493     * @throws SecurityException if {@code admin} is not a device or profile owner.
6494     */
6495    public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
6496        throwIfParentInstance("setSecureSetting");
6497        if (mService != null) {
6498            try {
6499                mService.setSecureSetting(admin, setting, value);
6500            } catch (RemoteException e) {
6501                throw e.rethrowFromSystemServer();
6502            }
6503        }
6504    }
6505
6506    /**
6507     * Designates a specific service component as the provider for making permission requests of a
6508     * local or remote administrator of the user.
6509     * <p/>
6510     * Only a profile owner can designate the restrictions provider.
6511     *
6512     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6513     * @param provider The component name of the service that implements
6514     *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
6515     *            provider previously assigned.
6516     * @throws SecurityException if {@code admin} is not a device or profile owner.
6517     */
6518    public void setRestrictionsProvider(@NonNull ComponentName admin,
6519            @Nullable ComponentName provider) {
6520        throwIfParentInstance("setRestrictionsProvider");
6521        if (mService != null) {
6522            try {
6523                mService.setRestrictionsProvider(admin, provider);
6524            } catch (RemoteException re) {
6525                throw re.rethrowFromSystemServer();
6526            }
6527        }
6528    }
6529
6530    /**
6531     * Called by profile or device owners to set the master volume mute on or off.
6532     * This has no effect when set on a managed profile.
6533     *
6534     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6535     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
6536     * @throws SecurityException if {@code admin} is not a device or profile owner.
6537     */
6538    public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
6539        throwIfParentInstance("setMasterVolumeMuted");
6540        if (mService != null) {
6541            try {
6542                mService.setMasterVolumeMuted(admin, on);
6543            } catch (RemoteException re) {
6544                throw re.rethrowFromSystemServer();
6545            }
6546        }
6547    }
6548
6549    /**
6550     * Called by profile or device owners to check whether the master volume mute is on or off.
6551     *
6552     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6553     * @return {@code true} if master volume is muted, {@code false} if it's not.
6554     * @throws SecurityException if {@code admin} is not a device or profile owner.
6555     */
6556    public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
6557        throwIfParentInstance("isMasterVolumeMuted");
6558        if (mService != null) {
6559            try {
6560                return mService.isMasterVolumeMuted(admin);
6561            } catch (RemoteException re) {
6562                throw re.rethrowFromSystemServer();
6563            }
6564        }
6565        return false;
6566    }
6567
6568    /**
6569     * Change whether a user can uninstall a package. This function can be called by a device owner,
6570     * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
6571     * {@link #setDelegatedScopes}.
6572     *
6573     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6574     *             {@code null} if the caller is a block uninstall delegate.
6575     * @param packageName package to change.
6576     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
6577     * @throws SecurityException if {@code admin} is not a device or profile owner.
6578     * @see #setDelegatedScopes
6579     * @see #DELEGATION_BLOCK_UNINSTALL
6580     */
6581    public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
6582            boolean uninstallBlocked) {
6583        throwIfParentInstance("setUninstallBlocked");
6584        if (mService != null) {
6585            try {
6586                mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
6587                    uninstallBlocked);
6588            } catch (RemoteException re) {
6589                throw re.rethrowFromSystemServer();
6590            }
6591        }
6592    }
6593
6594    /**
6595     * Check whether the user has been blocked by device policy from uninstalling a package.
6596     * Requires the caller to be the profile owner if checking a specific admin's policy.
6597     * <p>
6598     * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
6599     * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
6600     * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
6601     * will cause a NullPointerException to be raised.
6602     *
6603     * @param admin The name of the admin component whose blocking policy will be checked, or
6604     *            {@code null} to check whether any admin has blocked the uninstallation.
6605     * @param packageName package to check.
6606     * @return true if uninstallation is blocked.
6607     * @throws SecurityException if {@code admin} is not a device or profile owner.
6608     */
6609    public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
6610        throwIfParentInstance("isUninstallBlocked");
6611        if (mService != null) {
6612            try {
6613                return mService.isUninstallBlocked(admin, packageName);
6614            } catch (RemoteException re) {
6615                throw re.rethrowFromSystemServer();
6616            }
6617        }
6618        return false;
6619    }
6620
6621    /**
6622     * Called by the profile owner of a managed profile to enable widget providers from a given
6623     * package to be available in the parent profile. As a result the user will be able to add
6624     * widgets from the white-listed package running under the profile to a widget host which runs
6625     * under the parent profile, for example the home screen. Note that a package may have zero or
6626     * more provider components, where each component provides a different widget type.
6627     * <p>
6628     * <strong>Note:</strong> By default no widget provider package is white-listed.
6629     *
6630     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6631     * @param packageName The package from which widget providers are white-listed.
6632     * @return Whether the package was added.
6633     * @throws SecurityException if {@code admin} is not a profile owner.
6634     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
6635     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
6636     */
6637    public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
6638        throwIfParentInstance("addCrossProfileWidgetProvider");
6639        if (mService != null) {
6640            try {
6641                return mService.addCrossProfileWidgetProvider(admin, packageName);
6642            } catch (RemoteException re) {
6643                throw re.rethrowFromSystemServer();
6644            }
6645        }
6646        return false;
6647    }
6648
6649    /**
6650     * Called by the profile owner of a managed profile to disable widget providers from a given
6651     * package to be available in the parent profile. For this method to take effect the package
6652     * should have been added via
6653     * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
6654     * <p>
6655     * <strong>Note:</strong> By default no widget provider package is white-listed.
6656     *
6657     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6658     * @param packageName The package from which widget providers are no longer white-listed.
6659     * @return Whether the package was removed.
6660     * @throws SecurityException if {@code admin} is not a profile owner.
6661     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
6662     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
6663     */
6664    public boolean removeCrossProfileWidgetProvider(
6665            @NonNull ComponentName admin, String packageName) {
6666        throwIfParentInstance("removeCrossProfileWidgetProvider");
6667        if (mService != null) {
6668            try {
6669                return mService.removeCrossProfileWidgetProvider(admin, packageName);
6670            } catch (RemoteException re) {
6671                throw re.rethrowFromSystemServer();
6672            }
6673        }
6674        return false;
6675    }
6676
6677    /**
6678     * Called by the profile owner of a managed profile to query providers from which packages are
6679     * available in the parent profile.
6680     *
6681     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6682     * @return The white-listed package list.
6683     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
6684     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
6685     * @throws SecurityException if {@code admin} is not a profile owner.
6686     */
6687    public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
6688        throwIfParentInstance("getCrossProfileWidgetProviders");
6689        if (mService != null) {
6690            try {
6691                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
6692                if (providers != null) {
6693                    return providers;
6694                }
6695            } catch (RemoteException re) {
6696                throw re.rethrowFromSystemServer();
6697            }
6698        }
6699        return Collections.emptyList();
6700    }
6701
6702    /**
6703     * Called by profile or device owners to set the user's photo.
6704     *
6705     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6706     * @param icon the bitmap to set as the photo.
6707     * @throws SecurityException if {@code admin} is not a device or profile owner.
6708     */
6709    public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
6710        throwIfParentInstance("setUserIcon");
6711        try {
6712            mService.setUserIcon(admin, icon);
6713        } catch (RemoteException re) {
6714            throw re.rethrowFromSystemServer();
6715        }
6716    }
6717
6718    /**
6719     * Called by device owners to set a local system update policy. When a new policy is set,
6720     * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
6721     *
6722     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
6723     *            components in the device owner package can set system update policies and the most
6724     *            recent policy takes effect.
6725     * @param policy the new policy, or {@code null} to clear the current policy.
6726     * @throws SecurityException if {@code admin} is not a device owner.
6727     * @see SystemUpdatePolicy
6728     */
6729    public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
6730        throwIfParentInstance("setSystemUpdatePolicy");
6731        if (mService != null) {
6732            try {
6733                mService.setSystemUpdatePolicy(admin, policy);
6734            } catch (RemoteException re) {
6735                throw re.rethrowFromSystemServer();
6736            }
6737        }
6738    }
6739
6740    /**
6741     * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
6742     *
6743     * @return The current policy object, or {@code null} if no policy is set.
6744     */
6745    public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
6746        throwIfParentInstance("getSystemUpdatePolicy");
6747        if (mService != null) {
6748            try {
6749                return mService.getSystemUpdatePolicy();
6750            } catch (RemoteException re) {
6751                throw re.rethrowFromSystemServer();
6752            }
6753        }
6754        return null;
6755    }
6756
6757    /**
6758     * Called by a device owner to disable the keyguard altogether.
6759     * <p>
6760     * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
6761     * type. However, this call has no effect if a password, pin or pattern is currently set. If a
6762     * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
6763     * disabled.
6764     *
6765     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6766     * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
6767     * @return {@code false} if attempting to disable the keyguard while a lock password was in
6768     *         place. {@code true} otherwise.
6769     * @throws SecurityException if {@code admin} is not a device owner.
6770     */
6771    public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
6772        throwIfParentInstance("setKeyguardDisabled");
6773        try {
6774            return mService.setKeyguardDisabled(admin, disabled);
6775        } catch (RemoteException re) {
6776            throw re.rethrowFromSystemServer();
6777        }
6778    }
6779
6780    /**
6781     * Called by device owner to disable the status bar. Disabling the status bar blocks
6782     * notifications, quick settings and other screen overlays that allow escaping from a single use
6783     * device.
6784     *
6785     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6786     * @param disabled {@code true} disables the status bar, {@code false} reenables it.
6787     * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
6788     * @throws SecurityException if {@code admin} is not a device owner.
6789     */
6790    public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
6791        throwIfParentInstance("setStatusBarDisabled");
6792        try {
6793            return mService.setStatusBarDisabled(admin, disabled);
6794        } catch (RemoteException re) {
6795            throw re.rethrowFromSystemServer();
6796        }
6797    }
6798
6799    /**
6800     * Called by the system update service to notify device and profile owners of pending system
6801     * updates.
6802     *
6803     * This method should only be used when it is unknown whether the pending system
6804     * update is a security patch. Otherwise, use
6805     * {@link #notifyPendingSystemUpdate(long, boolean)}.
6806     *
6807     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
6808     *         indicating when the current pending update was first available. {@code -1} if no
6809     *         update is available.
6810     * @see #notifyPendingSystemUpdate(long, boolean)
6811     * @hide
6812     */
6813    @SystemApi
6814    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
6815    public void notifyPendingSystemUpdate(long updateReceivedTime) {
6816        throwIfParentInstance("notifyPendingSystemUpdate");
6817        if (mService != null) {
6818            try {
6819                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
6820            } catch (RemoteException re) {
6821                throw re.rethrowFromSystemServer();
6822            }
6823        }
6824    }
6825
6826    /**
6827     * Called by the system update service to notify device and profile owners of pending system
6828     * updates.
6829     *
6830     * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
6831     * when it is known whether the pending system update is a security patch.
6832     *
6833     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
6834     *         indicating when the current pending update was first available. {@code -1} if no
6835     *         update is available.
6836     * @param isSecurityPatch {@code true} if this system update is purely a security patch;
6837     *         {@code false} if not.
6838     * @see #notifyPendingSystemUpdate(long)
6839     * @hide
6840     */
6841    @SystemApi
6842    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
6843    public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
6844        throwIfParentInstance("notifyPendingSystemUpdate");
6845        if (mService != null) {
6846            try {
6847                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
6848                        isSecurityPatch));
6849            } catch (RemoteException re) {
6850                throw re.rethrowFromSystemServer();
6851            }
6852        }
6853    }
6854
6855    /**
6856     * Called by device or profile owners to get information about a pending system update.
6857     *
6858     * @param admin Which profile or device owner this request is associated with.
6859     * @return Information about a pending system update or {@code null} if no update pending.
6860     * @throws SecurityException if {@code admin} is not a device or profile owner.
6861     * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
6862     */
6863    public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
6864        throwIfParentInstance("getPendingSystemUpdate");
6865        try {
6866            return mService.getPendingSystemUpdate(admin);
6867        } catch (RemoteException re) {
6868            throw re.rethrowFromSystemServer();
6869        }
6870    }
6871
6872    /**
6873     * Set the default response for future runtime permission requests by applications. This
6874     * function can be called by a device owner, profile owner, or by a delegate given the
6875     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
6876     * The policy can allow for normal operation which prompts the user to grant a permission, or
6877     * can allow automatic granting or denying of runtime permission requests by an application.
6878     * This also applies to new permissions declared by app updates. When a permission is denied or
6879     * granted this way, the effect is equivalent to setting the permission * grant state via
6880     * {@link #setPermissionGrantState}.
6881     * <p/>
6882     * As this policy only acts on runtime permission requests, it only applies to applications
6883     * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
6884     *
6885     * @param admin Which profile or device owner this request is associated with.
6886     * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
6887     *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
6888     * @throws SecurityException if {@code admin} is not a device or profile owner.
6889     * @see #setPermissionGrantState
6890     * @see #setDelegatedScopes
6891     * @see #DELEGATION_PERMISSION_GRANT
6892     */
6893    public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
6894        throwIfParentInstance("setPermissionPolicy");
6895        try {
6896            mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
6897        } catch (RemoteException re) {
6898            throw re.rethrowFromSystemServer();
6899        }
6900    }
6901
6902    /**
6903     * Returns the current runtime permission policy set by the device or profile owner. The
6904     * default is {@link #PERMISSION_POLICY_PROMPT}.
6905     *
6906     * @param admin Which profile or device owner this request is associated with.
6907     * @return the current policy for future permission requests.
6908     */
6909    public int getPermissionPolicy(ComponentName admin) {
6910        throwIfParentInstance("getPermissionPolicy");
6911        try {
6912            return mService.getPermissionPolicy(admin);
6913        } catch (RemoteException re) {
6914            throw re.rethrowFromSystemServer();
6915        }
6916    }
6917
6918    /**
6919     * Sets the grant state of a runtime permission for a specific application. The state can be
6920     * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
6921     * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
6922     * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
6923     * the permission is granted and the user cannot manage it through the UI. This might affect all
6924     * permissions in a group that the runtime permission belongs to. This method can only be called
6925     * by a profile owner, device owner, or a delegate given the
6926     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
6927     * <p/>
6928     * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
6929     * the permission. It retains the previous grant, if any.
6930     * <p/>
6931     * Permissions can be granted or revoked only for applications built with a
6932     * {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
6933     *
6934     * @param admin Which profile or device owner this request is associated with.
6935     * @param packageName The application to grant or revoke a permission to.
6936     * @param permission The permission to grant or revoke.
6937     * @param grantState The permission grant state which is one of
6938     *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
6939     *            {@link #PERMISSION_GRANT_STATE_GRANTED},
6940     * @return whether the permission was successfully granted or revoked.
6941     * @throws SecurityException if {@code admin} is not a device or profile owner.
6942     * @see #PERMISSION_GRANT_STATE_DENIED
6943     * @see #PERMISSION_GRANT_STATE_DEFAULT
6944     * @see #PERMISSION_GRANT_STATE_GRANTED
6945     * @see #setDelegatedScopes
6946     * @see #DELEGATION_PERMISSION_GRANT
6947     */
6948    public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName,
6949            String permission, int grantState) {
6950        throwIfParentInstance("setPermissionGrantState");
6951        try {
6952            return mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
6953                    permission, grantState);
6954        } catch (RemoteException re) {
6955            throw re.rethrowFromSystemServer();
6956        }
6957    }
6958
6959    /**
6960     * Returns the current grant state of a runtime permission for a specific application. This
6961     * function can be called by a device owner, profile owner, or by a delegate given the
6962     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
6963     *
6964     * @param admin Which profile or device owner this request is associated with, or {@code null}
6965     *            if the caller is a permission grant delegate.
6966     * @param packageName The application to check the grant state for.
6967     * @param permission The permission to check for.
6968     * @return the current grant state specified by device policy. If the profile or device owner
6969     *         has not set a grant state, the return value is
6970     *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
6971     *         permission is currently granted for the package.
6972     *         <p/>
6973     *         If a grant state was set by the profile or device owner, then the return value will
6974     *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
6975     *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
6976     *         currently denied or granted.
6977     * @throws SecurityException if {@code admin} is not a device or profile owner.
6978     * @see #setPermissionGrantState(ComponentName, String, String, int)
6979     * @see PackageManager#checkPermission(String, String)
6980     * @see #setDelegatedScopes
6981     * @see #DELEGATION_PERMISSION_GRANT
6982     */
6983    public int getPermissionGrantState(@Nullable ComponentName admin, String packageName,
6984            String permission) {
6985        throwIfParentInstance("getPermissionGrantState");
6986        try {
6987            return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
6988                    permission);
6989        } catch (RemoteException re) {
6990            throw re.rethrowFromSystemServer();
6991        }
6992    }
6993
6994    /**
6995     * Returns whether it is possible for the caller to initiate provisioning of a managed profile
6996     * or device, setting itself as the device or profile owner.
6997     *
6998     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
6999     * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
7000     * @return whether provisioning a managed profile or device is possible.
7001     * @throws IllegalArgumentException if the supplied action is not valid.
7002     */
7003    public boolean isProvisioningAllowed(@NonNull String action) {
7004        throwIfParentInstance("isProvisioningAllowed");
7005        try {
7006            return mService.isProvisioningAllowed(action, mContext.getPackageName());
7007        } catch (RemoteException re) {
7008            throw re.rethrowFromSystemServer();
7009        }
7010    }
7011
7012    /**
7013     * Checks whether it is possible to initiate provisioning a managed device,
7014     * profile or user, setting the given package as owner.
7015     *
7016     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7017     *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
7018     *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
7019     *        {@link #ACTION_PROVISION_MANAGED_USER}
7020     * @param packageName The package of the component that would be set as device, user, or profile
7021     *        owner.
7022     * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
7023     * @hide
7024     */
7025    public @ProvisioningPreCondition int checkProvisioningPreCondition(
7026            String action, @NonNull String packageName) {
7027        try {
7028            return mService.checkProvisioningPreCondition(action, packageName);
7029        } catch (RemoteException re) {
7030            throw re.rethrowFromSystemServer();
7031        }
7032    }
7033
7034    /**
7035     * Return if this user is a managed profile of another user. An admin can become the profile
7036     * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
7037     * user with {@link #createAndManageUser}
7038     * @param admin Which profile owner this request is associated with.
7039     * @return if this user is a managed profile of another user.
7040     */
7041    public boolean isManagedProfile(@NonNull ComponentName admin) {
7042        throwIfParentInstance("isManagedProfile");
7043        try {
7044            return mService.isManagedProfile(admin);
7045        } catch (RemoteException re) {
7046            throw re.rethrowFromSystemServer();
7047        }
7048    }
7049
7050    /**
7051     * @hide
7052     * Return if this user is a system-only user. An admin can manage a device from a system only
7053     * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
7054     * @param admin Which device owner this request is associated with.
7055     * @return if this user is a system-only user.
7056     */
7057    public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
7058        try {
7059            return mService.isSystemOnlyUser(admin);
7060        } catch (RemoteException re) {
7061            throw re.rethrowFromSystemServer();
7062        }
7063    }
7064
7065    /**
7066     * Called by device owner to get the MAC address of the Wi-Fi device.
7067     *
7068     * @param admin Which device owner this request is associated with.
7069     * @return the MAC address of the Wi-Fi device, or null when the information is not available.
7070     *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
7071     *         <p>
7072     *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
7073     * @throws SecurityException if {@code admin} is not a device owner.
7074     */
7075    public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
7076        throwIfParentInstance("getWifiMacAddress");
7077        try {
7078            return mService.getWifiMacAddress(admin);
7079        } catch (RemoteException re) {
7080            throw re.rethrowFromSystemServer();
7081        }
7082    }
7083
7084    /**
7085     * Called by device owner to reboot the device. If there is an ongoing call on the device,
7086     * throws an {@link IllegalStateException}.
7087     * @param admin Which device owner the request is associated with.
7088     * @throws IllegalStateException if device has an ongoing call.
7089     * @throws SecurityException if {@code admin} is not a device owner.
7090     * @see TelephonyManager#CALL_STATE_IDLE
7091     */
7092    public void reboot(@NonNull ComponentName admin) {
7093        throwIfParentInstance("reboot");
7094        try {
7095            mService.reboot(admin);
7096        } catch (RemoteException re) {
7097            throw re.rethrowFromSystemServer();
7098        }
7099    }
7100
7101    /**
7102     * Called by a device admin to set the short support message. This will be displayed to the user
7103     * in settings screens where funtionality has been disabled by the admin. The message should be
7104     * limited to a short statement such as "This setting is disabled by your administrator. Contact
7105     * someone@example.com for support." If the message is longer than 200 characters it may be
7106     * truncated.
7107     * <p>
7108     * If the short support message needs to be localized, it is the responsibility of the
7109     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7110     * and set a new version of this string accordingly.
7111     *
7112     * @see #setLongSupportMessage
7113     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7114     * @param message Short message to be displayed to the user in settings or null to clear the
7115     *            existing message.
7116     * @throws SecurityException if {@code admin} is not an active administrator.
7117     */
7118    public void setShortSupportMessage(@NonNull ComponentName admin,
7119            @Nullable CharSequence message) {
7120        throwIfParentInstance("setShortSupportMessage");
7121        if (mService != null) {
7122            try {
7123                mService.setShortSupportMessage(admin, message);
7124            } catch (RemoteException e) {
7125                throw e.rethrowFromSystemServer();
7126            }
7127        }
7128    }
7129
7130    /**
7131     * Called by a device admin to get the short support message.
7132     *
7133     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7134     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
7135     *         null if no message has been set.
7136     * @throws SecurityException if {@code admin} is not an active administrator.
7137     */
7138    public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
7139        throwIfParentInstance("getShortSupportMessage");
7140        if (mService != null) {
7141            try {
7142                return mService.getShortSupportMessage(admin);
7143            } catch (RemoteException e) {
7144                throw e.rethrowFromSystemServer();
7145            }
7146        }
7147        return null;
7148    }
7149
7150    /**
7151     * Called by a device admin to set the long support message. This will be displayed to the user
7152     * in the device administators settings screen.
7153     * <p>
7154     * If the long support message needs to be localized, it is the responsibility of the
7155     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7156     * and set a new version of this string accordingly.
7157     *
7158     * @see #setShortSupportMessage
7159     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7160     * @param message Long message to be displayed to the user in settings or null to clear the
7161     *            existing message.
7162     * @throws SecurityException if {@code admin} is not an active administrator.
7163     */
7164    public void setLongSupportMessage(@NonNull ComponentName admin,
7165            @Nullable CharSequence message) {
7166        throwIfParentInstance("setLongSupportMessage");
7167        if (mService != null) {
7168            try {
7169                mService.setLongSupportMessage(admin, message);
7170            } catch (RemoteException e) {
7171                throw e.rethrowFromSystemServer();
7172            }
7173        }
7174    }
7175
7176    /**
7177     * Called by a device admin to get the long support message.
7178     *
7179     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7180     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
7181     *         null if no message has been set.
7182     * @throws SecurityException if {@code admin} is not an active administrator.
7183     */
7184    public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
7185        throwIfParentInstance("getLongSupportMessage");
7186        if (mService != null) {
7187            try {
7188                return mService.getLongSupportMessage(admin);
7189            } catch (RemoteException e) {
7190                throw e.rethrowFromSystemServer();
7191            }
7192        }
7193        return null;
7194    }
7195
7196    /**
7197     * Called by the system to get the short support message.
7198     *
7199     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7200     * @param userHandle user id the admin is running as.
7201     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
7202     *
7203     * @hide
7204     */
7205    public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
7206            int userHandle) {
7207        if (mService != null) {
7208            try {
7209                return mService.getShortSupportMessageForUser(admin, userHandle);
7210            } catch (RemoteException e) {
7211                throw e.rethrowFromSystemServer();
7212            }
7213        }
7214        return null;
7215    }
7216
7217
7218    /**
7219     * Called by the system to get the long support message.
7220     *
7221     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7222     * @param userHandle user id the admin is running as.
7223     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
7224     *
7225     * @hide
7226     */
7227    public @Nullable CharSequence getLongSupportMessageForUser(
7228            @NonNull ComponentName admin, int userHandle) {
7229        if (mService != null) {
7230            try {
7231                return mService.getLongSupportMessageForUser(admin, userHandle);
7232            } catch (RemoteException e) {
7233                throw e.rethrowFromSystemServer();
7234            }
7235        }
7236        return null;
7237    }
7238
7239    /**
7240     * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
7241     * whose calls act on the parent profile.
7242     *
7243     * <p>The following methods are supported for the parent instance, all other methods will
7244     * throw a SecurityException when called on the parent instance:
7245     * <ul>
7246     * <li>{@link #getPasswordQuality}</li>
7247     * <li>{@link #setPasswordQuality}</li>
7248     * <li>{@link #getPasswordMinimumLength}</li>
7249     * <li>{@link #setPasswordMinimumLength}</li>
7250     * <li>{@link #getPasswordMinimumUpperCase}</li>
7251     * <li>{@link #setPasswordMinimumUpperCase}</li>
7252     * <li>{@link #getPasswordMinimumLowerCase}</li>
7253     * <li>{@link #setPasswordMinimumLowerCase}</li>
7254     * <li>{@link #getPasswordMinimumLetters}</li>
7255     * <li>{@link #setPasswordMinimumLetters}</li>
7256     * <li>{@link #getPasswordMinimumNumeric}</li>
7257     * <li>{@link #setPasswordMinimumNumeric}</li>
7258     * <li>{@link #getPasswordMinimumSymbols}</li>
7259     * <li>{@link #setPasswordMinimumSymbols}</li>
7260     * <li>{@link #getPasswordMinimumNonLetter}</li>
7261     * <li>{@link #setPasswordMinimumNonLetter}</li>
7262     * <li>{@link #getPasswordHistoryLength}</li>
7263     * <li>{@link #setPasswordHistoryLength}</li>
7264     * <li>{@link #getPasswordExpirationTimeout}</li>
7265     * <li>{@link #setPasswordExpirationTimeout}</li>
7266     * <li>{@link #getPasswordExpiration}</li>
7267     * <li>{@link #getPasswordMaximumLength}</li>
7268     * <li>{@link #isActivePasswordSufficient}</li>
7269     * <li>{@link #getCurrentFailedPasswordAttempts}</li>
7270     * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
7271     * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
7272     * <li>{@link #getMaximumTimeToLock}</li>
7273     * <li>{@link #setMaximumTimeToLock}</li>
7274     * <li>{@link #lockNow}</li>
7275     * <li>{@link #getKeyguardDisabledFeatures}</li>
7276     * <li>{@link #setKeyguardDisabledFeatures}</li>
7277     * <li>{@link #getTrustAgentConfiguration}</li>
7278     * <li>{@link #setTrustAgentConfiguration}</li>
7279     * <li>{@link #getRequiredStrongAuthTimeout}</li>
7280     * <li>{@link #setRequiredStrongAuthTimeout}</li>
7281     * </ul>
7282     *
7283     * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
7284     * @throws SecurityException if {@code admin} is not a profile owner.
7285     */
7286    public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
7287        throwIfParentInstance("getParentProfileInstance");
7288        try {
7289            if (!mService.isManagedProfile(admin)) {
7290                throw new SecurityException("The current user does not have a parent profile.");
7291            }
7292            return new DevicePolicyManager(mContext, mService, true);
7293        } catch (RemoteException e) {
7294            throw e.rethrowFromSystemServer();
7295        }
7296    }
7297
7298    /**
7299     * Called by device owner to control the security logging feature.
7300     *
7301     * <p> Security logs contain various information intended for security auditing purposes.
7302     * See {@link SecurityEvent} for details.
7303     *
7304     * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
7305     * are unaffiliated secondary users or profiles on the device, regardless of whether the
7306     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
7307     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
7308     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
7309     *
7310     * @param admin Which device owner this request is associated with.
7311     * @param enabled whether security logging should be enabled or not.
7312     * @throws SecurityException if {@code admin} is not a device owner.
7313     * @see #retrieveSecurityLogs
7314     */
7315    public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
7316        throwIfParentInstance("setSecurityLoggingEnabled");
7317        try {
7318            mService.setSecurityLoggingEnabled(admin, enabled);
7319        } catch (RemoteException re) {
7320            throw re.rethrowFromSystemServer();
7321        }
7322    }
7323
7324    /**
7325     * Return whether security logging is enabled or not by the device owner.
7326     *
7327     * <p>Can only be called by the device owner, otherwise a {@link SecurityException} will be
7328     * thrown.
7329     *
7330     * @param admin Which device owner this request is associated with.
7331     * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
7332     * @throws SecurityException if {@code admin} is not a device owner.
7333     */
7334    public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
7335        throwIfParentInstance("isSecurityLoggingEnabled");
7336        try {
7337            return mService.isSecurityLoggingEnabled(admin);
7338        } catch (RemoteException re) {
7339            throw re.rethrowFromSystemServer();
7340        }
7341    }
7342
7343    /**
7344     * Called by device owner to retrieve all new security logging entries since the last call to
7345     * this API after device boots.
7346     *
7347     * <p> Access to the logs is rate limited and it will only return new logs after the device
7348     * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
7349     *
7350     * <p>If there is any other user or profile on the device, it must be affiliated with the
7351     * device owner. Otherwise a {@link SecurityException} will be thrown. See
7352     * {@link #setAffiliationIds}
7353     *
7354     * @param admin Which device owner this request is associated with.
7355     * @return the new batch of security logs which is a list of {@link SecurityEvent},
7356     * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
7357     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
7358     * profile or secondary user that is not affiliated with the device owner user.
7359     * @see DeviceAdminReceiver#onSecurityLogsAvailable
7360     */
7361    public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
7362        throwIfParentInstance("retrieveSecurityLogs");
7363        try {
7364            ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
7365            if (list != null) {
7366                return list.getList();
7367            } else {
7368                // Rate limit exceeded.
7369                return null;
7370            }
7371        } catch (RemoteException re) {
7372            throw re.rethrowFromSystemServer();
7373        }
7374    }
7375
7376    /**
7377     * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
7378     * profile.
7379     *
7380     * @hide
7381     */
7382    public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
7383        mContext.checkSelfPermission(
7384                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
7385        if (!uInfo.isManagedProfile()) {
7386            throw new SecurityException("The user " + uInfo.id
7387                    + " does not have a parent profile.");
7388        }
7389        return new DevicePolicyManager(mContext, mService, true);
7390    }
7391
7392    /**
7393     * Called by device owners to retrieve device logs from before the device's last reboot.
7394     * <p>
7395     * <strong> This API is not supported on all devices. Calling this API on unsupported devices
7396     * will result in {@code null} being returned. The device logs are retrieved from a RAM region
7397     * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
7398     * about data corruption when parsing. </strong>
7399     *
7400     * <p>If there is any other user or profile on the device, it must be affiliated with the
7401     * device owner. Otherwise a {@link SecurityException} will be thrown. See
7402     * {@link #setAffiliationIds}
7403     *
7404     * @param admin Which device owner this request is associated with.
7405     * @return Device logs from before the latest reboot of the system, or {@code null} if this API
7406     *         is not supported on the device.
7407     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
7408     * profile or secondary user that is not affiliated with the device owner user.
7409     * @see #retrieveSecurityLogs
7410     */
7411    public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
7412            @NonNull ComponentName admin) {
7413        throwIfParentInstance("retrievePreRebootSecurityLogs");
7414        try {
7415            ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
7416            if (list != null) {
7417                return list.getList();
7418            } else {
7419                return null;
7420            }
7421        } catch (RemoteException re) {
7422            throw re.rethrowFromSystemServer();
7423        }
7424    }
7425
7426    /**
7427     * Called by a profile owner of a managed profile to set the color used for customization. This
7428     * color is used as background color of the confirm credentials screen for that user. The
7429     * default color is teal (#00796B).
7430     * <p>
7431     * The confirm credentials screen can be created using
7432     * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
7433     *
7434     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7435     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
7436     * @throws SecurityException if {@code admin} is not a profile owner.
7437     */
7438    public void setOrganizationColor(@NonNull ComponentName admin, int color) {
7439        throwIfParentInstance("setOrganizationColor");
7440        try {
7441            // always enforce alpha channel to have 100% opacity
7442            color |= 0xFF000000;
7443            mService.setOrganizationColor(admin, color);
7444        } catch (RemoteException re) {
7445            throw re.rethrowFromSystemServer();
7446        }
7447    }
7448
7449    /**
7450     * @hide
7451     *
7452     * Sets the color used for customization.
7453     *
7454     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
7455     * @param userId which user to set the color to.
7456     * @RequiresPermission(allOf = {
7457     *       Manifest.permission.MANAGE_USERS,
7458     *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
7459     */
7460    public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
7461        try {
7462            // always enforce alpha channel to have 100% opacity
7463            color |= 0xFF000000;
7464            mService.setOrganizationColorForUser(color, userId);
7465        } catch (RemoteException re) {
7466            throw re.rethrowFromSystemServer();
7467        }
7468    }
7469
7470    /**
7471     * Called by a profile owner of a managed profile to retrieve the color used for customization.
7472     * This color is used as background color of the confirm credentials screen for that user.
7473     *
7474     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7475     * @return The 24bit (0xRRGGBB) representation of the color to be used.
7476     * @throws SecurityException if {@code admin} is not a profile owner.
7477     */
7478    public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
7479        throwIfParentInstance("getOrganizationColor");
7480        try {
7481            return mService.getOrganizationColor(admin);
7482        } catch (RemoteException re) {
7483            throw re.rethrowFromSystemServer();
7484        }
7485    }
7486
7487    /**
7488     * @hide
7489     * Retrieve the customization color for a given user.
7490     *
7491     * @param userHandle The user id of the user we're interested in.
7492     * @return The 24bit (0xRRGGBB) representation of the color to be used.
7493     */
7494    public @ColorInt int getOrganizationColorForUser(int userHandle) {
7495        try {
7496            return mService.getOrganizationColorForUser(userHandle);
7497        } catch (RemoteException re) {
7498            throw re.rethrowFromSystemServer();
7499        }
7500    }
7501
7502    /**
7503     * Called by the device owner or profile owner to set the name of the organization under
7504     * management.
7505     * <p>
7506     * If the organization name needs to be localized, it is the responsibility of the
7507     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7508     * and set a new version of this string accordingly.
7509     *
7510     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7511     * @param title The organization name or {@code null} to clear a previously set name.
7512     * @throws SecurityException if {@code admin} is not a device or profile owner.
7513     */
7514    public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
7515        throwIfParentInstance("setOrganizationName");
7516        try {
7517            mService.setOrganizationName(admin, title);
7518        } catch (RemoteException re) {
7519            throw re.rethrowFromSystemServer();
7520        }
7521    }
7522
7523    /**
7524     * Called by a profile owner of a managed profile to retrieve the name of the organization under
7525     * management.
7526     *
7527     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7528     * @return The organization name or {@code null} if none is set.
7529     * @throws SecurityException if {@code admin} is not a profile owner.
7530     */
7531    public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
7532        throwIfParentInstance("getOrganizationName");
7533        try {
7534            return mService.getOrganizationName(admin);
7535        } catch (RemoteException re) {
7536            throw re.rethrowFromSystemServer();
7537        }
7538    }
7539
7540    /**
7541     * Called by the system to retrieve the name of the organization managing the device.
7542     *
7543     * @return The organization name or {@code null} if none is set.
7544     * @throws SecurityException if the caller is not the device owner, does not hold the
7545     *         MANAGE_USERS permission and is not the system.
7546     *
7547     * @hide
7548     */
7549    @SystemApi
7550    @TestApi
7551    public @Nullable CharSequence getDeviceOwnerOrganizationName() {
7552        try {
7553            return mService.getDeviceOwnerOrganizationName();
7554        } catch (RemoteException re) {
7555            throw re.rethrowFromSystemServer();
7556        }
7557    }
7558
7559    /**
7560     * Retrieve the default title message used in the confirm credentials screen for a given user.
7561     *
7562     * @param userHandle The user id of the user we're interested in.
7563     * @return The organization name or {@code null} if none is set.
7564     *
7565     * @hide
7566     */
7567    public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
7568        try {
7569            return mService.getOrganizationNameForUser(userHandle);
7570        } catch (RemoteException re) {
7571            throw re.rethrowFromSystemServer();
7572        }
7573    }
7574
7575    /**
7576     * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
7577     *         return {@link #STATE_USER_UNMANAGED}
7578     * @hide
7579     */
7580    @SystemApi
7581    @UserProvisioningState
7582    public int getUserProvisioningState() {
7583        throwIfParentInstance("getUserProvisioningState");
7584        if (mService != null) {
7585            try {
7586                return mService.getUserProvisioningState();
7587            } catch (RemoteException e) {
7588                throw e.rethrowFromSystemServer();
7589            }
7590        }
7591        return STATE_USER_UNMANAGED;
7592    }
7593
7594    /**
7595     * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
7596     *
7597     * @param state to store
7598     * @param userHandle for user
7599     * @hide
7600     */
7601    public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
7602        if (mService != null) {
7603            try {
7604                mService.setUserProvisioningState(state, userHandle);
7605            } catch (RemoteException e) {
7606                throw e.rethrowFromSystemServer();
7607            }
7608        }
7609    }
7610
7611    /**
7612     * Indicates the entity that controls the device or profile owner. Two users/profiles are
7613     * affiliated if the set of ids set by their device or profile owners intersect.
7614     *
7615     * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
7616     * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user or profile
7617     * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
7618     * affiliation ids are set by its profile owner as soon as possible after the user/profile is
7619     * created.
7620     *
7621     * @param admin Which profile or device owner this request is associated with.
7622     * @param ids A set of opaque non-empty affiliation ids.
7623     *
7624     * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
7625     */
7626    public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
7627        throwIfParentInstance("setAffiliationIds");
7628        if (ids == null) {
7629            throw new IllegalArgumentException("ids must not be null");
7630        }
7631        try {
7632            mService.setAffiliationIds(admin, new ArrayList<>(ids));
7633        } catch (RemoteException e) {
7634            throw e.rethrowFromSystemServer();
7635        }
7636    }
7637
7638    /**
7639     * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
7640     * empty set if none have been set.
7641     */
7642    public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
7643        throwIfParentInstance("getAffiliationIds");
7644        try {
7645            return new ArraySet<>(mService.getAffiliationIds(admin));
7646        } catch (RemoteException e) {
7647            throw e.rethrowFromSystemServer();
7648        }
7649    }
7650
7651    /**
7652     * @hide
7653     * Returns whether this user/profile is affiliated with the device.
7654     * <p>
7655     * By definition, the user that the device owner runs on is always affiliated with the device.
7656     * Any other user/profile is considered affiliated with the device if the set specified by its
7657     * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
7658     *
7659     */
7660    public boolean isAffiliatedUser() {
7661        throwIfParentInstance("isAffiliatedUser");
7662        try {
7663            return mService.isAffiliatedUser();
7664        } catch (RemoteException e) {
7665            throw e.rethrowFromSystemServer();
7666        }
7667    }
7668
7669    /**
7670     * @hide
7671     * Returns whether the uninstall for {@code packageName} for the current user is in queue
7672     * to be started
7673     * @param packageName the package to check for
7674     * @return whether the uninstall intent for {@code packageName} is pending
7675     */
7676    public boolean isUninstallInQueue(String packageName) {
7677        try {
7678            return mService.isUninstallInQueue(packageName);
7679        } catch (RemoteException re) {
7680            throw re.rethrowFromSystemServer();
7681        }
7682    }
7683
7684    /**
7685     * @hide
7686     * @param packageName the package containing active DAs to be uninstalled
7687     */
7688    public void uninstallPackageWithActiveAdmins(String packageName) {
7689        try {
7690            mService.uninstallPackageWithActiveAdmins(packageName);
7691        } catch (RemoteException re) {
7692            throw re.rethrowFromSystemServer();
7693        }
7694    }
7695
7696    /**
7697     * @hide
7698     * Remove a test admin synchronously without sending it a broadcast about being removed.
7699     * If the admin is a profile owner or device owner it will still be removed.
7700     *
7701     * @param userHandle user id to remove the admin for.
7702     * @param admin The administration compononent to remove.
7703     * @throws SecurityException if the caller is not shell / root or the admin package
7704     *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
7705     */
7706    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
7707        try {
7708            mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
7709        } catch (RemoteException re) {
7710            throw re.rethrowFromSystemServer();
7711        }
7712    }
7713
7714    /**
7715     * Returns whether the device has been provisioned.
7716     *
7717     * <p>Not for use by third-party applications.
7718     *
7719     * @hide
7720     */
7721    @SystemApi
7722    public boolean isDeviceProvisioned() {
7723        try {
7724            return mService.isDeviceProvisioned();
7725        } catch (RemoteException re) {
7726            throw re.rethrowFromSystemServer();
7727        }
7728    }
7729
7730    /**
7731      * Writes that the provisioning configuration has been applied.
7732      *
7733      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
7734      * permission.
7735      *
7736      * <p>Not for use by third-party applications.
7737      *
7738      * @hide
7739      */
7740    @SystemApi
7741    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
7742    public void setDeviceProvisioningConfigApplied() {
7743        try {
7744            mService.setDeviceProvisioningConfigApplied();
7745        } catch (RemoteException re) {
7746            throw re.rethrowFromSystemServer();
7747        }
7748    }
7749
7750    /**
7751     * Returns whether the provisioning configuration has been applied.
7752     *
7753     * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
7754     *
7755     * <p>Not for use by third-party applications.
7756     *
7757     * @return whether the provisioning configuration has been applied.
7758     *
7759     * @hide
7760     */
7761    @SystemApi
7762    public boolean isDeviceProvisioningConfigApplied() {
7763        try {
7764            return mService.isDeviceProvisioningConfigApplied();
7765        } catch (RemoteException re) {
7766            throw re.rethrowFromSystemServer();
7767        }
7768    }
7769
7770    /**
7771     * @hide
7772     * Force update user setup completed status. This API has no effect on user build.
7773     * @throws {@link SecurityException} if the caller has no
7774     *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
7775     *         not {@link UserHandle#SYSTEM_USER}
7776     */
7777    public void forceUpdateUserSetupComplete() {
7778        try {
7779            mService.forceUpdateUserSetupComplete();
7780        } catch (RemoteException re) {
7781            throw re.rethrowFromSystemServer();
7782        }
7783    }
7784
7785    private void throwIfParentInstance(String functionName) {
7786        if (mParentInstance) {
7787            throw new SecurityException(functionName + " cannot be called on the parent instance");
7788        }
7789    }
7790
7791    /**
7792     * Allows the device owner to enable or disable the backup service.
7793     *
7794     * <p> Backup service manages all backup and restore mechanisms on the device. Setting this to
7795     * false will prevent data from being backed up or restored.
7796     *
7797     * <p> Backup service is off by default when device owner is present.
7798     *
7799     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7800     * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
7801     * @throws SecurityException if {@code admin} is not a device owner.
7802     */
7803    public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
7804        throwIfParentInstance("setBackupServiceEnabled");
7805        try {
7806            mService.setBackupServiceEnabled(admin, enabled);
7807        } catch (RemoteException re) {
7808            throw re.rethrowFromSystemServer();
7809        }
7810    }
7811
7812    /**
7813     * Return whether the backup service is enabled by the device owner.
7814     *
7815     * <p> Backup service manages all backup and restore mechanisms on the device.
7816     *
7817     * @return {@code true} if backup service is enabled, {@code false} otherwise.
7818     * @see #setBackupServiceEnabled
7819     */
7820    public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
7821        throwIfParentInstance("isBackupServiceEnabled");
7822        try {
7823            return mService.isBackupServiceEnabled(admin);
7824        } catch (RemoteException re) {
7825            throw re.rethrowFromSystemServer();
7826        }
7827    }
7828
7829    /**
7830     * Called by a device owner to control the network logging feature.
7831     *
7832     * <p> Network logs contain DNS lookup and connect() library call events. The following library
7833     *     functions are recorded while network logging is active:
7834     *     <ul>
7835     *       <li>{@code getaddrinfo()}</li>
7836     *       <li>{@code gethostbyname()}</li>
7837     *       <li>{@code connect()}</li>
7838     *     </ul>
7839     *
7840     * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
7841     *     full system call logging; event reporting is enabled by default for all processes but not
7842     *     strongly enforced.
7843     *     Events from applications using alternative implementations of libc, making direct kernel
7844     *     calls, or deliberately obfuscating traffic may not be recorded.
7845     *
7846     * <p> Some common network events may not be reported. For example:
7847     *     <ul>
7848     *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
7849     *           an alternative system for name resolution, and so avoid calling
7850     *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
7851     *       <li>Applications may use datagram sockets for performance reasons, for example
7852     *           for a game client. Calling {@code connect()} is unnecessary for this kind of
7853     *           socket, so it will not trigger a network event.</li>
7854     *     </ul>
7855     *
7856     * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
7857     *     always-on VPN service.
7858     *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
7859     *     and {@link android.net.VpnService} for details.
7860     *
7861     * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
7862     * are unaffiliated secondary users or profiles on the device, regardless of whether the
7863     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
7864     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
7865     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
7866     *
7867     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7868     * @param enabled whether network logging should be enabled or not.
7869     * @throws SecurityException if {@code admin} is not a device owner.
7870     * @see #retrieveNetworkLogs
7871     */
7872    public void setNetworkLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
7873        throwIfParentInstance("setNetworkLoggingEnabled");
7874        try {
7875            mService.setNetworkLoggingEnabled(admin, enabled);
7876        } catch (RemoteException re) {
7877            throw re.rethrowFromSystemServer();
7878        }
7879    }
7880
7881    /**
7882     * Return whether network logging is enabled by a device owner.
7883     *
7884     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
7885     * be {@code null} if the caller has MANAGE_USERS permission.
7886     * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
7887     * @throws SecurityException if {@code admin} is not a device owner and caller has
7888     * no MANAGE_USERS permission
7889     */
7890    public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
7891        throwIfParentInstance("isNetworkLoggingEnabled");
7892        try {
7893            return mService.isNetworkLoggingEnabled(admin);
7894        } catch (RemoteException re) {
7895            throw re.rethrowFromSystemServer();
7896        }
7897    }
7898
7899    /**
7900     * Called by device owner to retrieve the most recent batch of network logging events.
7901     * A device owner has to provide a batchToken provided as part of
7902     * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
7903     * token of the most recent available batch of logs, {@code null} will be returned.
7904     *
7905     * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
7906     *
7907     * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
7908     *
7909     * <p> Access to the logs is rate limited and this method will only return a new batch of logs
7910     * after the device device owner has been notified via
7911     * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
7912     *
7913     * <p>If a secondary user or profile is created, calling this method will throw a
7914     * {@link SecurityException} until all users become affiliated again. It will also no longer be
7915     * possible to retrieve the network logs batch with the most recent batchToken provided
7916     * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
7917     * {@link DevicePolicyManager#setAffiliationIds}.
7918     *
7919     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7920     * @param batchToken A token of the batch to retrieve
7921     * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
7922     *        {@code null} if the batch represented by batchToken is no longer available or if
7923     *        logging is disabled.
7924     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
7925     * profile or secondary user that is not affiliated with the device owner user.
7926     * @see DeviceAdminReceiver#onNetworkLogsAvailable
7927     */
7928    public @Nullable List<NetworkEvent> retrieveNetworkLogs(@NonNull ComponentName admin,
7929            long batchToken) {
7930        throwIfParentInstance("retrieveNetworkLogs");
7931        try {
7932            return mService.retrieveNetworkLogs(admin, batchToken);
7933        } catch (RemoteException re) {
7934            throw re.rethrowFromSystemServer();
7935        }
7936    }
7937
7938    /**
7939     * Called by a device owner to bind to a service from a profile owner or vice versa.
7940     * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
7941     * device/profile owners are allowed to bind to services of another profile/device owner.
7942     * <p>
7943     * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
7944     * Note that the {@link Context} used to obtain this
7945     * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
7946     * to bind to the {@link android.app.Service}.
7947     *
7948     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7949     * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
7950     *        explicit component name or a package name to match an
7951     *        {@link IntentFilter} published by a service.
7952     * @param conn Receives information as the service is started and stopped in main thread. This
7953     *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
7954     * @param flags Operation options for the binding operation. See
7955     *        {@link Context#bindService(Intent, ServiceConnection, int)}.
7956     * @param targetUser Which user to bind to. Must be one of the users returned by
7957     *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
7958     *        be thrown.
7959     * @return If you have successfully bound to the service, {@code true} is returned;
7960     *         {@code false} is returned if the connection is not made and you will not
7961     *         receive the service object.
7962     *
7963     * @see Context#bindService(Intent, ServiceConnection, int)
7964     * @see #getBindDeviceAdminTargetUsers(ComponentName)
7965     */
7966    public boolean bindDeviceAdminServiceAsUser(
7967            @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
7968            @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
7969        throwIfParentInstance("bindDeviceAdminServiceAsUser");
7970        // Keep this in sync with ContextImpl.bindServiceCommon.
7971        try {
7972            final IServiceConnection sd = mContext.getServiceDispatcher(
7973                    conn, mContext.getMainThreadHandler(), flags);
7974            serviceIntent.prepareToLeaveProcess(mContext);
7975            return mService.bindDeviceAdminServiceAsUser(admin,
7976                    mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
7977                    sd, flags, targetUser.getIdentifier());
7978        } catch (RemoteException re) {
7979            throw re.rethrowFromSystemServer();
7980        }
7981    }
7982
7983    /**
7984     * Returns the list of target users that the calling device or profile owner can use when
7985     * calling {@link #bindDeviceAdminServiceAsUser}.
7986     * <p>
7987     * A device owner can bind to a service from a profile owner and vice versa, provided that:
7988     * <ul>
7989     * <li>Both belong to the same package name.
7990     * <li>Both users are affiliated. See {@link #setAffiliationIds}.
7991     * </ul>
7992     */
7993    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
7994        throwIfParentInstance("getBindDeviceAdminTargetUsers");
7995        try {
7996            return mService.getBindDeviceAdminTargetUsers(admin);
7997        } catch (RemoteException re) {
7998            throw re.rethrowFromSystemServer();
7999        }
8000    }
8001
8002    /**
8003     * Called by the system to get the time at which the device owner last retrieved security
8004     * logging entries.
8005     *
8006     * @return the time at which the device owner most recently retrieved security logging entries,
8007     *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
8008     * @throws SecurityException if the caller is not the device owner, does not hold the
8009     *         MANAGE_USERS permission and is not the system.
8010     *
8011     * @hide
8012     */
8013    @TestApi
8014    public long getLastSecurityLogRetrievalTime() {
8015        try {
8016            return mService.getLastSecurityLogRetrievalTime();
8017        } catch (RemoteException re) {
8018            throw re.rethrowFromSystemServer();
8019        }
8020    }
8021
8022    /**
8023     * Called by the system to get the time at which the device owner last requested a bug report.
8024     *
8025     * @return the time at which the device owner most recently requested a bug report, in
8026     *         milliseconds since epoch; -1 if a bug report was never requested.
8027     * @throws SecurityException if the caller is not the device owner, does not hold the
8028     *         MANAGE_USERS permission and is not the system.
8029     *
8030     * @hide
8031     */
8032    @TestApi
8033    public long getLastBugReportRequestTime() {
8034        try {
8035            return mService.getLastBugReportRequestTime();
8036        } catch (RemoteException re) {
8037            throw re.rethrowFromSystemServer();
8038        }
8039    }
8040
8041    /**
8042     * Called by the system to get the time at which the device owner last retrieved network logging
8043     * events.
8044     *
8045     * @return the time at which the device owner most recently retrieved network logging events, in
8046     *         milliseconds since epoch; -1 if network logging events were never retrieved.
8047     * @throws SecurityException if the caller is not the device owner, does not hold the
8048     *         MANAGE_USERS permission and is not the system.
8049     *
8050     * @hide
8051     */
8052    @TestApi
8053    public long getLastNetworkLogRetrievalTime() {
8054        try {
8055            return mService.getLastNetworkLogRetrievalTime();
8056        } catch (RemoteException re) {
8057            throw re.rethrowFromSystemServer();
8058        }
8059    }
8060
8061    /**
8062     * Called by the system to find out whether the current user's IME was set by the device/profile
8063     * owner or the user.
8064     *
8065     * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
8066     *         otherwise.
8067     * @throws SecurityException if the caller is not the device owner/profile owner.
8068     *
8069     * @hide
8070     */
8071    @TestApi
8072    public boolean isCurrentInputMethodSetByOwner() {
8073        try {
8074            return mService.isCurrentInputMethodSetByOwner();
8075        } catch (RemoteException re) {
8076            throw re.rethrowFromSystemServer();
8077        }
8078    }
8079
8080    /**
8081     * Called by the system to get a list of CA certificates that were installed by the device or
8082     * profile owner.
8083     *
8084     * <p> The caller must be the target user's device owner/profile Owner or hold the
8085     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
8086     *
8087     * @param user The user for whom to retrieve information.
8088     * @return list of aliases identifying CA certificates installed by the device or profile owner
8089     * @throws SecurityException if the caller does not have permission to retrieve information
8090     *         about the given user's CA certificates.
8091     *
8092     * @hide
8093     */
8094    @TestApi
8095    public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
8096        try {
8097            return mService.getOwnerInstalledCaCerts(user).getList();
8098        } catch (RemoteException re) {
8099            throw re.rethrowFromSystemServer();
8100        }
8101    }
8102}
8103