DevicePolicyManager.java revision 60d88ea3dd8f3b0dc592141b9ea09c92b1e753c8
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.SdkConstant;
24import android.annotation.SdkConstant.SdkConstantType;
25import android.annotation.SystemApi;
26import android.annotation.TestApi;
27import android.annotation.UserIdInt;
28import android.annotation.WorkerThread;
29import android.app.Activity;
30import android.app.IServiceConnection;
31import android.app.KeyguardManager;
32import android.app.admin.SecurityLog.SecurityEvent;
33import android.content.ComponentName;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.ServiceConnection;
38import android.content.pm.ApplicationInfo;
39import android.content.pm.PackageManager;
40import android.content.pm.PackageManager.NameNotFoundException;
41import android.content.pm.ParceledListSlice;
42import android.content.pm.UserInfo;
43import android.graphics.Bitmap;
44import android.net.ProxyInfo;
45import android.net.Uri;
46import android.os.Bundle;
47import android.os.Parcelable;
48import android.os.PersistableBundle;
49import android.os.Process;
50import android.os.RemoteCallback;
51import android.os.RemoteException;
52import android.os.UserHandle;
53import android.os.UserManager;
54import android.provider.ContactsContract.Directory;
55import android.provider.Settings;
56import android.security.Credentials;
57import android.service.restrictions.RestrictionsReceiver;
58import android.telephony.TelephonyManager;
59import android.util.ArraySet;
60import android.util.Log;
61
62import com.android.internal.annotations.VisibleForTesting;
63import com.android.org.conscrypt.TrustedCertificateStore;
64
65import java.io.ByteArrayInputStream;
66import java.io.IOException;
67import java.lang.annotation.Retention;
68import java.lang.annotation.RetentionPolicy;
69import java.net.InetSocketAddress;
70import java.net.Proxy;
71import java.security.KeyFactory;
72import java.security.NoSuchAlgorithmException;
73import java.security.PrivateKey;
74import java.security.cert.Certificate;
75import java.security.cert.CertificateException;
76import java.security.cert.CertificateFactory;
77import java.security.cert.X509Certificate;
78import java.security.spec.InvalidKeySpecException;
79import java.security.spec.PKCS8EncodedKeySpec;
80import java.util.ArrayList;
81import java.util.Arrays;
82import java.util.Collections;
83import java.util.List;
84import java.util.Set;
85
86/**
87 * Public interface for managing policies enforced on a device. Most clients of this class must be
88 * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
89 * administrator</a>. Additionally, a device administrator may be registered as either a profile or
90 * device owner. A given method is accessible to all device administrators unless the documentation
91 * for that method specifies that it is restricted to either device or profile owners. Any
92 * application calling an api may only pass as an argument a device administrator component it
93 * owns. Otherwise, a {@link SecurityException} will be thrown.
94 * <div class="special reference">
95 * <h3>Developer Guides</h3>
96 * <p>
97 * For more information about managing policies for device administration, read the <a href=
98 * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
99 * guide. </div>
100 */
101public class DevicePolicyManager {
102    private static String TAG = "DevicePolicyManager";
103
104    private final Context mContext;
105    private final IDevicePolicyManager mService;
106    private final boolean mParentInstance;
107
108    /** @hide */
109    public DevicePolicyManager(Context context, IDevicePolicyManager service) {
110        this(context, service, false);
111    }
112
113    /** @hide */
114    @VisibleForTesting
115    protected DevicePolicyManager(Context context, IDevicePolicyManager service,
116            boolean parentInstance) {
117        mContext = context;
118        mService = service;
119        mParentInstance = parentInstance;
120    }
121
122    /** @hide test will override it. */
123    @VisibleForTesting
124    protected int myUserId() {
125        return UserHandle.myUserId();
126    }
127
128    /**
129     * Activity action: Starts the provisioning flow which sets up a managed profile.
130     *
131     * <p>A managed profile allows data separation for example for the usage of a
132     * device as a personal and corporate device. The user which provisioning is started from and
133     * the managed profile share a launcher.
134     *
135     * <p>This intent will typically be sent by a mobile device management application (MDM).
136     * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
137     * control over the profile.
138     *
139     * <p>It is possible to check if provisioning is allowed or not by querying the method
140     * {@link #isProvisioningAllowed(String)}.
141     *
142     * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
143     * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
144     * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
145     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
146     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
147     *
148     * <p>The intent may also contain the following extras:
149     * <ul>
150     * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
151     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
152     * {@link android.os.Build.VERSION_CODES#N}</li>
153     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
154     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
155     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
156     * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
157     * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
158     * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
159     * </ul>
160     *
161     * <p>When managed provisioning has completed, broadcasts are sent to the application specified
162     * in the provisioning intent. The
163     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
164     * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
165     * the primary profile.
166     *
167     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
168     * completed, along with the above broadcast, activity intent
169     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the application specified in
170     * the provisioning intent.
171     *
172     * <p>If provisioning fails, the managedProfile is removed so the device returns to its
173     * previous state.
174     *
175     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
176     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
177     * the provisioning flow was successful, although this doesn't guarantee the full flow will
178     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
179     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
180     */
181    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
182    public static final String ACTION_PROVISION_MANAGED_PROFILE
183        = "android.app.action.PROVISION_MANAGED_PROFILE";
184
185    /**
186     * Activity action: Starts the provisioning flow which sets up a managed user.
187     *
188     * <p>This intent will typically be sent by a mobile device management application (MDM).
189     * Provisioning configures the user as managed user and sets the MDM as the profile
190     * owner who has full control over the user. Provisioning can only happen before user setup has
191     * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
192     * allowed.
193     *
194     * <p>The intent contains the following extras:
195     * <ul>
196     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
197     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
198     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
199     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
200     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
201     * </ul>
202     *
203     * <p>If provisioning fails, the device returns to its previous state.
204     *
205     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
206     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
207     * the provisioning flow was successful, although this doesn't guarantee the full flow will
208     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
209     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
210     *
211     * @hide
212     */
213    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
214    public static final String ACTION_PROVISION_MANAGED_USER
215        = "android.app.action.PROVISION_MANAGED_USER";
216
217    /**
218     * Activity action: Starts the provisioning flow which sets up a managed device.
219     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
220     *
221     * <p> During device owner provisioning a device admin app is set as the owner of the device.
222     * A device owner has full control over the device. The device owner can not be modified by the
223     * user.
224     *
225     * <p> A typical use case would be a device that is owned by a company, but used by either an
226     * employee or client.
227     *
228     * <p> An intent with this action can be sent only on an unprovisioned device.
229     * It is possible to check if provisioning is allowed or not by querying the method
230     * {@link #isProvisioningAllowed(String)}.
231     *
232     * <p>The intent contains the following extras:
233     * <ul>
234     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
235     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
236     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
237     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
238     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
239     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
240     * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
241     * </ul>
242     *
243     * <p>When device owner provisioning has completed, an intent of the type
244     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
245     * device owner.
246     *
247     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
248     * completed, along with the above broadcast, activity intent
249     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
250     *
251     * <p>If provisioning fails, the device is factory reset.
252     *
253     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
254     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
255     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
256     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
257     */
258    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
259    public static final String ACTION_PROVISION_MANAGED_DEVICE
260        = "android.app.action.PROVISION_MANAGED_DEVICE";
261
262    /**
263     * Activity action: launch when user provisioning completed, i.e.
264     * {@link #getUserProvisioningState()} returns one of the complete state.
265     *
266     * <p> Please note that the API behavior is not necessarily consistent across various releases,
267     * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
268     * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
269     *
270     * <p> The activity must be protected by permission
271     * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
272     * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
273     * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
274     * components are not started by this intent.
275     * @hide
276     */
277    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
278    @SystemApi
279    public static final String ACTION_STATE_USER_SETUP_COMPLETE =
280            "android.app.action.STATE_USER_SETUP_COMPLETE";
281
282    /**
283     * Activity action: Starts the provisioning flow which sets up a managed device.
284     *
285     * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
286     * the device. A device owner has full control over the device. The device owner can not be
287     * modified by the user and the only way of resetting the device is via factory reset.
288     *
289     * <p>A typical use case would be a device that is owned by a company, but used by either an
290     * employee or client.
291     *
292     * <p>The provisioning message should be sent to an unprovisioned device.
293     *
294     * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
295     * by a privileged app with the permission
296     * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
297     *
298     * <p>The provisioning intent contains the following properties:
299     * <ul>
300     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
301     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
302     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
303     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
304     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL}, optional</li>
305     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI}, optional</li>
306     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
307     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
308     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
309     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
310     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
311     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
312     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
313     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
314     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
315     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
316     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
317     * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
318     * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
319     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li></ul>
320     *
321     * @hide
322     */
323    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
324    @SystemApi
325    public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
326            "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
327
328    /**
329     * Activity action: Starts the provisioning flow which sets up a managed device.
330     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
331     *
332     * <p>NOTE: This is only supported on split system user devices, and puts the device into a
333     * management state that is distinct from that reached by
334     * {@link #ACTION_PROVISION_MANAGED_DEVICE} - specifically the device owner runs on the system
335     * user, and only has control over device-wide policies, not individual users and their data.
336     * The primary benefit is that multiple non-system users are supported when provisioning using
337     * this form of device management.
338     *
339     * <p>During device owner provisioning a device admin app is set as the owner of the device.
340     * A device owner has full control over the device. The device owner can not be modified by the
341     * user.
342     *
343     * <p>A typical use case would be a device that is owned by a company, but used by either an
344     * employee or client.
345     *
346     * <p>An intent with this action can be sent only on an unprovisioned device.
347     * It is possible to check if provisioning is allowed or not by querying the method
348     * {@link #isProvisioningAllowed(String)}.
349     *
350     * <p>The intent contains the following extras:
351     * <ul>
352     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
353     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
354     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
355     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
356     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
357     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
358     * </ul>
359     *
360     * <p>When device owner provisioning has completed, an intent of the type
361     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
362     * device owner.
363     *
364     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
365     * completed, along with the above broadcast, activity intent
366     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
367     *
368     * <p>If provisioning fails, the device is factory reset.
369     *
370     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
371     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
372     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
373     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
374     *
375     * @hide
376     */
377    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
378    public static final String ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE
379        = "android.app.action.PROVISION_MANAGED_SHAREABLE_DEVICE";
380
381    /**
382     * Activity action: Finalizes management provisioning, should be used after user-setup
383     * has been completed and {@link #getUserProvisioningState()} returns one of:
384     * <ul>
385     * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
386     * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
387     * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
388     * </ul>
389     *
390     * @hide
391     */
392    @SystemApi
393    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
394    public static final String ACTION_PROVISION_FINALIZATION
395            = "android.app.action.PROVISION_FINALIZATION";
396
397    /**
398     * Action: Bugreport sharing with device owner has been accepted by the user.
399     *
400     * @hide
401     */
402    public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
403            "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
404
405    /**
406     * Action: Bugreport sharing with device owner has been declined by the user.
407     *
408     * @hide
409     */
410    public static final String ACTION_BUGREPORT_SHARING_DECLINED =
411            "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
412
413    /**
414     * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
415     *
416     * @hide
417     */
418    public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
419            "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
420
421    /**
422     * Extra for shared bugreport's SHA-256 hash.
423     *
424     * @hide
425     */
426    public static final String EXTRA_REMOTE_BUGREPORT_HASH =
427            "android.intent.extra.REMOTE_BUGREPORT_HASH";
428
429    /**
430     * Extra for remote bugreport notification shown type.
431     *
432     * @hide
433     */
434    public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
435            "android.app.extra.bugreport_notification_type";
436
437    /**
438     * Notification type for a started remote bugreport flow.
439     *
440     * @hide
441     */
442    public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
443
444    /**
445     * Notification type for a bugreport that has already been accepted to be shared, but is still
446     * being taken.
447     *
448     * @hide
449     */
450    public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
451
452    /**
453     * Notification type for a bugreport that has been taken and can be shared or declined.
454     *
455     * @hide
456     */
457    public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
458
459    /**
460     * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
461     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
462     *
463     * @hide
464     */
465    public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
466
467    /**
468     * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
469     * allows a mobile device management application or NFC programmer application which starts
470     * managed provisioning to pass data to the management application instance after provisioning.
471     * <p>
472     * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
473     * sends the intent to pass data to itself on the newly created profile.
474     * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
475     * instance of the app on the primary user.
476     * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
477     * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
478     * message should contain a stringified {@link java.util.Properties} instance, whose string
479     * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
480     * management application after provisioning.
481     *
482     * <p>
483     * In both cases the application receives the data in
484     * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
485     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
486     * during the managed provisioning.
487     */
488    public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
489            "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
490
491    /**
492     * A String extra holding the package name of the mobile device management application that
493     * will be set as the profile owner or device owner.
494     *
495     * <p>If an application starts provisioning directly via an intent with action
496     * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
497     * application that started provisioning. The package will be set as profile owner in that case.
498     *
499     * <p>This package is set as device owner when device owner provisioning is started by an NFC
500     * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
501     *
502     * <p> When this extra is set, the application must have exactly one device admin receiver.
503     * This receiver will be set as the profile or device owner and active admin.
504     *
505     * @see DeviceAdminReceiver
506     * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
507     * supported, but only if there is only one device admin receiver in the package that requires
508     * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
509     */
510    @Deprecated
511    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
512        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
513
514    /**
515     * A ComponentName extra indicating the device admin receiver of the mobile device management
516     * application that will be set as the profile owner or device owner and active admin.
517     *
518     * <p>If an application starts provisioning directly via an intent with action
519     * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
520     * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
521     * component has to match the package name of the application that started provisioning.
522     *
523     * <p>This component is set as device owner and active admin when device owner provisioning is
524     * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
525     * message containing an NFC record with MIME type
526     * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
527     * flattened to a string, via {@link ComponentName#flattenToShortString()}.
528     *
529     * @see DeviceAdminReceiver
530     */
531    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
532        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
533
534    /**
535     * An {@link android.accounts.Account} extra holding the account to migrate during managed
536     * profile provisioning. If the account supplied is present in the primary user, it will be
537     * copied, along with its credentials to the managed profile and removed from the primary user.
538     *
539     * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}.
540     */
541
542    public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
543        = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
544
545    /**
546     * Boolean extra to indicate that the migrated account should be kept. This is used in
547     * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
548     * the account will not be removed from the primary user after it is migrated to the newly
549     * created user or profile.
550     *
551     * <p> Defaults to {@code false}
552     *
553     * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
554     * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}
555     */
556    public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
557            = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
558
559    /**
560     * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
561     * device.
562     */
563    @Deprecated
564    public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
565        = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
566
567    /**
568     * A integer extra indicating the predominant color to show during the provisioning.
569     * Refer to {@link android.graphics.Color} for how the color is represented.
570     *
571     * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
572     * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
573     */
574    public static final String EXTRA_PROVISIONING_MAIN_COLOR =
575             "android.app.extra.PROVISIONING_MAIN_COLOR";
576
577    /**
578     * A Boolean extra that can be used by the mobile device management application to skip the
579     * disabling of system apps during provisioning when set to {@code true}.
580     *
581     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
582     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
583     */
584    public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
585            "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
586
587    /**
588     * A String extra holding the time zone {@link android.app.AlarmManager} that the device
589     * will be set to.
590     *
591     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
592     * provisioning via an NFC bump.
593     */
594    public static final String EXTRA_PROVISIONING_TIME_ZONE
595        = "android.app.extra.PROVISIONING_TIME_ZONE";
596
597    /**
598     * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
599     * {@link android.app.AlarmManager}.
600     *
601     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
602     * provisioning via an NFC bump.
603     */
604    public static final String EXTRA_PROVISIONING_LOCAL_TIME
605        = "android.app.extra.PROVISIONING_LOCAL_TIME";
606
607    /**
608     * A String extra holding the {@link java.util.Locale} that the device will be set to.
609     * Format: xx_yy, where xx is the language code, and yy the country code.
610     *
611     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
612     * provisioning via an NFC bump.
613     */
614    public static final String EXTRA_PROVISIONING_LOCALE
615        = "android.app.extra.PROVISIONING_LOCALE";
616
617    /**
618     * A String extra holding the ssid of the wifi network that should be used during nfc device
619     * owner provisioning for downloading the mobile device management application.
620     *
621     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
622     * provisioning via an NFC bump.
623     */
624    public static final String EXTRA_PROVISIONING_WIFI_SSID
625        = "android.app.extra.PROVISIONING_WIFI_SSID";
626
627    /**
628     * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
629     * is hidden or not.
630     *
631     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
632     * provisioning via an NFC bump.
633     */
634    public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
635        = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
636
637    /**
638     * A String extra indicating the security type of the wifi network in
639     * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA} or
640     * {@code WEP}.
641     *
642     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
643     * provisioning via an NFC bump.
644     */
645    public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
646        = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
647
648    /**
649     * A String extra holding the password of the wifi network in
650     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
651     *
652     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
653     * provisioning via an NFC bump.
654     */
655    public static final String EXTRA_PROVISIONING_WIFI_PASSWORD
656        = "android.app.extra.PROVISIONING_WIFI_PASSWORD";
657
658    /**
659     * A String extra holding the proxy host for the wifi network in
660     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
661     *
662     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
663     * provisioning via an NFC bump.
664     */
665    public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
666        = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
667
668    /**
669     * An int extra holding the proxy port for the wifi network in
670     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
671     *
672     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
673     * provisioning via an NFC bump.
674     */
675    public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
676        = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
677
678    /**
679     * A String extra holding the proxy bypass for the wifi network in
680     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
681     *
682     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
683     * provisioning via an NFC bump.
684     */
685    public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
686        = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
687
688    /**
689     * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
690     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
691     *
692     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
693     * provisioning via an NFC bump.
694     */
695    public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
696        = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
697
698    /**
699     * A String extra holding a url that specifies the download location of the device admin
700     * package. When not provided it is assumed that the device admin package is already installed.
701     *
702     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
703     * provisioning via an NFC bump.
704     */
705    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
706        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
707
708    /**
709     * A String extra holding the localized name of the organization under management.
710     *
711     * The name is displayed only during provisioning.
712     *
713     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
714     *
715     * @hide
716     */
717    @SystemApi
718    public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
719            "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
720
721    /**
722     * A String extra holding a url to the website of the device provider so the user can open it
723     * during provisioning. If the url is not HTTPS, an error will be shown.
724     *
725     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
726     *
727     * @hide
728     */
729    @SystemApi
730    public static final String EXTRA_PROVISIONING_SUPPORT_URL =
731            "android.app.extra.PROVISIONING_SUPPORT_URL";
732
733    /**
734     * A String extra holding the localized name of the device admin package. It should be the same
735     * as the app label of the package.
736     *
737     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
738     *
739     * @hide
740     */
741    @SystemApi
742    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
743            "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
744
745    /**
746     * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
747     * shown during the provisioning.
748     * <h5>The following URI schemes are accepted:</h5>
749     * <ul>
750     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
751     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
752     * </ul>
753     *
754     * <p> It is the responsibility of the caller to provide an image with a reasonable
755     * pixel density for the device.
756     *
757     * <p> If a content: URI is passed, the intent should have the flag
758     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
759     * {@link android.content.ClipData} of the intent too.
760     *
761     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
762     *
763     * @hide
764     */
765    @SystemApi
766    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
767            "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
768
769    /**
770     * An int extra holding a minimum required version code for the device admin package. If the
771     * device admin is already installed on the device, it will only be re-downloaded from
772     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
773     * installed package is less than this version code.
774     *
775     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
776     * provisioning via an NFC bump.
777     */
778    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
779        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
780
781    /**
782     * A String extra holding a http cookie header which should be used in the http request to the
783     * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
784     *
785     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
786     * provisioning via an NFC bump.
787     */
788    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
789        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
790
791    /**
792     * A String extra holding the URL-safe base64 encoded SHA-256 or SHA-1 hash (see notes below) of
793     * the file at download location specified in
794     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
795     *
796     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
797     * present. The provided checksum must match the checksum of the file at the download
798     * location. If the checksum doesn't match an error will be shown to the user and the user will
799     * be asked to factory reset the device.
800     *
801     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
802     * provisioning via an NFC bump.
803     *
804     * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
805     * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
806     * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
807     * addition to SHA-1. Support for SHA-1 is likely to be removed in future OS releases.
808     */
809    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
810        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
811
812    /**
813     * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
814     * android package archive at the download location specified in {@link
815     * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
816     *
817     * <p>The signatures of an android package archive can be obtained using
818     * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
819     * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
820     *
821     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
822     * present. The provided checksum must match the checksum of any signature of the file at
823     * the download location. If the checksum does not match an error will be shown to the user and
824     * the user will be asked to factory reset the device.
825     *
826     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
827     * provisioning via an NFC bump.
828     */
829    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
830        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
831
832    /**
833     * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
834     * has completed successfully.
835     *
836     * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
837     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
838     *
839     * <p>This intent will contain the following extras
840     * <ul>
841     * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
842     * profile.</li>
843     * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
844     * be migrated at provisioning time, if any.</li>
845     * </ul>
846     */
847    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
848    public static final String ACTION_MANAGED_PROFILE_PROVISIONED
849        = "android.app.action.MANAGED_PROFILE_PROVISIONED";
850
851    /**
852     * Activity action: This activity action is sent to indicate that provisioning of a managed
853     * profile or managed device has completed successfully. It'll be sent at the same time as
854     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
855     * delivered faster as it's an activity intent.
856     *
857     * <p>The intent is only sent to the application on the profile that requested provisioning. In
858     * the device owner case the profile is the primary user.
859     *
860     * @see #ACTION_PROVISION_MANAGED_PROFILE
861     * @see #ACTION_PROVISION_MANAGED_DEVICE
862     */
863    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
864    public static final String ACTION_PROVISIONING_SUCCESSFUL =
865            "android.app.action.PROVISIONING_SUCCESSFUL";
866
867    /**
868     * A boolean extra indicating whether device encryption can be skipped as part of device owner
869     * or managed profile provisioning.
870     *
871     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
872     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
873     *
874     * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
875     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
876     */
877    public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
878             "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
879
880    /**
881     * A {@link Uri} extra pointing to a logo image. This image will be shown during the
882     * provisioning. If this extra is not passed, a default image will be shown.
883     * <h5>The following URI schemes are accepted:</h5>
884     * <ul>
885     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
886     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
887     * </ul>
888     *
889     * <p> It is the responsibility of the caller to provide an image with a reasonable
890     * pixel density for the device.
891     *
892     * <p> If a content: URI is passed, the intent should have the flag
893     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
894     * {@link android.content.ClipData} of the intent too.
895     *
896     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
897     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
898     */
899    public static final String EXTRA_PROVISIONING_LOGO_URI =
900            "android.app.extra.PROVISIONING_LOGO_URI";
901
902    /**
903     * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
904     * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
905     * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
906     * content.
907     *
908     * <p> The extra typically contains one disclaimer from the company of mobile device
909     * management application (MDM), and one disclaimer from the organization.
910     *
911     * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
912     *
913     * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
914     *
915     * <p> Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
916     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
917     */
918    public static final String EXTRA_PROVISIONING_DISCLAIMERS =
919            "android.app.extra.PROVISIONING_DISCLAIMERS";
920
921    /**
922     * A String extra of localized disclaimer header.
923     *
924     * <p> The extra is typically the company name of mobile device management application (MDM)
925     * or the organization name.
926     *
927     * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
928     *
929     * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
930     * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
931     * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
932     *
933     * <pre>
934     *  &lt;meta-data
935     *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
936     *      android:resource="@string/disclaimer_header"
937     * /&gt;</pre>
938     */
939    public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
940            "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
941
942    /**
943     * A {@link Uri} extra pointing to disclaimer content.
944     *
945     * <h5>The following URI schemes are accepted:</h5>
946     * <ul>
947     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
948     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
949     * </ul>
950     *
951     * <p> Styled text is supported in the disclaimer content. The content is parsed by
952     * {@link android.text.Html#fromHtml(String)} and displayed in a
953     * {@link android.widget.TextView}.
954     *
955     * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
956     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
957     * {@link android.content.ClipData} of the intent too.
958     *
959     * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
960     *
961     * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
962     * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
963     * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
964     *
965     * <pre>
966     *  &lt;meta-data
967     *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
968     *      android:resource="@string/disclaimer_content"
969     * /&gt;</pre>
970     */
971    public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
972            "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
973
974    /**
975     * A boolean extra indicating if user setup should be skipped, for when provisioning is started
976     * during setup-wizard.
977     *
978     * <p>If unspecified, defaults to {@code true} to match the behavior in
979     * {@link android.os.Build.VERSION_CODES#M} and earlier.
980     *
981     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or
982     * {@link #ACTION_PROVISION_MANAGED_USER}.
983     *
984     * @hide
985     */
986    public static final String EXTRA_PROVISIONING_SKIP_USER_SETUP =
987            "android.app.extra.PROVISIONING_SKIP_USER_SETUP";
988
989    /**
990     * A boolean extra indicating if the user consent steps from the provisioning flow should be
991     * skipped. If unspecified, defaults to {@code false}.
992     *
993     * It can only be used by an existing device owner trying to create a managed profile via
994     * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
995     */
996    public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
997            "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
998
999    /**
1000     * This MIME type is used for starting the device owner provisioning.
1001     *
1002     * <p>During device owner provisioning a device admin app is set as the owner of the device.
1003     * A device owner has full control over the device. The device owner can not be modified by the
1004     * user and the only way of resetting the device is if the device owner app calls a factory
1005     * reset.
1006     *
1007     * <p> A typical use case would be a device that is owned by a company, but used by either an
1008     * employee or client.
1009     *
1010     * <p> The NFC message must be sent to an unprovisioned device.
1011     *
1012     * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1013     * contains the following properties:
1014     * <ul>
1015     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1016     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1017     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1018     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1019     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1020     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1021     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1022     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1023     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1024     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1025     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1026     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1027     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1028     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1029     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1030     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from
1031     * {@link android.os.Build.VERSION_CODES#M} </li></ul>
1032     *
1033     * <p>
1034     * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1035     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1036     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1037     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1038     */
1039    public static final String MIME_TYPE_PROVISIONING_NFC
1040        = "application/com.android.managedprovisioning";
1041
1042    /**
1043     * Activity action: ask the user to add a new device administrator to the system.
1044     * The desired policy is the ComponentName of the policy in the
1045     * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
1046     * bring the user through adding the device administrator to the system (or
1047     * allowing them to reject it).
1048     *
1049     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1050     * field to provide the user with additional explanation (in addition
1051     * to your component's description) about what is being added.
1052     *
1053     * <p>If your administrator is already active, this will ordinarily return immediately (without
1054     * user intervention).  However, if your administrator has been updated and is requesting
1055     * additional uses-policy flags, the user will be presented with the new list.  New policies
1056     * will not be available to the updated administrator until the user has accepted the new list.
1057     */
1058    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1059    public static final String ACTION_ADD_DEVICE_ADMIN
1060            = "android.app.action.ADD_DEVICE_ADMIN";
1061
1062    /**
1063     * @hide
1064     * Activity action: ask the user to add a new device administrator as the profile owner
1065     * for this user. Only system apps can launch this intent.
1066     *
1067     * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
1068     * extra field. This will invoke a UI to bring the user through adding the profile owner admin
1069     * to remotely control restrictions on the user.
1070     *
1071     * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
1072     * result of whether or not the user approved the action. If approved, the result will
1073     * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
1074     * as a profile owner.
1075     *
1076     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1077     * field to provide the user with additional explanation (in addition
1078     * to your component's description) about what is being added.
1079     *
1080     * <p>If there is already a profile owner active or the caller is not a system app, the
1081     * operation will return a failure result.
1082     */
1083    @SystemApi
1084    public static final String ACTION_SET_PROFILE_OWNER
1085            = "android.app.action.SET_PROFILE_OWNER";
1086
1087    /**
1088     * @hide
1089     * Name of the profile owner admin that controls the user.
1090     */
1091    @SystemApi
1092    public static final String EXTRA_PROFILE_OWNER_NAME
1093            = "android.app.extra.PROFILE_OWNER_NAME";
1094
1095    /**
1096     * Broadcast action: send when any policy admin changes a policy.
1097     * This is generally used to find out when a new policy is in effect.
1098     *
1099     * @hide
1100     */
1101    public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1102            = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
1103
1104    /**
1105     * Broadcast action: sent when the device owner is set, changed or cleared.
1106     *
1107     * This broadcast is sent only to the primary user.
1108     * @see #ACTION_PROVISION_MANAGED_DEVICE
1109     */
1110    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1111    public static final String ACTION_DEVICE_OWNER_CHANGED
1112            = "android.app.action.DEVICE_OWNER_CHANGED";
1113
1114    /**
1115     * The ComponentName of the administrator component.
1116     *
1117     * @see #ACTION_ADD_DEVICE_ADMIN
1118     */
1119    public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
1120
1121    /**
1122     * An optional CharSequence providing additional explanation for why the
1123     * admin is being added.
1124     *
1125     * @see #ACTION_ADD_DEVICE_ADMIN
1126     */
1127    public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
1128
1129    /**
1130     * Constant to indicate the feature of disabling the camera. Used as argument to
1131     * {@link #createAdminSupportIntent(String)}.
1132     * @see #setCameraDisabled(ComponentName, boolean)
1133     */
1134    public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
1135
1136    /**
1137     * Constant to indicate the feature of disabling screen captures. Used as argument to
1138     * {@link #createAdminSupportIntent(String)}.
1139     * @see #setScreenCaptureDisabled(ComponentName, boolean)
1140     */
1141    public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
1142
1143    /**
1144     * A String indicating a specific restricted feature. Can be a user restriction from the
1145     * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1146     * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
1147     * @see #createAdminSupportIntent(String)
1148     * @hide
1149     */
1150    @TestApi
1151    public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1152
1153    /**
1154     * Activity action: have the user enter a new password. This activity should
1155     * be launched after using {@link #setPasswordQuality(ComponentName, int)},
1156     * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
1157     * enter a new password that meets the current requirements. You can use
1158     * {@link #isActivePasswordSufficient()} to determine whether you need to
1159     * have the user select a new password in order to meet the current
1160     * constraints. Upon being resumed from this activity, you can check the new
1161     * password characteristics to see if they are sufficient.
1162     *
1163     * If the intent is launched from within a managed profile with a profile
1164     * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1165     * this will trigger entering a new password for the parent of the profile.
1166     * For all other cases it will trigger entering a new password for the user
1167     * or profile it is launched from.
1168     *
1169     * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1170     */
1171    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1172    public static final String ACTION_SET_NEW_PASSWORD
1173            = "android.app.action.SET_NEW_PASSWORD";
1174
1175    /**
1176     * Activity action: have the user enter a new password for the parent profile.
1177     * If the intent is launched from within a managed profile, this will trigger
1178     * entering a new password for the parent of the profile. In all other cases
1179     * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
1180     */
1181    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1182    public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1183            = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1184
1185    /**
1186     * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1187     * Network logging was enabled and the user tapped the notification.
1188     * <p class="note">This is a protected intent that can only be sent by the system.</p>
1189     * @hide
1190     */
1191    public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1192            = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1193
1194    /**
1195     * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1196     * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1197     * {@link #EXTRA_DELEGATION_SCOPES} key.
1198     *
1199     * <p class=”note”> Note: This is a protected intent that can only be sent by the system.</p>
1200     */
1201    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1202    public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1203            "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1204
1205    /**
1206     * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1207     * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1208     */
1209    public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1210
1211    /**
1212     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1213     * the parent profile to access intents sent from the managed profile.
1214     * That is, when an app in the managed profile calls
1215     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1216     * matching activity in the parent profile.
1217     */
1218    public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1219
1220    /**
1221     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1222     * the managed profile to access intents sent from the parent profile.
1223     * That is, when an app in the parent profile calls
1224     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1225     * matching activity in the managed profile.
1226     */
1227    public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1228
1229    /**
1230     * Broadcast action: notify that a new local system update policy has been set by the device
1231     * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1232     */
1233    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1234    public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1235            = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1236
1237    /**
1238     * Permission policy to prompt user for new permission requests for runtime permissions.
1239     * Already granted or denied permissions are not affected by this.
1240     */
1241    public static final int PERMISSION_POLICY_PROMPT = 0;
1242
1243    /**
1244     * Permission policy to always grant new permission requests for runtime permissions.
1245     * Already granted or denied permissions are not affected by this.
1246     */
1247    public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1248
1249    /**
1250     * Permission policy to always deny new permission requests for runtime permissions.
1251     * Already granted or denied permissions are not affected by this.
1252     */
1253    public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1254
1255    /**
1256     * Runtime permission state: The user can manage the permission
1257     * through the UI.
1258     */
1259    public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1260
1261    /**
1262     * Runtime permission state: The permission is granted to the app
1263     * and the user cannot manage the permission through the UI.
1264     */
1265    public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1266
1267    /**
1268     * Runtime permission state: The permission is denied to the app
1269     * and the user cannot manage the permission through the UI.
1270     */
1271    public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1272
1273    /**
1274     * Delegation of certificate installation and management. This scope grants access to the
1275     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1276     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1277     */
1278    public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1279
1280    /**
1281     * Delegation of application restrictions management. This scope grants access to the
1282     * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1283     */
1284    public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1285
1286    /**
1287     * Delegation of application uninstall block. This scope grants access to the
1288     * {@link #setUninstallBlocked} API.
1289     */
1290    public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1291
1292    /**
1293     * Delegation of permission policy and permission grant state. This scope grants access to the
1294     * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1295     * and {@link #setPermissionGrantState} APIs.
1296     */
1297    public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1298
1299    /**
1300     * Delegation of package access state. This scope grants access to the
1301     * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1302     * {@link #setPackagesSuspended} APIs.
1303     */
1304    public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1305
1306    /**
1307     * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1308     * API.
1309     */
1310    public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1311
1312    /**
1313     * Delegation of management of uninstalled packages. This scope grants access to the
1314     * {@code #setKeepUninstalledPackages} and {@code #getKeepUninstalledPackages} APIs.
1315     * @hide
1316     */
1317    public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1318            "delegation-keep-uninstalled-packages";
1319
1320    /**
1321     * No management for current user in-effect. This is the default.
1322     * @hide
1323     */
1324    @SystemApi
1325    public static final int STATE_USER_UNMANAGED = 0;
1326
1327    /**
1328     * Management partially setup, user setup needs to be completed.
1329     * @hide
1330     */
1331    @SystemApi
1332    public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1333
1334    /**
1335     * Management partially setup, user setup completed.
1336     * @hide
1337     */
1338    @SystemApi
1339    public static final int STATE_USER_SETUP_COMPLETE = 2;
1340
1341    /**
1342     * Management setup and active on current user.
1343     * @hide
1344     */
1345    @SystemApi
1346    public static final int STATE_USER_SETUP_FINALIZED = 3;
1347
1348    /**
1349     * Management partially setup on a managed profile.
1350     * @hide
1351     */
1352    @SystemApi
1353    public static final int STATE_USER_PROFILE_COMPLETE = 4;
1354
1355    /**
1356     * @hide
1357     */
1358    @IntDef({STATE_USER_UNMANAGED, STATE_USER_SETUP_INCOMPLETE, STATE_USER_SETUP_COMPLETE,
1359            STATE_USER_SETUP_FINALIZED, STATE_USER_PROFILE_COMPLETE})
1360    @Retention(RetentionPolicy.SOURCE)
1361    public @interface UserProvisioningState {}
1362
1363    /**
1364     * Result code for {@link #checkProvisioningPreCondition}.
1365     *
1366     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1367     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1368     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when provisioning is allowed.
1369     *
1370     * @hide
1371     */
1372    public static final int CODE_OK = 0;
1373
1374    /**
1375     * Result code for {@link #checkProvisioningPreCondition}.
1376     *
1377     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1378     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the device already has a device
1379     * owner.
1380     *
1381     * @hide
1382     */
1383    public static final int CODE_HAS_DEVICE_OWNER = 1;
1384
1385    /**
1386     * Result code for {@link #checkProvisioningPreCondition}.
1387     *
1388     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1389     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user has a profile owner and for
1390     * {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
1391     *
1392     * @hide
1393     */
1394    public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
1395
1396    /**
1397     * Result code for {@link #checkProvisioningPreCondition}.
1398     *
1399     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1400     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user isn't running.
1401     *
1402     * @hide
1403     */
1404    public static final int CODE_USER_NOT_RUNNING = 3;
1405
1406    /**
1407     * Result code for {@link #checkProvisioningPreCondition}.
1408     *
1409     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1410     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the device has already been setup and
1411     * for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
1412     *
1413     * @hide
1414     */
1415    public static final int CODE_USER_SETUP_COMPLETED = 4;
1416
1417    /**
1418     * Code used to indicate that the device also has a user other than the system user.
1419     *
1420     * @hide
1421     */
1422    public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
1423
1424    /**
1425     * Code used to indicate that device has an account that prevents provisioning.
1426     *
1427     * @hide
1428     */
1429    public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
1430
1431    /**
1432     * Result code for {@link #checkProvisioningPreCondition}.
1433     *
1434     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1435     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the user is not a system user.
1436     *
1437     * @hide
1438     */
1439    public static final int CODE_NOT_SYSTEM_USER = 7;
1440
1441    /**
1442     * Result code for {@link #checkProvisioningPreCondition}.
1443     *
1444     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1445     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} and {@link #ACTION_PROVISION_MANAGED_USER}
1446     * when the device is a watch and is already paired.
1447     *
1448     * @hide
1449     */
1450    public static final int CODE_HAS_PAIRED = 8;
1451
1452    /**
1453     * Result code for {@link #checkProvisioningPreCondition}.
1454     *
1455     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
1456     * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
1457     *
1458     * @see {@link PackageManager#FEATURE_MANAGED_USERS}
1459     * @hide
1460     */
1461    public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
1462
1463    /**
1464     * Result code for {@link #checkProvisioningPreCondition}.
1465     *
1466     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user.
1467     *
1468     * @hide
1469     */
1470    public static final int CODE_SYSTEM_USER = 10;
1471
1472    /**
1473     * Result code for {@link #checkProvisioningPreCondition}.
1474     *
1475     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
1476     * managed profiles.
1477     *
1478     * @hide
1479     */
1480    public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
1481
1482    /**
1483     * Result code for {@link #checkProvisioningPreCondition}.
1484     *
1485     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} and
1486     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices not running with split system
1487     * user.
1488     *
1489     * @hide
1490     */
1491    public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
1492
1493    /**
1494     * Result code for {@link #checkProvisioningPreCondition}.
1495     *
1496     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1497     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1498     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices which do no support device
1499     * admins.
1500     *
1501     * @hide
1502     */
1503    public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
1504
1505    /**
1506     * Result code for {@link #checkProvisioningPreCondition}.
1507     *
1508     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the device the user is a
1509     * system user on a split system user device.
1510     *
1511     * @hide
1512     */
1513    public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
1514
1515    /**
1516     * Result code for {@link #checkProvisioningPreCondition}.
1517     *
1518     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when adding a managed profile is
1519     * disallowed by {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
1520     *
1521     * @hide
1522     */
1523    public static final int CODE_ADD_MANAGED_PROFILE_DISALLOWED = 15;
1524
1525    /**
1526     * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
1527     * conditions.
1528     *
1529     * @hide
1530     */
1531    @Retention(RetentionPolicy.SOURCE)
1532    @IntDef({CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
1533            CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
1534            CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
1535            CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
1536            CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER, CODE_ADD_MANAGED_PROFILE_DISALLOWED})
1537    public @interface ProvisioningPreCondition {}
1538
1539    /**
1540     * Service action: Action for a service that device owner and profile owner can optionally
1541     * own.  If a device owner or a profile owner has such a service, the system tries to keep
1542     * a bound connection to it, in order to keep their process always running.
1543     * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
1544     * permission.
1545     */
1546    @SdkConstant(SdkConstantType.SERVICE_ACTION)
1547    public static final String ACTION_DEVICE_ADMIN_SERVICE
1548            = "android.app.action.DEVICE_ADMIN_SERVICE";
1549
1550    /**
1551     * Return true if the given administrator component is currently active (enabled) in the system.
1552     *
1553     * @param admin The administrator component to check for.
1554     * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
1555     *         otherwise
1556     */
1557    public boolean isAdminActive(@NonNull ComponentName admin) {
1558        throwIfParentInstance("isAdminActive");
1559        return isAdminActiveAsUser(admin, myUserId());
1560    }
1561
1562    /**
1563     * @see #isAdminActive(ComponentName)
1564     * @hide
1565     */
1566    public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
1567        if (mService != null) {
1568            try {
1569                return mService.isAdminActive(admin, userId);
1570            } catch (RemoteException e) {
1571                throw e.rethrowFromSystemServer();
1572            }
1573        }
1574        return false;
1575    }
1576
1577    /**
1578     * Return true if the given administrator component is currently being removed
1579     * for the user.
1580     * @hide
1581     */
1582    public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
1583        if (mService != null) {
1584            try {
1585                return mService.isRemovingAdmin(admin, userId);
1586            } catch (RemoteException e) {
1587                throw e.rethrowFromSystemServer();
1588            }
1589        }
1590        return false;
1591    }
1592
1593    /**
1594     * Return a list of all currently active device administrators' component
1595     * names.  If there are no administrators {@code null} may be
1596     * returned.
1597     */
1598    public @Nullable List<ComponentName> getActiveAdmins() {
1599        throwIfParentInstance("getActiveAdmins");
1600        return getActiveAdminsAsUser(myUserId());
1601    }
1602
1603    /**
1604     * @see #getActiveAdmins()
1605     * @hide
1606     */
1607    public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
1608        if (mService != null) {
1609            try {
1610                return mService.getActiveAdmins(userId);
1611            } catch (RemoteException e) {
1612                throw e.rethrowFromSystemServer();
1613            }
1614        }
1615        return null;
1616    }
1617
1618    /**
1619     * Used by package administration code to determine if a package can be stopped
1620     * or uninstalled.
1621     * @hide
1622     */
1623    @SystemApi
1624    public boolean packageHasActiveAdmins(String packageName) {
1625        return packageHasActiveAdmins(packageName, myUserId());
1626    }
1627
1628    /**
1629     * Used by package administration code to determine if a package can be stopped
1630     * or uninstalled.
1631     * @hide
1632     */
1633    public boolean packageHasActiveAdmins(String packageName, int userId) {
1634        if (mService != null) {
1635            try {
1636                return mService.packageHasActiveAdmins(packageName, userId);
1637            } catch (RemoteException e) {
1638                throw e.rethrowFromSystemServer();
1639            }
1640        }
1641        return false;
1642    }
1643
1644    /**
1645     * Remove a current administration component.  This can only be called
1646     * by the application that owns the administration component; if you
1647     * try to remove someone else's component, a security exception will be
1648     * thrown.
1649     *
1650     * <p>Note that the operation is not synchronous and the admin might still be active (as
1651     * indicated by {@link #getActiveAdmins()}) by the time this method returns.
1652     *
1653     * @param admin The administration compononent to remove.
1654     * @throws SecurityException if the caller is not in the owner application of {@code admin}.
1655     */
1656    public void removeActiveAdmin(@NonNull ComponentName admin) {
1657        throwIfParentInstance("removeActiveAdmin");
1658        if (mService != null) {
1659            try {
1660                mService.removeActiveAdmin(admin, myUserId());
1661            } catch (RemoteException e) {
1662                throw e.rethrowFromSystemServer();
1663            }
1664        }
1665    }
1666
1667    /**
1668     * Returns true if an administrator has been granted a particular device policy. This can be
1669     * used to check whether the administrator was activated under an earlier set of policies, but
1670     * requires additional policies after an upgrade.
1671     *
1672     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
1673     *            active administrator, or an exception will be thrown.
1674     * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
1675     * @throws SecurityException if {@code admin} is not an active administrator.
1676     */
1677    public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
1678        throwIfParentInstance("hasGrantedPolicy");
1679        if (mService != null) {
1680            try {
1681                return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
1682            } catch (RemoteException e) {
1683                throw e.rethrowFromSystemServer();
1684            }
1685        }
1686        return false;
1687    }
1688
1689    /**
1690     * Returns true if the Profile Challenge is available to use for the given profile user.
1691     *
1692     * @hide
1693     */
1694    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
1695        if (mService != null) {
1696            try {
1697                return mService.isSeparateProfileChallengeAllowed(userHandle);
1698            } catch (RemoteException e) {
1699                throw e.rethrowFromSystemServer();
1700            }
1701        }
1702        return false;
1703    }
1704
1705    /**
1706     * Constant for {@link #setPasswordQuality}: the policy has no requirements
1707     * for the password.  Note that quality constants are ordered so that higher
1708     * values are more restrictive.
1709     */
1710    public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
1711
1712    /**
1713     * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
1714     * recognition technology.  This implies technologies that can recognize the identity of
1715     * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
1716     * Note that quality constants are ordered so that higher values are more restrictive.
1717     */
1718    public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
1719
1720    /**
1721     * Constant for {@link #setPasswordQuality}: the policy requires some kind
1722     * of password or pattern, but doesn't care what it is. Note that quality constants
1723     * are ordered so that higher values are more restrictive.
1724     */
1725    public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
1726
1727    /**
1728     * Constant for {@link #setPasswordQuality}: the user must have entered a
1729     * password containing at least numeric characters.  Note that quality
1730     * constants are ordered so that higher values are more restrictive.
1731     */
1732    public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
1733
1734    /**
1735     * Constant for {@link #setPasswordQuality}: the user must have entered a
1736     * password containing at least numeric characters with no repeating (4444)
1737     * or ordered (1234, 4321, 2468) sequences.  Note that quality
1738     * constants are ordered so that higher values are more restrictive.
1739     */
1740    public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
1741
1742    /**
1743     * Constant for {@link #setPasswordQuality}: the user must have entered a
1744     * password containing at least alphabetic (or other symbol) characters.
1745     * Note that quality constants are ordered so that higher values are more
1746     * restrictive.
1747     */
1748    public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
1749
1750    /**
1751     * Constant for {@link #setPasswordQuality}: the user must have entered a
1752     * password containing at least <em>both></em> numeric <em>and</em>
1753     * alphabetic (or other symbol) characters.  Note that quality constants are
1754     * ordered so that higher values are more restrictive.
1755     */
1756    public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
1757
1758    /**
1759     * Constant for {@link #setPasswordQuality}: the user must have entered a
1760     * password containing at least a letter, a numerical digit and a special
1761     * symbol, by default. With this password quality, passwords can be
1762     * restricted to contain various sets of characters, like at least an
1763     * uppercase letter, etc. These are specified using various methods,
1764     * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
1765     * that quality constants are ordered so that higher values are more
1766     * restrictive.
1767     */
1768    public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
1769
1770    /**
1771     * Constant for {@link #setPasswordQuality}: the user is not allowed to
1772     * modify password. In case this password quality is set, the password is
1773     * managed by a profile owner. The profile owner can set any password,
1774     * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
1775     * that quality constants are ordered so that higher values are more
1776     * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
1777     * the highest.
1778     * @hide
1779     */
1780    public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
1781
1782    /**
1783     * @hide
1784     *
1785     * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
1786     * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
1787     * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
1788     * used by authenticator to exempt their accounts from this:
1789     *
1790     * <ul>
1791     *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
1792     *     <p>In order to make an apk test-only, add android:testOnly="true" to the
1793     *     &lt;application&gt; tag in the manifest.
1794     *
1795     *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
1796     *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
1797     *     Some authenticators claim to have any features, so to detect it, we also check
1798     *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
1799     *     if any of the accounts have it.
1800     * </ul>
1801     */
1802    @SystemApi
1803    @TestApi
1804    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
1805            "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
1806
1807    /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
1808    @SystemApi
1809    @TestApi
1810    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
1811            "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
1812
1813    /**
1814     * Called by an application that is administering the device to set the password restrictions it
1815     * is imposing. After setting this, the user will not be able to enter a new password that is
1816     * not at least as restrictive as what has been set. Note that the current password will remain
1817     * until the user has set a new one, so the change does not take place immediately. To prompt
1818     * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
1819     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
1820     * <p>
1821     * Quality constants are ordered so that higher values are more restrictive; thus the highest
1822     * requested quality constant (between the policy set here, the user's preference, and any other
1823     * considerations) is the one that is in effect.
1824     * <p>
1825     * The calling device admin must have requested
1826     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1827     * not, a security exception will be thrown.
1828     * <p>
1829     * This method can be called on the {@link DevicePolicyManager} instance returned by
1830     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1831     * profile.
1832     *
1833     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1834     * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
1835     *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
1836     *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
1837     *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
1838     * @throws SecurityException if {@code admin} is not an active administrator or if {@code admin}
1839     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1840     */
1841    public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
1842        if (mService != null) {
1843            try {
1844                mService.setPasswordQuality(admin, quality, mParentInstance);
1845            } catch (RemoteException e) {
1846                throw e.rethrowFromSystemServer();
1847            }
1848        }
1849    }
1850
1851    /**
1852     * Retrieve the current minimum password quality for a particular admin or all admins that set
1853     * restrictions on this user and its participating profiles. Restrictions on profiles that have
1854     * a separate challenge are not taken into account.
1855     *
1856     * <p>This method can be called on the {@link DevicePolicyManager} instance
1857     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1858     * restrictions on the parent profile.
1859     *
1860     * @param admin The name of the admin component to check, or {@code null} to aggregate
1861     * all admins.
1862     */
1863    public int getPasswordQuality(@Nullable ComponentName admin) {
1864        return getPasswordQuality(admin, myUserId());
1865    }
1866
1867    /** @hide per-user version */
1868    public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
1869        if (mService != null) {
1870            try {
1871                return mService.getPasswordQuality(admin, userHandle, mParentInstance);
1872            } catch (RemoteException e) {
1873                throw e.rethrowFromSystemServer();
1874            }
1875        }
1876        return PASSWORD_QUALITY_UNSPECIFIED;
1877    }
1878
1879    /**
1880     * Called by an application that is administering the device to set the minimum allowed password
1881     * length. After setting this, the user will not be able to enter a new password that is not at
1882     * least as restrictive as what has been set. Note that the current password will remain until
1883     * the user has set a new one, so the change does not take place immediately. To prompt the user
1884     * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
1885     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
1886     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
1887     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
1888     * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
1889     * {@link #setPasswordQuality}.
1890     * <p>
1891     * The calling device admin must have requested
1892     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1893     * not, a security exception will be thrown.
1894     * <p>
1895     * This method can be called on the {@link DevicePolicyManager} instance returned by
1896     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1897     * profile.
1898     *
1899     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1900     * @param length The new desired minimum password length. A value of 0 means there is no
1901     *            restriction.
1902     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1903     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1904     */
1905    public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
1906        if (mService != null) {
1907            try {
1908                mService.setPasswordMinimumLength(admin, length, mParentInstance);
1909            } catch (RemoteException e) {
1910                throw e.rethrowFromSystemServer();
1911            }
1912        }
1913    }
1914
1915    /**
1916     * Retrieve the current minimum password length for a particular admin or all admins that set
1917     * restrictions on this user and its participating profiles. Restrictions on profiles that have
1918     * a separate challenge are not taken into account.
1919     *
1920     * <p>This method can be called on the {@link DevicePolicyManager} instance
1921     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1922     * restrictions on the parent profile.
1923     *
1924     * user and its profiles or a particular one.
1925     * @param admin The name of the admin component to check, or {@code null} to aggregate
1926     * all admins.
1927     */
1928    public int getPasswordMinimumLength(@Nullable ComponentName admin) {
1929        return getPasswordMinimumLength(admin, myUserId());
1930    }
1931
1932    /** @hide per-user version */
1933    public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
1934        if (mService != null) {
1935            try {
1936                return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
1937            } catch (RemoteException e) {
1938                throw e.rethrowFromSystemServer();
1939            }
1940        }
1941        return 0;
1942    }
1943
1944    /**
1945     * Called by an application that is administering the device to set the minimum number of upper
1946     * case letters required in the password. After setting this, the user will not be able to enter
1947     * a new password that is not at least as restrictive as what has been set. Note that the
1948     * current password will remain until the user has set a new one, so the change does not take
1949     * place immediately. To prompt the user for a new password, use
1950     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
1951     * setting this value. This constraint is only imposed if the administrator has also requested
1952     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
1953     * <p>
1954     * The calling device admin must have requested
1955     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1956     * not, a security exception will be thrown.
1957     * <p>
1958     * This method can be called on the {@link DevicePolicyManager} instance returned by
1959     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1960     * profile.
1961     *
1962     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1963     * @param length The new desired minimum number of upper case letters required in the password.
1964     *            A value of 0 means there is no restriction.
1965     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1966     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1967     */
1968    public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
1969        if (mService != null) {
1970            try {
1971                mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
1972            } catch (RemoteException e) {
1973                throw e.rethrowFromSystemServer();
1974            }
1975        }
1976    }
1977
1978    /**
1979     * Retrieve the current number of upper case letters required in the password
1980     * for a particular admin or all admins that set restrictions on this user and
1981     * its participating profiles. Restrictions on profiles that have a separate challenge
1982     * are not taken into account.
1983     * This is the same value as set by
1984     * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
1985     * and only applies when the password quality is
1986     * {@link #PASSWORD_QUALITY_COMPLEX}.
1987     *
1988     * <p>This method can be called on the {@link DevicePolicyManager} instance
1989     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1990     * restrictions on the parent profile.
1991     *
1992     * @param admin The name of the admin component to check, or {@code null} to
1993     *            aggregate all admins.
1994     * @return The minimum number of upper case letters required in the
1995     *         password.
1996     */
1997    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
1998        return getPasswordMinimumUpperCase(admin, myUserId());
1999    }
2000
2001    /** @hide per-user version */
2002    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
2003        if (mService != null) {
2004            try {
2005                return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
2006            } catch (RemoteException e) {
2007                throw e.rethrowFromSystemServer();
2008            }
2009        }
2010        return 0;
2011    }
2012
2013    /**
2014     * Called by an application that is administering the device to set the minimum number of lower
2015     * case letters required in the password. After setting this, the user will not be able to enter
2016     * a new password that is not at least as restrictive as what has been set. Note that the
2017     * current password will remain until the user has set a new one, so the change does not take
2018     * place immediately. To prompt the user for a new password, use
2019     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2020     * setting this value. This constraint is only imposed if the administrator has also requested
2021     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2022     * <p>
2023     * The calling device admin must have requested
2024     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2025     * not, a security exception will be thrown.
2026     * <p>
2027     * This method can be called on the {@link DevicePolicyManager} instance returned by
2028     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2029     * profile.
2030     *
2031     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2032     * @param length The new desired minimum number of lower case letters required in the password.
2033     *            A value of 0 means there is no restriction.
2034     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2035     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2036     */
2037    public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
2038        if (mService != null) {
2039            try {
2040                mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
2041            } catch (RemoteException e) {
2042                throw e.rethrowFromSystemServer();
2043            }
2044        }
2045    }
2046
2047    /**
2048     * Retrieve the current number of lower case letters required in the password
2049     * for a particular admin or all admins that set restrictions on this user
2050     * and its participating profiles. Restrictions on profiles that have
2051     * a separate challenge are not taken into account.
2052     * This is the same value as set by
2053     * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
2054     * and only applies when the password quality is
2055     * {@link #PASSWORD_QUALITY_COMPLEX}.
2056     *
2057     * <p>This method can be called on the {@link DevicePolicyManager} instance
2058     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2059     * restrictions on the parent profile.
2060     *
2061     * @param admin The name of the admin component to check, or {@code null} to
2062     *            aggregate all admins.
2063     * @return The minimum number of lower case letters required in the
2064     *         password.
2065     */
2066    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
2067        return getPasswordMinimumLowerCase(admin, myUserId());
2068    }
2069
2070    /** @hide per-user version */
2071    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
2072        if (mService != null) {
2073            try {
2074                return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
2075            } catch (RemoteException e) {
2076                throw e.rethrowFromSystemServer();
2077            }
2078        }
2079        return 0;
2080    }
2081
2082    /**
2083     * Called by an application that is administering the device to set the minimum number of
2084     * letters required in the password. After setting this, the user will not be able to enter a
2085     * new password that is not at least as restrictive as what has been set. Note that the current
2086     * password will remain until the user has set a new one, so the change does not take place
2087     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2088     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2089     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2090     * {@link #setPasswordQuality}. The default value is 1.
2091     * <p>
2092     * The calling device admin must have requested
2093     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2094     * not, a security exception will be thrown.
2095     * <p>
2096     * This method can be called on the {@link DevicePolicyManager} instance returned by
2097     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2098     * profile.
2099     *
2100     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2101     * @param length The new desired minimum number of letters required in the password. A value of
2102     *            0 means there is no restriction.
2103     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2104     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2105     */
2106    public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
2107        if (mService != null) {
2108            try {
2109                mService.setPasswordMinimumLetters(admin, length, mParentInstance);
2110            } catch (RemoteException e) {
2111                throw e.rethrowFromSystemServer();
2112            }
2113        }
2114    }
2115
2116    /**
2117     * Retrieve the current number of letters required in the password
2118     * for a particular admin or all admins that set restrictions on this user
2119     * and its participating profiles. Restrictions on profiles that have
2120     * a separate challenge are not taken into account.
2121     * This is the same value as set by
2122     * {@link #setPasswordMinimumLetters(ComponentName, int)}
2123     * and only applies when the password quality is
2124     * {@link #PASSWORD_QUALITY_COMPLEX}.
2125     *
2126     * <p>This method can be called on the {@link DevicePolicyManager} instance
2127     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2128     * restrictions on the parent profile.
2129     *
2130     * @param admin The name of the admin component to check, or {@code null} to
2131     *            aggregate all admins.
2132     * @return The minimum number of letters required in the password.
2133     */
2134    public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
2135        return getPasswordMinimumLetters(admin, myUserId());
2136    }
2137
2138    /** @hide per-user version */
2139    public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
2140        if (mService != null) {
2141            try {
2142                return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
2143            } catch (RemoteException e) {
2144                throw e.rethrowFromSystemServer();
2145            }
2146        }
2147        return 0;
2148    }
2149
2150    /**
2151     * Called by an application that is administering the device to set the minimum number of
2152     * numerical digits required in the password. After setting this, the user will not be able to
2153     * enter a new password that is not at least as restrictive as what has been set. Note that the
2154     * current password will remain until the user has set a new one, so the change does not take
2155     * place immediately. To prompt the user for a new password, use
2156     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2157     * setting this value. This constraint is only imposed if the administrator has also requested
2158     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 1.
2159     * <p>
2160     * The calling device admin must have requested
2161     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2162     * not, a security exception will be thrown.
2163     * <p>
2164     * This method can be called on the {@link DevicePolicyManager} instance returned by
2165     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2166     * profile.
2167     *
2168     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2169     * @param length The new desired minimum number of numerical digits required in the password. A
2170     *            value of 0 means there is no restriction.
2171     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2172     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2173     */
2174    public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
2175        if (mService != null) {
2176            try {
2177                mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
2178            } catch (RemoteException e) {
2179                throw e.rethrowFromSystemServer();
2180            }
2181        }
2182    }
2183
2184    /**
2185     * Retrieve the current number of numerical digits required in the password
2186     * for a particular admin or all admins that set restrictions on this user
2187     * and its participating profiles. Restrictions on profiles that have
2188     * a separate challenge are not taken into account.
2189     * This is the same value as set by
2190     * {@link #setPasswordMinimumNumeric(ComponentName, int)}
2191     * and only applies when the password quality is
2192     * {@link #PASSWORD_QUALITY_COMPLEX}.
2193     *
2194     * <p>This method can be called on the {@link DevicePolicyManager} instance
2195     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2196     * restrictions on the parent profile.
2197     *
2198     * @param admin The name of the admin component to check, or {@code null} to
2199     *            aggregate all admins.
2200     * @return The minimum number of numerical digits required in the password.
2201     */
2202    public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
2203        return getPasswordMinimumNumeric(admin, myUserId());
2204    }
2205
2206    /** @hide per-user version */
2207    public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
2208        if (mService != null) {
2209            try {
2210                return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
2211            } catch (RemoteException e) {
2212                throw e.rethrowFromSystemServer();
2213            }
2214        }
2215        return 0;
2216    }
2217
2218    /**
2219     * Called by an application that is administering the device to set the minimum number of
2220     * symbols required in the password. After setting this, the user will not be able to enter a
2221     * new password that is not at least as restrictive as what has been set. Note that the current
2222     * password will remain until the user has set a new one, so the change does not take place
2223     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2224     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2225     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2226     * {@link #setPasswordQuality}. The default value is 1.
2227     * <p>
2228     * The calling device admin must have requested
2229     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2230     * not, a security exception will be thrown.
2231     * <p>
2232     * This method can be called on the {@link DevicePolicyManager} instance returned by
2233     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2234     * profile.
2235     *
2236     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2237     * @param length The new desired minimum number of symbols required in the password. A value of
2238     *            0 means there is no restriction.
2239     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2240     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2241     */
2242    public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
2243        if (mService != null) {
2244            try {
2245                mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
2246            } catch (RemoteException e) {
2247                throw e.rethrowFromSystemServer();
2248            }
2249        }
2250    }
2251
2252    /**
2253     * Retrieve the current number of symbols required in the password
2254     * for a particular admin or all admins that set restrictions on this user
2255     * and its participating profiles. Restrictions on profiles that have
2256     * a separate challenge are not taken into account. This is the same value as
2257     * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
2258     * and only applies when the password quality is
2259     * {@link #PASSWORD_QUALITY_COMPLEX}.
2260     *
2261     * <p>This method can be called on the {@link DevicePolicyManager} instance
2262     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2263     * restrictions on the parent profile.
2264     *
2265     * @param admin The name of the admin component to check, or {@code null} to
2266     *            aggregate all admins.
2267     * @return The minimum number of symbols required in the password.
2268     */
2269    public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
2270        return getPasswordMinimumSymbols(admin, myUserId());
2271    }
2272
2273    /** @hide per-user version */
2274    public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
2275        if (mService != null) {
2276            try {
2277                return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
2278            } catch (RemoteException e) {
2279                throw e.rethrowFromSystemServer();
2280            }
2281        }
2282        return 0;
2283    }
2284
2285    /**
2286     * Called by an application that is administering the device to set the minimum number of
2287     * non-letter characters (numerical digits or symbols) required in the password. After setting
2288     * this, the user will not be able to enter a new password that is not at least as restrictive
2289     * as what has been set. Note that the current password will remain until the user has set a new
2290     * one, so the change does not take place immediately. To prompt the user for a new password,
2291     * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2292     * setting this value. This constraint is only imposed if the administrator has also requested
2293     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2294     * <p>
2295     * The calling device admin must have requested
2296     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2297     * not, a security exception will be thrown.
2298     * <p>
2299     * This method can be called on the {@link DevicePolicyManager} instance returned by
2300     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2301     * profile.
2302     *
2303     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2304     * @param length The new desired minimum number of letters required in the password. A value of
2305     *            0 means there is no restriction.
2306     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2307     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2308     */
2309    public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
2310        if (mService != null) {
2311            try {
2312                mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
2313            } catch (RemoteException e) {
2314                throw e.rethrowFromSystemServer();
2315            }
2316        }
2317    }
2318
2319    /**
2320     * Retrieve the current number of non-letter characters required in the password
2321     * for a particular admin or all admins that set restrictions on this user
2322     * and its participating profiles. Restrictions on profiles that have
2323     * a separate challenge are not taken into account.
2324     * This is the same value as set by
2325     * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
2326     * and only applies when the password quality is
2327     * {@link #PASSWORD_QUALITY_COMPLEX}.
2328     *
2329     * <p>This method can be called on the {@link DevicePolicyManager} instance
2330     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2331     * restrictions on the parent profile.
2332     *
2333     * @param admin The name of the admin component to check, or {@code null} to
2334     *            aggregate all admins.
2335     * @return The minimum number of letters required in the password.
2336     */
2337    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
2338        return getPasswordMinimumNonLetter(admin, myUserId());
2339    }
2340
2341    /** @hide per-user version */
2342    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
2343        if (mService != null) {
2344            try {
2345                return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
2346            } catch (RemoteException e) {
2347                throw e.rethrowFromSystemServer();
2348            }
2349        }
2350        return 0;
2351    }
2352
2353    /**
2354     * Called by an application that is administering the device to set the length of the password
2355     * history. After setting this, the user will not be able to enter a new password that is the
2356     * same as any password in the history. Note that the current password will remain until the
2357     * user has set a new one, so the change does not take place immediately. To prompt the user for
2358     * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2359     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2360     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2361     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX} {@link #PASSWORD_QUALITY_ALPHABETIC}, or
2362     * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
2363     * <p>
2364     * The calling device admin must have requested
2365     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2366     * not, a security exception will be thrown.
2367     * <p>
2368     * This method can be called on the {@link DevicePolicyManager} instance returned by
2369     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2370     * profile.
2371     *
2372     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2373     * @param length The new desired length of password history. A value of 0 means there is no
2374     *            restriction.
2375     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2376     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2377     */
2378    public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
2379        if (mService != null) {
2380            try {
2381                mService.setPasswordHistoryLength(admin, length, mParentInstance);
2382            } catch (RemoteException e) {
2383                throw e.rethrowFromSystemServer();
2384            }
2385        }
2386    }
2387
2388    /**
2389     * Called by a device admin to set the password expiration timeout. Calling this method will
2390     * restart the countdown for password expiration for the given admin, as will changing the
2391     * device password (for all admins).
2392     * <p>
2393     * The provided timeout is the time delta in ms and will be added to the current time. For
2394     * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
2395     * 432000000 ms for timeout.
2396     * <p>
2397     * To disable password expiration, a value of 0 may be used for timeout.
2398     * <p>
2399     * The calling device admin must have requested
2400     * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
2401     * not, a security exception will be thrown.
2402     * <p>
2403     * Note that setting the password will automatically reset the expiration time for all active
2404     * admins. Active admins do not need to explicitly call this method in that case.
2405     * <p>
2406     * This method can be called on the {@link DevicePolicyManager} instance returned by
2407     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2408     * profile.
2409     *
2410     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2411     * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
2412     *            there is no restriction (unlimited).
2413     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2414     *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
2415     */
2416    public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
2417        if (mService != null) {
2418            try {
2419                mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
2420            } catch (RemoteException e) {
2421                throw e.rethrowFromSystemServer();
2422            }
2423        }
2424    }
2425
2426    /**
2427     * Get the password expiration timeout for the given admin. The expiration timeout is the
2428     * recurring expiration timeout provided in the call to
2429     * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
2430     * aggregate of all participating policy administrators if {@code admin} is null. Admins that
2431     * have set restrictions on profiles that have a separate challenge are not taken into account.
2432     *
2433     * <p>This method can be called on the {@link DevicePolicyManager} instance
2434     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2435     * restrictions on the parent profile.
2436     *
2437     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2438     * @return The timeout for the given admin or the minimum of all timeouts
2439     */
2440    public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
2441        if (mService != null) {
2442            try {
2443                return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
2444            } catch (RemoteException e) {
2445                throw e.rethrowFromSystemServer();
2446            }
2447        }
2448        return 0;
2449    }
2450
2451    /**
2452     * Get the current password expiration time for a particular admin or all admins that set
2453     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2454     * a separate challenge are not taken into account. If admin is {@code null}, then a composite
2455     * of all expiration times is returned - which will be the minimum of all of them.
2456     *
2457     * <p>This method can be called on the {@link DevicePolicyManager} instance
2458     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2459     * the password expiration for the parent profile.
2460     *
2461     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2462     * @return The password expiration time, in milliseconds since epoch.
2463     */
2464    public long getPasswordExpiration(@Nullable ComponentName admin) {
2465        if (mService != null) {
2466            try {
2467                return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
2468            } catch (RemoteException e) {
2469                throw e.rethrowFromSystemServer();
2470            }
2471        }
2472        return 0;
2473    }
2474
2475    /**
2476     * Retrieve the current password history length for a particular admin or all admins that
2477     * set restrictions on this user and its participating profiles. Restrictions on profiles that
2478     * have a separate challenge are not taken into account.
2479     *
2480     * <p>This method can be called on the {@link DevicePolicyManager} instance
2481     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2482     * restrictions on the parent profile.
2483     *
2484     * @param admin The name of the admin component to check, or {@code null} to aggregate
2485     * all admins.
2486     * @return The length of the password history
2487     */
2488    public int getPasswordHistoryLength(@Nullable ComponentName admin) {
2489        return getPasswordHistoryLength(admin, myUserId());
2490    }
2491
2492    /** @hide per-user version */
2493    public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
2494        if (mService != null) {
2495            try {
2496                return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
2497            } catch (RemoteException e) {
2498                throw e.rethrowFromSystemServer();
2499            }
2500        }
2501        return 0;
2502    }
2503
2504    /**
2505     * Return the maximum password length that the device supports for a
2506     * particular password quality.
2507     * @param quality The quality being interrogated.
2508     * @return Returns the maximum length that the user can enter.
2509     */
2510    public int getPasswordMaximumLength(int quality) {
2511        // Kind-of arbitrary.
2512        return 16;
2513    }
2514
2515    /**
2516     * Determine whether the current password the user has set is sufficient to meet the policy
2517     * requirements (e.g. quality, minimum length) that have been requested by the admins of this
2518     * user and its participating profiles. Restrictions on profiles that have a separate challenge
2519     * are not taken into account. The user must be unlocked in order to perform the check.
2520     * <p>
2521     * The calling device admin must have requested
2522     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2523     * not, a security exception will be thrown.
2524     * <p>
2525     * This method can be called on the {@link DevicePolicyManager} instance returned by
2526     * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
2527     * the parent profile is sufficient.
2528     *
2529     * @return Returns true if the password meets the current requirements, else false.
2530     * @throws SecurityException if the calling application does not own an active administrator
2531     *             that uses {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2532     * @throws InvalidStateException if the user is not unlocked.
2533     */
2534    public boolean isActivePasswordSufficient() {
2535        if (mService != null) {
2536            try {
2537                return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
2538            } catch (RemoteException e) {
2539                throw e.rethrowFromSystemServer();
2540            }
2541        }
2542        return false;
2543    }
2544
2545    /**
2546     * Determine whether the current profile password the user has set is sufficient
2547     * to meet the policy requirements (e.g. quality, minimum length) that have been
2548     * requested by the admins of the parent user and its profiles.
2549     *
2550     * @param userHandle the userId of the profile to check the password for.
2551     * @return Returns true if the password would meet the current requirements, else false.
2552     * @throws SecurityException if {@code userHandle} is not a managed profile.
2553     * @hide
2554     */
2555    public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
2556        if (mService != null) {
2557            try {
2558                return mService.isProfileActivePasswordSufficientForParent(userHandle);
2559            } catch (RemoteException e) {
2560                throw e.rethrowFromSystemServer();
2561            }
2562        }
2563        return false;
2564    }
2565
2566    /**
2567     * Retrieve the number of times the user has failed at entering a password since that last
2568     * successful password entry.
2569     * <p>
2570     * This method can be called on the {@link DevicePolicyManager} instance returned by
2571     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
2572     * password attemts for the parent user.
2573     * <p>
2574     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2575     * to be able to call this method; if it has not, a security exception will be thrown.
2576     *
2577     * @return The number of times user has entered an incorrect password since the last correct
2578     *         password entry.
2579     * @throws SecurityException if the calling application does not own an active administrator
2580     *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2581     */
2582    public int getCurrentFailedPasswordAttempts() {
2583        return getCurrentFailedPasswordAttempts(myUserId());
2584    }
2585
2586    /**
2587     * Retrieve the number of times the given user has failed at entering a
2588     * password since that last successful password entry.
2589     *
2590     * <p>The calling device admin must have requested
2591     * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
2592     * not and it is not the system uid, a security exception will be thrown.
2593     *
2594     * @hide
2595     */
2596    public int getCurrentFailedPasswordAttempts(int userHandle) {
2597        if (mService != null) {
2598            try {
2599                return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
2600            } catch (RemoteException e) {
2601                throw e.rethrowFromSystemServer();
2602            }
2603        }
2604        return -1;
2605    }
2606
2607    /**
2608     * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
2609     *
2610     * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
2611     * @hide
2612     */
2613    public boolean getDoNotAskCredentialsOnBoot() {
2614        if (mService != null) {
2615            try {
2616                return mService.getDoNotAskCredentialsOnBoot();
2617            } catch (RemoteException e) {
2618                throw e.rethrowFromSystemServer();
2619            }
2620        }
2621        return false;
2622    }
2623
2624    /**
2625     * Setting this to a value greater than zero enables a built-in policy that will perform a
2626     * device or profile wipe after too many incorrect device-unlock passwords have been entered.
2627     * This built-in policy combines watching for failed passwords and wiping the device, and
2628     * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2629     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
2630     * <p>
2631     * To implement any other policy (e.g. wiping data for a particular application only, erasing or
2632     * revoking credentials, or reporting the failure to a server), you should implement
2633     * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
2634     * use this API, because if the maximum count is reached, the device or profile will be wiped
2635     * immediately, and your callback will not be invoked.
2636     * <p>
2637     * This method can be called on the {@link DevicePolicyManager} instance returned by
2638     * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
2639     * profile.
2640     *
2641     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2642     * @param num The number of failed password attempts at which point the device or profile will
2643     *            be wiped.
2644     * @throws SecurityException if {@code admin} is not an active administrator or does not use
2645     *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2646     *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
2647     */
2648    public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
2649        if (mService != null) {
2650            try {
2651                mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
2652            } catch (RemoteException e) {
2653                throw e.rethrowFromSystemServer();
2654            }
2655        }
2656    }
2657
2658    /**
2659     * Retrieve the current maximum number of login attempts that are allowed before the device
2660     * or profile is wiped, for a particular admin or all admins that set restrictions on this user
2661     * and its participating profiles. Restrictions on profiles that have a separate challenge are
2662     * not taken into account.
2663     *
2664     * <p>This method can be called on the {@link DevicePolicyManager} instance
2665     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2666     * the value for the parent profile.
2667     *
2668     * @param admin The name of the admin component to check, or {@code null} to aggregate
2669     * all admins.
2670     */
2671    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
2672        return getMaximumFailedPasswordsForWipe(admin, myUserId());
2673    }
2674
2675    /** @hide per-user version */
2676    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
2677        if (mService != null) {
2678            try {
2679                return mService.getMaximumFailedPasswordsForWipe(
2680                        admin, userHandle, mParentInstance);
2681            } catch (RemoteException e) {
2682                throw e.rethrowFromSystemServer();
2683            }
2684        }
2685        return 0;
2686    }
2687
2688    /**
2689     * Returns the profile with the smallest maximum failed passwords for wipe,
2690     * for the given user. So for primary user, it might return the primary or
2691     * a managed profile. For a secondary user, it would be the same as the
2692     * user passed in.
2693     * @hide Used only by Keyguard
2694     */
2695    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
2696        if (mService != null) {
2697            try {
2698                return mService.getProfileWithMinimumFailedPasswordsForWipe(
2699                        userHandle, mParentInstance);
2700            } catch (RemoteException e) {
2701                throw e.rethrowFromSystemServer();
2702            }
2703        }
2704        return UserHandle.USER_NULL;
2705    }
2706
2707    /**
2708     * Flag for {@link #resetPassword}: don't allow other admins to change
2709     * the password again until the user has entered it.
2710     */
2711    public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
2712
2713    /**
2714     * Flag for {@link #resetPassword}: don't ask for user credentials on device boot.
2715     * If the flag is set, the device can be booted without asking for user password.
2716     * The absence of this flag does not change the current boot requirements. This flag
2717     * can be set by the device owner only. If the app is not the device owner, the flag
2718     * is ignored. Once the flag is set, it cannot be reverted back without resetting the
2719     * device to factory defaults.
2720     */
2721    public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
2722
2723    /**
2724     * Force a new device unlock password (the password needed to access the entire device, not for
2725     * individual accounts) on the user. This takes effect immediately.
2726     * <p>
2727     * <em>For device owner and profile owners targeting SDK level
2728     * {@link android.os.Build.VERSION_CODES#O} or above, this API is no longer available and will
2729     * throw {@link SecurityException}. Please use the new API {@link #resetPasswordWithToken}
2730     * instead. </em>
2731     * <p>
2732     * <em>Note: This API has been limited as of {@link android.os.Build.VERSION_CODES#N} for
2733     * device admins that are not device owner and not profile owner.
2734     * The password can now only be changed if there is currently no password set.  Device owner
2735     * and profile owner can still do this when user is unlocked and does not have a managed
2736     * profile.</em>
2737     * <p>
2738     * The given password must be sufficient for the current password quality and length constraints
2739     * as returned by {@link #getPasswordQuality(ComponentName)} and
2740     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
2741     * it will be rejected and false returned. Note that the password may be a stronger quality
2742     * (containing alphanumeric characters when the requested quality is only numeric), in which
2743     * case the currently active quality will be increased to match.
2744     * <p>
2745     * Calling with a null or empty password will clear any existing PIN, pattern or password if the
2746     * current password constraints allow it. <em>Note: This will not work in
2747     * {@link android.os.Build.VERSION_CODES#N} and later for managed profiles, or for device admins
2748     * that are not device owner or profile owner.  Once set, the password cannot be changed to null
2749     * or empty except by these admins.</em>
2750     * <p>
2751     * The calling device admin must have requested
2752     * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
2753     * not, a security exception will be thrown.
2754     *
2755     * @param password The new password for the user. Null or empty clears the password.
2756     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
2757     *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
2758     * @return Returns true if the password was applied, or false if it is not acceptable for the
2759     *         current constraints or if the user has not been decrypted yet.
2760     * @throws SecurityException if the calling application does not own an active administrator
2761     *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
2762     * @throws IllegalStateException if the calling user is locked or has a managed profile.
2763     * @throws IllegalArgumentException if the password does not meet system requirements.
2764     */
2765    public boolean resetPassword(String password, int flags) {
2766        throwIfParentInstance("resetPassword");
2767        if (mService != null) {
2768            try {
2769                return mService.resetPassword(password, flags);
2770            } catch (RemoteException e) {
2771                throw e.rethrowFromSystemServer();
2772            }
2773        }
2774        return false;
2775    }
2776
2777    /**
2778     * Called by a profile or device owner to provision a token which can later be used to reset the
2779     * device lockscreen password (if called by device owner), or managed profile challenge (if
2780     * called by profile owner), via {@link #resetPasswordWithToken}.
2781     * <p>
2782     * If the user currently has a lockscreen password, the provisioned token will not be
2783     * immediately usable; it only becomes active after the user performs a confirm credential
2784     * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
2785     * If the user has no lockscreen password, the token is activated immediately. In all cases,
2786     * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
2787     * For security reasons, un-activated tokens are only stored in memory and will be lost once
2788     * the device reboots. In this case a new token needs to be provisioned again.
2789     * <p>
2790     * Once provisioned and activated, the token will remain effective even if the user changes
2791     * or clears the lockscreen password.
2792     * <p>
2793     * <em>This token is highly sensitive and should be treated at the same level as user
2794     * credentials. In particular, NEVER store this token on device in plaintext. Do not store
2795     * the plaintext token in device-encrypted storage if it will be needed to reset password on
2796     * file-based encryption devices before user unlocks. Consider carefully how any password token
2797     * will be stored on your server and who will need access to them. Tokens may be the subject of
2798     * legal access requests.
2799     * </em>
2800     *
2801     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2802     * @param token a secure token a least 32-byte long, which must be generated by a
2803     *        cryptographically strong random number generator.
2804     * @return true if the operation is successful, false otherwise.
2805     * @throws IllegalArgumentException if the supplied token is invalid.
2806     * @throws SecurityException
2807     */
2808    public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
2809        throwIfParentInstance("setResetPasswordToken");
2810        if (mService != null) {
2811            try {
2812                return mService.setResetPasswordToken(admin, token);
2813            } catch (RemoteException e) {
2814                throw e.rethrowFromSystemServer();
2815            }
2816        }
2817        return false;
2818    }
2819
2820    /**
2821     * Called by a profile or device owner to revoke the current password reset token.
2822     *
2823     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2824     * @return true if the operation is successful, false otherwise.
2825     */
2826    public boolean clearResetPasswordToken(ComponentName admin) {
2827        throwIfParentInstance("clearResetPasswordToken");
2828        if (mService != null) {
2829            try {
2830                return mService.clearResetPasswordToken(admin);
2831            } catch (RemoteException e) {
2832                throw e.rethrowFromSystemServer();
2833            }
2834        }
2835        return false;
2836    }
2837
2838    /**
2839     * Called by a profile or device owner to check if the current reset password token is active.
2840     *
2841     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2842     * @return true if the token is active, false otherwise.
2843     * @throws IllegalStateException if no token has been set.
2844     */
2845    public boolean isResetPasswordTokenActive(ComponentName admin) {
2846        throwIfParentInstance("isResetPasswordTokenActive");
2847        if (mService != null) {
2848            try {
2849                return mService.isResetPasswordTokenActive(admin);
2850            } catch (RemoteException e) {
2851                throw e.rethrowFromSystemServer();
2852            }
2853        }
2854        return false;
2855    }
2856
2857    /**
2858     * Called by device or profile owner to force set a new device unlock password or a managed
2859     * profile challenge on current user. This takes effect immediately.
2860     * <p>
2861     * Unlike {@link #resetPassword}, this API can change the password even before the user or
2862     * device is unlocked or decrypted. The supplied token must have been previously provisioned via
2863     * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
2864     * <p>
2865     * The given password must be sufficient for the current password quality and length constraints
2866     * as returned by {@link #getPasswordQuality(ComponentName)} and
2867     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
2868     * it will be rejected and false returned. Note that the password may be a stronger quality
2869     * (containing alphanumeric characters when the requested quality is only numeric), in which
2870     * case the currently active quality will be increased to match.
2871     * <p>
2872     * Calling with a null or empty password will clear any existing PIN, pattern or password if the
2873     * current password constraints allow it.
2874     *
2875     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2876     * @param password The new password for the user. Null or empty clears the password.
2877     * @param token the password reset token previously provisioned by #setResetPasswordToken.
2878     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
2879     *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
2880     * @return Returns true if the password was applied, or false if it is not acceptable for the
2881     *         current constraints.
2882     * @throws SecurityException if the calling application does not own an active administrator
2883     *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
2884     * @throws IllegalStateException if the provided token is not valid.
2885     * @throws IllegalArgumentException if the password does not meet system requirements.
2886     */
2887    public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
2888            byte[] token, int flags) {
2889        throwIfParentInstance("resetPassword");
2890        if (mService != null) {
2891            try {
2892                return mService.resetPasswordWithToken(admin, password, token, flags);
2893            } catch (RemoteException e) {
2894                throw e.rethrowFromSystemServer();
2895            }
2896        }
2897        return false;
2898    }
2899
2900    /**
2901     * Called by an application that is administering the device to set the maximum time for user
2902     * activity until the device will lock. This limits the length that the user can set. It takes
2903     * effect immediately.
2904     * <p>
2905     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
2906     * to be able to call this method; if it has not, a security exception will be thrown.
2907     * <p>
2908     * This method can be called on the {@link DevicePolicyManager} instance returned by
2909     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2910     * profile.
2911     *
2912     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2913     * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
2914     *            is no restriction.
2915     * @throws SecurityException if {@code admin} is not an active administrator or it does not use
2916     *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
2917     */
2918    public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
2919        if (mService != null) {
2920            try {
2921                mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
2922            } catch (RemoteException e) {
2923                throw e.rethrowFromSystemServer();
2924            }
2925        }
2926    }
2927
2928    /**
2929     * Retrieve the current maximum time to unlock for a particular admin or all admins that set
2930     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2931     * a separate challenge are not taken into account.
2932     *
2933     * <p>This method can be called on the {@link DevicePolicyManager} instance
2934     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2935     * restrictions on the parent profile.
2936     *
2937     * @param admin The name of the admin component to check, or {@code null} to aggregate
2938     * all admins.
2939     * @return time in milliseconds for the given admin or the minimum value (strictest) of
2940     * all admins if admin is null. Returns 0 if there are no restrictions.
2941     */
2942    public long getMaximumTimeToLock(@Nullable ComponentName admin) {
2943        return getMaximumTimeToLock(admin, myUserId());
2944    }
2945
2946    /** @hide per-user version */
2947    public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
2948        if (mService != null) {
2949            try {
2950                return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
2951            } catch (RemoteException e) {
2952                throw e.rethrowFromSystemServer();
2953            }
2954        }
2955        return 0;
2956    }
2957
2958    /**
2959     * Returns maximum time to lock that applied by all profiles in this user. We do this because we
2960     * do not have a separate timeout to lock for work challenge only.
2961     *
2962     * @hide
2963     */
2964    public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
2965        if (mService != null) {
2966            try {
2967                return mService.getMaximumTimeToLockForUserAndProfiles(userHandle);
2968            } catch (RemoteException e) {
2969                throw e.rethrowFromSystemServer();
2970            }
2971        }
2972        return 0;
2973    }
2974
2975    /**
2976     * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
2977     * strong auth (e.g. fingerprint, trust agents) times out, i.e. the user has to use a strong
2978     * authentication method like password, pin or pattern.
2979     *
2980     * <p>This timeout is used internally to reset the timer to require strong auth again after
2981     * specified timeout each time it has been successfully used.
2982     *
2983     * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
2984     *
2985     * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
2986     *
2987     * <p>The calling device admin must be a device or profile owner. If it is not,
2988     * a {@link SecurityException} will be thrown.
2989     *
2990     * <p>The calling device admin can verify the value it has set by calling
2991     * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
2992     *
2993     * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
2994     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2995     * profile.
2996     *
2997     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2998     * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
2999     *         with strong authentication method. A value of 0 means the admin is not participating
3000     *         in controlling the timeout.
3001     *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
3002     *         72 hours, respectively. Though discouraged, the admin may choose to require strong
3003     *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
3004     *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3005     *
3006     * @throws SecurityException if {@code admin} is not a device or profile owner.
3007     */
3008    public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
3009            long timeoutMs) {
3010        if (mService != null) {
3011            try {
3012                mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
3013            } catch (RemoteException e) {
3014                throw e.rethrowFromSystemServer();
3015            }
3016        }
3017    }
3018
3019    /**
3020     * Determine for how long the user will be able to use secondary, non strong auth for
3021     * authentication, since last strong method authentication (password, pin or pattern) was used.
3022     * After the returned timeout the user is required to use strong authentication method.
3023     *
3024     * <p>This method can be called on the {@link DevicePolicyManager} instance
3025     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3026     * restrictions on the parent profile.
3027     *
3028     * @param admin The name of the admin component to check, or {@code null} to aggregate
3029     *         accross all participating admins.
3030     * @return The timeout in milliseconds or 0 if not configured for the provided admin.
3031     */
3032    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
3033        return getRequiredStrongAuthTimeout(admin, myUserId());
3034    }
3035
3036    /** @hide per-user version */
3037    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
3038        if (mService != null) {
3039            try {
3040                return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
3041            } catch (RemoteException e) {
3042                throw e.rethrowFromSystemServer();
3043            }
3044        }
3045        return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
3046    }
3047
3048    /**
3049     * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
3050     * keyring. The user's credential will need to be entered again in order to derive the
3051     * credential encryption key that will be stored back in the keyring for future use.
3052     * <p>
3053     * This flag can only be used by a profile owner when locking a managed profile when
3054     * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3055     * <p>
3056     * In order to secure user data, the user will be stopped and restarted so apps should wait
3057     * until they are next run to perform further actions.
3058     */
3059    public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
3060
3061    /**
3062     * Instead use {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
3063     * @removed
3064     */
3065    @Deprecated
3066    public static final int FLAG_EVICT_CE_KEY = 1;
3067
3068    /** @hide */
3069    @Retention(RetentionPolicy.SOURCE)
3070    @IntDef(flag=true, value={FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY})
3071    public @interface LockNowFlag {}
3072
3073    /**
3074     * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3075     * this call.
3076     * <p>
3077     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3078     * to be able to call this method; if it has not, a security exception will be thrown.
3079     * <p>
3080     * This method can be called on the {@link DevicePolicyManager} instance returned by
3081     * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3082     * <p>
3083     * Equivalent to calling {@link #lockNow(int)} with no flags.
3084     *
3085     * @throws SecurityException if the calling application does not own an active administrator
3086     *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3087     */
3088    public void lockNow() {
3089        lockNow(0);
3090    }
3091
3092    /**
3093     * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3094     * this call.
3095     * <p>
3096     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3097     * to be able to call this method; if it has not, a security exception will be thrown.
3098     * <p>
3099     * This method can be called on the {@link DevicePolicyManager} instance returned by
3100     * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3101     *
3102     * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
3103     * @throws SecurityException if the calling application does not own an active administrator
3104     *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
3105     *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
3106     *             that is not a profile
3107     *             owner of a managed profile.
3108     * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
3109     *             passed when locking the parent profile.
3110     * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
3111     *             flag is passed when {@link #getStorageEncryptionStatus} does not return
3112     *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3113     */
3114    public void lockNow(@LockNowFlag int flags) {
3115        if (mService != null) {
3116            try {
3117                mService.lockNow(flags, mParentInstance);
3118            } catch (RemoteException e) {
3119                throw e.rethrowFromSystemServer();
3120            }
3121        }
3122    }
3123
3124    /**
3125     * Flag for {@link #wipeData(int)}: also erase the device's external
3126     * storage (such as SD cards).
3127     */
3128    public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
3129
3130    /**
3131     * Flag for {@link #wipeData(int)}: also erase the factory reset protection
3132     * data.
3133     *
3134     * <p>This flag may only be set by device owner admins; if it is set by
3135     * other admins a {@link SecurityException} will be thrown.
3136     */
3137    public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
3138
3139    /**
3140     * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
3141     * other users will remain unaffected. Calling from the primary user will cause the device to
3142     * reboot, erasing all device data - including all the secondary users and their data - while
3143     * booting up.
3144     * <p>
3145     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
3146     * be able to call this method; if it has not, a security exception will be thrown.
3147     *
3148     * @param flags Bit mask of additional options: currently supported flags are
3149     *            {@link #WIPE_EXTERNAL_STORAGE} and {@link #WIPE_RESET_PROTECTION_DATA}.
3150     * @throws SecurityException if the calling application does not own an active administrator
3151     *             that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
3152     */
3153    public void wipeData(int flags) {
3154        throwIfParentInstance("wipeData");
3155        if (mService != null) {
3156            try {
3157                mService.wipeData(flags);
3158            } catch (RemoteException e) {
3159                throw e.rethrowFromSystemServer();
3160            }
3161        }
3162    }
3163
3164    /**
3165     * Called by an application that is administering the device to set the
3166     * global proxy and exclusion list.
3167     * <p>
3168     * The calling device admin must have requested
3169     * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
3170     * this method; if it has not, a security exception will be thrown.
3171     * Only the first device admin can set the proxy. If a second admin attempts
3172     * to set the proxy, the {@link ComponentName} of the admin originally setting the
3173     * proxy will be returned. If successful in setting the proxy, {@code null} will
3174     * be returned.
3175     * The method can be called repeatedly by the device admin alrady setting the
3176     * proxy to update the proxy and exclusion list.
3177     *
3178     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3179     * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
3180     *            Pass Proxy.NO_PROXY to reset the proxy.
3181     * @param exclusionList a list of domains to be excluded from the global proxy.
3182     * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
3183     *            of the device admin that sets the proxy.
3184     * @hide
3185     */
3186    public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
3187            List<String> exclusionList ) {
3188        throwIfParentInstance("setGlobalProxy");
3189        if (proxySpec == null) {
3190            throw new NullPointerException();
3191        }
3192        if (mService != null) {
3193            try {
3194                String hostSpec;
3195                String exclSpec;
3196                if (proxySpec.equals(Proxy.NO_PROXY)) {
3197                    hostSpec = null;
3198                    exclSpec = null;
3199                } else {
3200                    if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
3201                        throw new IllegalArgumentException();
3202                    }
3203                    InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
3204                    String hostName = sa.getHostName();
3205                    int port = sa.getPort();
3206                    StringBuilder hostBuilder = new StringBuilder();
3207                    hostSpec = hostBuilder.append(hostName)
3208                        .append(":").append(Integer.toString(port)).toString();
3209                    if (exclusionList == null) {
3210                        exclSpec = "";
3211                    } else {
3212                        StringBuilder listBuilder = new StringBuilder();
3213                        boolean firstDomain = true;
3214                        for (String exclDomain : exclusionList) {
3215                            if (!firstDomain) {
3216                                listBuilder = listBuilder.append(",");
3217                            } else {
3218                                firstDomain = false;
3219                            }
3220                            listBuilder = listBuilder.append(exclDomain.trim());
3221                        }
3222                        exclSpec = listBuilder.toString();
3223                    }
3224                    if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
3225                            != android.net.Proxy.PROXY_VALID)
3226                        throw new IllegalArgumentException();
3227                }
3228                return mService.setGlobalProxy(admin, hostSpec, exclSpec);
3229            } catch (RemoteException e) {
3230                throw e.rethrowFromSystemServer();
3231            }
3232        }
3233        return null;
3234    }
3235
3236    /**
3237     * Set a network-independent global HTTP proxy. This is not normally what you want for typical
3238     * HTTP proxies - they are generally network dependent. However if you're doing something
3239     * unusual like general internal filtering this may be useful. On a private network where the
3240     * proxy is not accessible, you may break HTTP using this.
3241     * <p>
3242     * This method requires the caller to be the device owner.
3243     * <p>
3244     * This proxy is only a recommendation and it is possible that some apps will ignore it.
3245     *
3246     * @see ProxyInfo
3247     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3248     * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
3249     *            {@code null} value will clear the global HTTP proxy.
3250     * @throws SecurityException if {@code admin} is not the device owner.
3251     */
3252    public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
3253            proxyInfo) {
3254        throwIfParentInstance("setRecommendedGlobalProxy");
3255        if (mService != null) {
3256            try {
3257                mService.setRecommendedGlobalProxy(admin, proxyInfo);
3258            } catch (RemoteException e) {
3259                throw e.rethrowFromSystemServer();
3260            }
3261        }
3262    }
3263
3264    /**
3265     * Returns the component name setting the global proxy.
3266     * @return ComponentName object of the device admin that set the global proxy, or {@code null}
3267     *         if no admin has set the proxy.
3268     * @hide
3269     */
3270    public @Nullable ComponentName getGlobalProxyAdmin() {
3271        if (mService != null) {
3272            try {
3273                return mService.getGlobalProxyAdmin(myUserId());
3274            } catch (RemoteException e) {
3275                throw e.rethrowFromSystemServer();
3276            }
3277        }
3278        return null;
3279    }
3280
3281    /**
3282     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3283     * indicating that encryption is not supported.
3284     */
3285    public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
3286
3287    /**
3288     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3289     * indicating that encryption is supported, but is not currently active.
3290     */
3291    public static final int ENCRYPTION_STATUS_INACTIVE = 1;
3292
3293    /**
3294     * Result code for {@link #getStorageEncryptionStatus}:
3295     * indicating that encryption is not currently active, but is currently
3296     * being activated.  This is only reported by devices that support
3297     * encryption of data and only when the storage is currently
3298     * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
3299     * to become encrypted will never return this value.
3300     */
3301    public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
3302
3303    /**
3304     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3305     * indicating that encryption is active.
3306     * <p>
3307     * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3308     */
3309    public static final int ENCRYPTION_STATUS_ACTIVE = 3;
3310
3311    /**
3312     * Result code for {@link #getStorageEncryptionStatus}:
3313     * indicating that encryption is active, but an encryption key has not
3314     * been set by the user.
3315     */
3316    public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
3317
3318    /**
3319     * Result code for {@link #getStorageEncryptionStatus}:
3320     * indicating that encryption is active and the encryption key is tied to the user or profile.
3321     * <p>
3322     * This value is only returned to apps targeting API level 24 and above. For apps targeting
3323     * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
3324     * encryption key is specific to the user or profile.
3325     */
3326    public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
3327
3328    /**
3329     * Activity action: begin the process of encrypting data on the device.  This activity should
3330     * be launched after using {@link #setStorageEncryption} to request encryption be activated.
3331     * After resuming from this activity, use {@link #getStorageEncryption}
3332     * to check encryption status.  However, on some devices this activity may never return, as
3333     * it may trigger a reboot and in some cases a complete data wipe of the device.
3334     */
3335    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3336    public static final String ACTION_START_ENCRYPTION
3337            = "android.app.action.START_ENCRYPTION";
3338    /**
3339     * Widgets are enabled in keyguard
3340     */
3341    public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
3342
3343    /**
3344     * Disable all keyguard widgets. Has no effect.
3345     */
3346    public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
3347
3348    /**
3349     * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
3350     */
3351    public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
3352
3353    /**
3354     * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3355     */
3356    public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
3357
3358    /**
3359     * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3360     */
3361    public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
3362
3363    /**
3364     * Ignore trust agent state on secure keyguard screens
3365     * (e.g. PIN/Pattern/Password).
3366     */
3367    public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
3368
3369    /**
3370     * Disable fingerprint sensor on keyguard secure screens (e.g. PIN/Pattern/Password).
3371     */
3372    public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
3373
3374    /**
3375     * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
3376     */
3377    public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
3378
3379    /**
3380     * Disable all current and future keyguard customizations.
3381     */
3382    public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
3383
3384    /**
3385     * Keyguard features that when set on a managed profile that doesn't have its own challenge will
3386     * affect the profile's parent user. These can also be set on the managed profile's parent
3387     * {@link DevicePolicyManager} instance.
3388     *
3389     * @hide
3390     */
3391    public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
3392            DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
3393            | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
3394
3395    /**
3396     * Called by an application that is administering the device to request that the storage system
3397     * be encrypted.
3398     * <p>
3399     * When multiple device administrators attempt to control device encryption, the most secure,
3400     * supported setting will always be used. If any device administrator requests device
3401     * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
3402     * device encryption while another device administrator has enabled it, the call to disable will
3403     * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
3404     * <p>
3405     * This policy controls encryption of the secure (application data) storage area. Data written
3406     * to other storage areas may or may not be encrypted, and this policy does not require or
3407     * control the encryption of any other storage areas. There is one exception: If
3408     * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
3409     * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
3410     * written to disk within the encrypted storage area.
3411     * <p>
3412     * Important Note: On some devices, it is possible to encrypt storage without requiring the user
3413     * to create a device PIN or Password. In this case, the storage is encrypted, but the
3414     * encryption key may not be fully secured. For maximum security, the administrator should also
3415     * require (and check for) a pattern, PIN, or password.
3416     *
3417     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3418     * @param encrypt true to request encryption, false to release any previous request
3419     * @return the new request status (for all active admins) - will be one of
3420     *         {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, or
3421     *         {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value of the requests; Use
3422     *         {@link #getStorageEncryptionStatus()} to query the actual device state.
3423     * @throws SecurityException if {@code admin} is not an active administrator or does not use
3424     *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
3425     */
3426    public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
3427        throwIfParentInstance("setStorageEncryption");
3428        if (mService != null) {
3429            try {
3430                return mService.setStorageEncryption(admin, encrypt);
3431            } catch (RemoteException e) {
3432                throw e.rethrowFromSystemServer();
3433            }
3434        }
3435        return ENCRYPTION_STATUS_UNSUPPORTED;
3436    }
3437
3438    /**
3439     * Called by an application that is administering the device to
3440     * determine the requested setting for secure storage.
3441     *
3442     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
3443     * this will return the requested encryption setting as an aggregate of all active
3444     * administrators.
3445     * @return true if the admin(s) are requesting encryption, false if not.
3446     */
3447    public boolean getStorageEncryption(@Nullable ComponentName admin) {
3448        throwIfParentInstance("getStorageEncryption");
3449        if (mService != null) {
3450            try {
3451                return mService.getStorageEncryption(admin, myUserId());
3452            } catch (RemoteException e) {
3453                throw e.rethrowFromSystemServer();
3454            }
3455        }
3456        return false;
3457    }
3458
3459    /**
3460     * Called by an application that is administering the device to
3461     * determine the current encryption status of the device.
3462     * <p>
3463     * Depending on the returned status code, the caller may proceed in different
3464     * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
3465     * storage system does not support encryption.  If the
3466     * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
3467     * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
3468     * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
3469     * storage system has enabled encryption but no password is set so further action
3470     * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
3471     * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
3472     * no further action is required.
3473     *
3474     * @return current status of encryption. The value will be one of
3475     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
3476     * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
3477     * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3478     */
3479    public int getStorageEncryptionStatus() {
3480        throwIfParentInstance("getStorageEncryptionStatus");
3481        return getStorageEncryptionStatus(myUserId());
3482    }
3483
3484    /** @hide per-user version */
3485    public int getStorageEncryptionStatus(int userHandle) {
3486        if (mService != null) {
3487            try {
3488                return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
3489            } catch (RemoteException e) {
3490                throw e.rethrowFromSystemServer();
3491            }
3492        }
3493        return ENCRYPTION_STATUS_UNSUPPORTED;
3494    }
3495
3496    /**
3497     * Mark a CA certificate as approved by the device user. This means that they have been notified
3498     * of the installation, were made aware of the risks, viewed the certificate and still wanted to
3499     * keep the certificate on the device.
3500     *
3501     * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
3502     * this certificate.
3503     *
3504     * @hide
3505     */
3506    public boolean approveCaCert(String alias, int userHandle, boolean approval) {
3507        if (mService != null) {
3508            try {
3509                return mService.approveCaCert(alias, userHandle, approval);
3510            } catch (RemoteException e) {
3511                throw e.rethrowFromSystemServer();
3512            }
3513        }
3514        return false;
3515    }
3516
3517    /**
3518     * Check whether a CA certificate has been approved by the device user.
3519     *
3520     * @hide
3521     */
3522    public boolean isCaCertApproved(String alias, int userHandle) {
3523        if (mService != null) {
3524            try {
3525                return mService.isCaCertApproved(alias, userHandle);
3526            } catch (RemoteException e) {
3527                throw e.rethrowFromSystemServer();
3528            }
3529        }
3530        return false;
3531    }
3532
3533    /**
3534     * Installs the given certificate as a user CA.
3535     *
3536     * The caller must be a profile or device owner on that user, or a delegate package given the
3537     * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3538     * security exception will be thrown.
3539     *
3540     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3541     *              {@code null} if calling from a delegated certificate installer.
3542     * @param certBuffer encoded form of the certificate to install.
3543     *
3544     * @return false if the certBuffer cannot be parsed or installation is
3545     *         interrupted, true otherwise.
3546     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3547     *         owner.
3548     * @see #setDelegatedScopes
3549     * @see #DELEGATION_CERT_INSTALL
3550     */
3551    public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3552        throwIfParentInstance("installCaCert");
3553        if (mService != null) {
3554            try {
3555                return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
3556            } catch (RemoteException e) {
3557                throw e.rethrowFromSystemServer();
3558            }
3559        }
3560        return false;
3561    }
3562
3563    /**
3564     * Uninstalls the given certificate from trusted user CAs, if present.
3565     *
3566     * The caller must be a profile or device owner on that user, or a delegate package given the
3567     * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3568     * security exception will be thrown.
3569     *
3570     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3571     *              {@code null} if calling from a delegated certificate installer.
3572     * @param certBuffer encoded form of the certificate to remove.
3573     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3574     *         owner.
3575     * @see #setDelegatedScopes
3576     * @see #DELEGATION_CERT_INSTALL
3577     */
3578    public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3579        throwIfParentInstance("uninstallCaCert");
3580        if (mService != null) {
3581            try {
3582                final String alias = getCaCertAlias(certBuffer);
3583                mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
3584            } catch (CertificateException e) {
3585                Log.w(TAG, "Unable to parse certificate", e);
3586            } catch (RemoteException e) {
3587                throw e.rethrowFromSystemServer();
3588            }
3589        }
3590    }
3591
3592    /**
3593     * Returns all CA certificates that are currently trusted, excluding system CA certificates.
3594     * If a user has installed any certificates by other means than device policy these will be
3595     * included too.
3596     *
3597     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3598     *              {@code null} if calling from a delegated certificate installer.
3599     * @return a List of byte[] arrays, each encoding one user CA certificate.
3600     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3601     *         owner.
3602     */
3603    public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
3604        final List<byte[]> certs = new ArrayList<byte[]>();
3605        throwIfParentInstance("getInstalledCaCerts");
3606        if (mService != null) {
3607            try {
3608                mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
3609                final TrustedCertificateStore certStore = new TrustedCertificateStore();
3610                for (String alias : certStore.userAliases()) {
3611                    try {
3612                        certs.add(certStore.getCertificate(alias).getEncoded());
3613                    } catch (CertificateException ce) {
3614                        Log.w(TAG, "Could not encode certificate: " + alias, ce);
3615                    }
3616                }
3617            } catch (RemoteException re) {
3618                throw re.rethrowFromSystemServer();
3619            }
3620        }
3621        return certs;
3622    }
3623
3624    /**
3625     * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
3626     * means other than device policy will also be removed, except for system CA certificates.
3627     *
3628     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3629     *              {@code null} if calling from a delegated certificate installer.
3630     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3631     *         owner.
3632     */
3633    public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
3634        throwIfParentInstance("uninstallAllUserCaCerts");
3635        if (mService != null) {
3636            try {
3637                mService.uninstallCaCerts(admin, mContext.getPackageName(),
3638                        new TrustedCertificateStore().userAliases() .toArray(new String[0]));
3639            } catch (RemoteException re) {
3640                throw re.rethrowFromSystemServer();
3641            }
3642        }
3643    }
3644
3645    /**
3646     * Returns whether this certificate is installed as a trusted CA.
3647     *
3648     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3649     *              {@code null} if calling from a delegated certificate installer.
3650     * @param certBuffer encoded form of the certificate to look up.
3651     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3652     *         owner.
3653     */
3654    public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
3655        throwIfParentInstance("hasCaCertInstalled");
3656        if (mService != null) {
3657            try {
3658                mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
3659                return getCaCertAlias(certBuffer) != null;
3660            } catch (RemoteException re) {
3661                throw re.rethrowFromSystemServer();
3662            } catch (CertificateException ce) {
3663                Log.w(TAG, "Could not parse certificate", ce);
3664            }
3665        }
3666        return false;
3667    }
3668
3669    /**
3670     * Called by a device or profile owner, or delegated certificate installer, to install a
3671     * certificate and corresponding private key. All apps within the profile will be able to access
3672     * the certificate and use the private key, given direct user approval.
3673     *
3674     * <p>Access to the installed credentials will not be granted to the caller of this API without
3675     * direct user approval. This is for security - should a certificate installer become
3676     * compromised, certificates it had already installed will be protected.
3677     *
3678     * <p>If the installer must have access to the credentials, call
3679     * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
3680     *
3681     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3682     *            {@code null} if calling from a delegated certificate installer.
3683     * @param privKey The private key to install.
3684     * @param cert The certificate to install.
3685     * @param alias The private key alias under which to install the certificate. If a certificate
3686     * with that alias already exists, it will be overwritten.
3687     * @return {@code true} if the keys were installed, {@code false} otherwise.
3688     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3689     *         owner.
3690     * @see #setDelegatedScopes
3691     * @see #DELEGATION_CERT_INSTALL
3692     */
3693    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
3694            @NonNull Certificate cert, @NonNull String alias) {
3695        return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
3696    }
3697
3698    /**
3699     * Called by a device or profile owner, or delegated certificate installer, to install a
3700     * certificate chain and corresponding private key for the leaf certificate. All apps within the
3701     * profile will be able to access the certificate chain and use the private key, given direct
3702     * user approval.
3703     *
3704     * <p>The caller of this API may grant itself access to the certificate and private key
3705     * immediately, without user approval. It is a best practice not to request this unless strictly
3706     * necessary since it opens up additional security vulnerabilities.
3707     *
3708     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3709     *        {@code null} if calling from a delegated certificate installer.
3710     * @param privKey The private key to install.
3711     * @param certs The certificate chain to install. The chain should start with the leaf
3712     *        certificate and include the chain of trust in order. This will be returned by
3713     *        {@link android.security.KeyChain#getCertificateChain}.
3714     * @param alias The private key alias under which to install the certificate. If a certificate
3715     *        with that alias already exists, it will be overwritten.
3716     * @param requestAccess {@code true} to request that the calling app be granted access to the
3717     *        credentials immediately. Otherwise, access to the credentials will be gated by user
3718     *        approval.
3719     * @return {@code true} if the keys were installed, {@code false} otherwise.
3720     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3721     *         owner.
3722     * @see android.security.KeyChain#getCertificateChain
3723     * @see #setDelegatedScopes
3724     * @see #DELEGATION_CERT_INSTALL
3725     */
3726    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
3727            @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
3728        throwIfParentInstance("installKeyPair");
3729        try {
3730            final byte[] pemCert = Credentials.convertToPem(certs[0]);
3731            byte[] pemChain = null;
3732            if (certs.length > 1) {
3733                pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
3734            }
3735            final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
3736                    .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
3737            return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
3738                    pemChain, alias, requestAccess);
3739        } catch (RemoteException e) {
3740            throw e.rethrowFromSystemServer();
3741        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
3742            Log.w(TAG, "Failed to obtain private key material", e);
3743        } catch (CertificateException | IOException e) {
3744            Log.w(TAG, "Could not pem-encode certificate", e);
3745        }
3746        return false;
3747    }
3748
3749    /**
3750     * Called by a device or profile owner, or delegated certificate installer, to remove a
3751     * certificate and private key pair installed under a given alias.
3752     *
3753     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3754     *        {@code null} if calling from a delegated certificate installer.
3755     * @param alias The private key alias under which the certificate is installed.
3756     * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
3757     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3758     *         owner.
3759     * @see #setDelegatedScopes
3760     * @see #DELEGATION_CERT_INSTALL
3761     */
3762    public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
3763        throwIfParentInstance("removeKeyPair");
3764        try {
3765            return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
3766        } catch (RemoteException e) {
3767            throw e.rethrowFromSystemServer();
3768        }
3769    }
3770
3771    /**
3772     * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
3773     * doesn't exist.
3774     */
3775    private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
3776        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
3777        final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
3778                              new ByteArrayInputStream(certBuffer));
3779        return new TrustedCertificateStore().getCertificateAlias(cert);
3780    }
3781
3782    /**
3783     * Called by a profile owner or device owner to grant access to privileged certificate
3784     * manipulation APIs to a third-party certificate installer app. Granted APIs include
3785     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
3786     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
3787     * <p>
3788     * Delegated certificate installer is a per-user state. The delegated access is persistent until
3789     * it is later cleared by calling this method with a null value or uninstallling the certificate
3790     * installer.
3791     * <p>
3792     * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
3793     * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
3794     * supplied certificate installer package must be installed when calling this API, otherwise an
3795     * {@link IllegalArgumentException} will be thrown.
3796     *
3797     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3798     * @param installerPackage The package name of the certificate installer which will be given
3799     *            access. If {@code null} is given the current package will be cleared.
3800     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3801     *
3802     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
3803     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
3804     */
3805    @Deprecated
3806    public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
3807            installerPackage) throws SecurityException {
3808        throwIfParentInstance("setCertInstallerPackage");
3809        if (mService != null) {
3810            try {
3811                mService.setCertInstallerPackage(admin, installerPackage);
3812            } catch (RemoteException e) {
3813                throw e.rethrowFromSystemServer();
3814            }
3815        }
3816    }
3817
3818    /**
3819     * Called by a profile owner or device owner to retrieve the certificate installer for the user,
3820     * or {@code null} if none is set. If there are multiple delegates this function will return one
3821     * of them.
3822     *
3823     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3824     * @return The package name of the current delegated certificate installer, or {@code null} if
3825     *         none is set.
3826     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3827     *
3828     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
3829     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
3830     */
3831    @Deprecated
3832    public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
3833            throws SecurityException {
3834        throwIfParentInstance("getCertInstallerPackage");
3835        if (mService != null) {
3836            try {
3837                return mService.getCertInstallerPackage(admin);
3838            } catch (RemoteException e) {
3839                throw e.rethrowFromSystemServer();
3840            }
3841        }
3842        return null;
3843    }
3844
3845    /**
3846     * Called by a profile owner or device owner to grant access to privileged APIs to another app.
3847     * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
3848     * constants.
3849     * <p>
3850     * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
3851     * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
3852     * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
3853     * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
3854     * <p>
3855     * Delegated scopes are a per-user state. The delegated access is persistent until it is later
3856     * cleared by calling this method with an empty {@code scopes} list or uninstalling the
3857     * {@code delegatePackage}.
3858     *
3859     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3860     * @param delegatePackage The package name of the app which will be given access.
3861     * @param scopes The groups of privileged APIs whose access should be granted to
3862     *            {@code delegatedPackage}.
3863     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3864     */
3865     public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
3866            @NonNull List<String> scopes) {
3867        throwIfParentInstance("setDelegatedScopes");
3868        if (mService != null) {
3869            try {
3870                mService.setDelegatedScopes(admin, delegatePackage, scopes);
3871            } catch (RemoteException e) {
3872                throw e.rethrowFromSystemServer();
3873            }
3874        }
3875    }
3876
3877    /**
3878     * Called by a profile owner or device owner to retrieve a list of the scopes given to a
3879     * delegate package. Other apps can use this method to retrieve their own delegated scopes by
3880     * passing {@code null} for {@code admin} and their own package name as
3881     * {@code delegatedPackage}.
3882     *
3883     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3884     *            {@code null} if the caller is {@code delegatedPackage}.
3885     * @param delegatedPackage The package name of the app whose scopes should be retrieved.
3886     * @return A list containing the scopes given to {@code delegatedPackage}.
3887     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3888     */
3889     @NonNull
3890     public List<String> getDelegatedScopes(@Nullable ComponentName admin,
3891             @NonNull String delegatedPackage) {
3892         throwIfParentInstance("getDelegatedScopes");
3893         if (mService != null) {
3894             try {
3895                 return mService.getDelegatedScopes(admin, delegatedPackage);
3896             } catch (RemoteException e) {
3897                 throw e.rethrowFromSystemServer();
3898             }
3899         }
3900         return null;
3901    }
3902
3903    /**
3904     * Called by a profile owner or device owner to retrieve a list of delegate packages that were
3905     * granted a delegation scope.
3906     *
3907     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3908     * @param delegationScope The scope whose delegates should be retrieved.
3909     * @return A list of package names of the current delegated packages for
3910               {@code delegationScope}.
3911     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3912     */
3913     @Nullable
3914     public List<String> getDelegatePackages(@NonNull ComponentName admin,
3915             @NonNull String delegationScope) {
3916        throwIfParentInstance("getDelegatePackages");
3917        if (mService != null) {
3918            try {
3919                return mService.getDelegatePackages(admin, delegationScope);
3920            } catch (RemoteException e) {
3921                throw e.rethrowFromSystemServer();
3922            }
3923        }
3924        return null;
3925    }
3926
3927    /**
3928     * Called by a device or profile owner to configure an always-on VPN connection through a
3929     * specific application for the current user.
3930     *
3931     * @deprecated this version only exists for compability with previous developer preview builds.
3932     *             TODO: delete once there are no longer any live references.
3933     * @hide
3934     */
3935    @Deprecated
3936    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage)
3937            throws NameNotFoundException, UnsupportedOperationException {
3938        setAlwaysOnVpnPackage(admin, vpnPackage, /* lockdownEnabled */ true);
3939    }
3940
3941    /**
3942     * Called by a device or profile owner to configure an always-on VPN connection through a
3943     * specific application for the current user. This connection is automatically granted and
3944     * persisted after a reboot.
3945     * <p>
3946     * The designated package should declare a {@link android.net.VpnService} in its manifest
3947     * guarded by {@link android.Manifest.permission#BIND_VPN_SERVICE}, otherwise the call will
3948     * fail.
3949     *
3950     * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
3951     *        remove an existing always-on VPN configuration.
3952     * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
3953     *        {@code false} otherwise. This carries the risk that any failure of the VPN provider
3954     *        could break networking for all apps. This has no effect when clearing.
3955     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3956     * @throws NameNotFoundException if {@code vpnPackage} is not installed.
3957     * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
3958     *         set as always-on, or if always-on VPN is not available.
3959     */
3960    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
3961            boolean lockdownEnabled)
3962            throws NameNotFoundException, UnsupportedOperationException {
3963        throwIfParentInstance("setAlwaysOnVpnPackage");
3964        if (mService != null) {
3965            try {
3966                if (!mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled)) {
3967                    throw new NameNotFoundException(vpnPackage);
3968                }
3969            } catch (RemoteException e) {
3970                throw e.rethrowFromSystemServer();
3971            }
3972        }
3973    }
3974
3975    /**
3976     * Called by a device or profile owner to read the name of the package administering an
3977     * always-on VPN connection for the current user. If there is no such package, or the always-on
3978     * VPN is provided by the system instead of by an application, {@code null} will be returned.
3979     *
3980     * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
3981     *         is set.
3982     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3983     */
3984    public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
3985        throwIfParentInstance("getAlwaysOnVpnPackage");
3986        if (mService != null) {
3987            try {
3988                return mService.getAlwaysOnVpnPackage(admin);
3989            } catch (RemoteException e) {
3990                throw e.rethrowFromSystemServer();
3991            }
3992        }
3993        return null;
3994    }
3995
3996    /**
3997     * Called by an application that is administering the device to disable all cameras on the
3998     * device, for this user. After setting this, no applications running as this user will be able
3999     * to access any cameras on the device.
4000     * <p>
4001     * If the caller is device owner, then the restriction will be applied to all users.
4002     * <p>
4003     * The calling device admin must have requested
4004     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
4005     * not, a security exception will be thrown.
4006     *
4007     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4008     * @param disabled Whether or not the camera should be disabled.
4009     * @throws SecurityException if {@code admin} is not an active administrator or does not use
4010     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
4011     */
4012    public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
4013        throwIfParentInstance("setCameraDisabled");
4014        if (mService != null) {
4015            try {
4016                mService.setCameraDisabled(admin, disabled);
4017            } catch (RemoteException e) {
4018                throw e.rethrowFromSystemServer();
4019            }
4020        }
4021    }
4022
4023    /**
4024     * Determine whether or not the device's cameras have been disabled for this user,
4025     * either by the calling admin, if specified, or all admins.
4026     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4027     * have disabled the camera
4028     */
4029    public boolean getCameraDisabled(@Nullable ComponentName admin) {
4030        throwIfParentInstance("getCameraDisabled");
4031        return getCameraDisabled(admin, myUserId());
4032    }
4033
4034    /** @hide per-user version */
4035    public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
4036        if (mService != null) {
4037            try {
4038                return mService.getCameraDisabled(admin, userHandle);
4039            } catch (RemoteException e) {
4040                throw e.rethrowFromSystemServer();
4041            }
4042        }
4043        return false;
4044    }
4045
4046    /**
4047     * Called by a device owner to request a bugreport.
4048     * <p>
4049     * If the device contains secondary users or profiles, they must be affiliated with the device
4050     * owner user. Otherwise a {@link SecurityException} will be thrown. See
4051     * {@link #setAffiliationIds}.
4052     *
4053     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4054     * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
4055     *         wasn't triggered because a previous bugreport operation is still active (either the
4056     *         bugreport is still running or waiting for the user to share or decline)
4057     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
4058     *         profile or secondary user that is not affiliated with the device owner user.
4059     */
4060    public boolean requestBugreport(@NonNull ComponentName admin) {
4061        throwIfParentInstance("requestBugreport");
4062        if (mService != null) {
4063            try {
4064                return mService.requestBugreport(admin);
4065            } catch (RemoteException e) {
4066                throw e.rethrowFromSystemServer();
4067            }
4068        }
4069        return false;
4070    }
4071
4072    /**
4073     * Determine whether or not creating a guest user has been disabled for the device
4074     *
4075     * @hide
4076     */
4077    public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
4078        // Currently guest users can always be created if multi-user is enabled
4079        // TODO introduce a policy for guest user creation
4080        return false;
4081    }
4082
4083    /**
4084     * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
4085     * screen capture also prevents the content from being shown on display devices that do not have
4086     * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
4087     * secure surfaces and secure displays.
4088     * <p>
4089     * The calling device admin must be a device or profile owner. If it is not, a security
4090     * exception will be thrown.
4091     * <p>
4092     * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
4093     * assist requests for all activities of the relevant user.
4094     *
4095     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4096     * @param disabled Whether screen capture is disabled or not.
4097     * @throws SecurityException if {@code admin} is not a device or profile owner.
4098     */
4099    public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
4100        throwIfParentInstance("setScreenCaptureDisabled");
4101        if (mService != null) {
4102            try {
4103                mService.setScreenCaptureDisabled(admin, disabled);
4104            } catch (RemoteException e) {
4105                throw e.rethrowFromSystemServer();
4106            }
4107        }
4108    }
4109
4110    /**
4111     * Determine whether or not screen capture has been disabled by the calling
4112     * admin, if specified, or all admins.
4113     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4114     * have disabled screen capture.
4115     */
4116    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
4117        throwIfParentInstance("getScreenCaptureDisabled");
4118        return getScreenCaptureDisabled(admin, myUserId());
4119    }
4120
4121    /** @hide per-user version */
4122    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
4123        if (mService != null) {
4124            try {
4125                return mService.getScreenCaptureDisabled(admin, userHandle);
4126            } catch (RemoteException e) {
4127                throw e.rethrowFromSystemServer();
4128            }
4129        }
4130        return false;
4131    }
4132
4133    /**
4134     * Called by a device or profile owner to set whether auto time is required. If auto time is
4135     * required, no user will be able set the date and time and network date and time will be used.
4136     * <p>
4137     * Note: if auto time is required the user can still manually set the time zone.
4138     * <p>
4139     * The calling device admin must be a device or profile owner. If it is not, a security
4140     * exception will be thrown.
4141     *
4142     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4143     * @param required Whether auto time is set required or not.
4144     * @throws SecurityException if {@code admin} is not a device owner.
4145     */
4146    public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
4147        throwIfParentInstance("setAutoTimeRequired");
4148        if (mService != null) {
4149            try {
4150                mService.setAutoTimeRequired(admin, required);
4151            } catch (RemoteException e) {
4152                throw e.rethrowFromSystemServer();
4153            }
4154        }
4155    }
4156
4157    /**
4158     * @return true if auto time is required.
4159     */
4160    public boolean getAutoTimeRequired() {
4161        throwIfParentInstance("getAutoTimeRequired");
4162        if (mService != null) {
4163            try {
4164                return mService.getAutoTimeRequired();
4165            } catch (RemoteException e) {
4166                throw e.rethrowFromSystemServer();
4167            }
4168        }
4169        return false;
4170    }
4171
4172    /**
4173     * Called by a device owner to set whether all users created on the device should be ephemeral.
4174     * <p>
4175     * The system user is exempt from this policy - it is never ephemeral.
4176     * <p>
4177     * The calling device admin must be the device owner. If it is not, a security exception will be
4178     * thrown.
4179     *
4180     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4181     * @param forceEphemeralUsers If true, all the existing users will be deleted and all
4182     *            subsequently created users will be ephemeral.
4183     * @throws SecurityException if {@code admin} is not a device owner.
4184     * @hide
4185     */
4186    public void setForceEphemeralUsers(
4187            @NonNull ComponentName admin, boolean forceEphemeralUsers) {
4188        throwIfParentInstance("setForceEphemeralUsers");
4189        if (mService != null) {
4190            try {
4191                mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
4192            } catch (RemoteException e) {
4193                throw e.rethrowFromSystemServer();
4194            }
4195        }
4196    }
4197
4198    /**
4199     * @return true if all users are created ephemeral.
4200     * @throws SecurityException if {@code admin} is not a device owner.
4201     * @hide
4202     */
4203    public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
4204        throwIfParentInstance("getForceEphemeralUsers");
4205        if (mService != null) {
4206            try {
4207                return mService.getForceEphemeralUsers(admin);
4208            } catch (RemoteException e) {
4209                throw e.rethrowFromSystemServer();
4210            }
4211        }
4212        return false;
4213    }
4214
4215    /**
4216     * Called by an application that is administering the device to disable keyguard customizations,
4217     * such as widgets. After setting this, keyguard features will be disabled according to the
4218     * provided feature list.
4219     * <p>
4220     * The calling device admin must have requested
4221     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
4222     * if it has not, a security exception will be thrown.
4223     * <p>
4224     * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
4225     * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
4226     * profile owner of a managed profile can set:
4227     * <ul>
4228     * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
4229     * is no separate challenge set on the managed profile.
4230     * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT} which affects the managed profile challenge if
4231     * there is one, or the parent user otherwise.
4232     * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
4233     * by applications in the managed profile.
4234     * </ul>
4235     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and {@link #KEYGUARD_DISABLE_FINGERPRINT} can also be
4236     * set on the {@link DevicePolicyManager} instance returned by
4237     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4238     * profile.
4239     * <p>
4240     * Requests to disable other features on a managed profile will be ignored.
4241     * <p>
4242     * The admin can check which features have been disabled by calling
4243     * {@link #getKeyguardDisabledFeatures(ComponentName)}
4244     *
4245     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4246     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
4247     *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
4248     *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
4249     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
4250     *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
4251     *            {@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
4252     * @throws SecurityException if {@code admin} is not an active administrator or does not user
4253     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
4254     */
4255    public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
4256        if (mService != null) {
4257            try {
4258                mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
4259            } catch (RemoteException e) {
4260                throw e.rethrowFromSystemServer();
4261            }
4262        }
4263    }
4264
4265    /**
4266     * Determine whether or not features have been disabled in keyguard either by the calling
4267     * admin, if specified, or all admins that set restrictions on this user and its participating
4268     * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
4269     *
4270     * <p>This method can be called on the {@link DevicePolicyManager} instance
4271     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4272     * restrictions on the parent profile.
4273     *
4274     * @param admin The name of the admin component to check, or {@code null} to check whether any
4275     * admins have disabled features in keyguard.
4276     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
4277     * for a list.
4278     */
4279    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
4280        return getKeyguardDisabledFeatures(admin, myUserId());
4281    }
4282
4283    /** @hide per-user version */
4284    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
4285        if (mService != null) {
4286            try {
4287                return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
4288            } catch (RemoteException e) {
4289                throw e.rethrowFromSystemServer();
4290            }
4291        }
4292        return KEYGUARD_DISABLE_FEATURES_NONE;
4293    }
4294
4295    /**
4296     * @hide
4297     */
4298    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
4299            int userHandle) {
4300        if (mService != null) {
4301            try {
4302                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
4303            } catch (RemoteException e) {
4304                throw e.rethrowFromSystemServer();
4305            }
4306        }
4307    }
4308
4309    /**
4310     * @hide
4311     */
4312    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
4313        setActiveAdmin(policyReceiver, refreshing, myUserId());
4314    }
4315
4316    /**
4317     * @hide
4318     */
4319    public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
4320        if (mService != null) {
4321            try {
4322                mService.getRemoveWarning(admin, result, myUserId());
4323            } catch (RemoteException e) {
4324                throw e.rethrowFromSystemServer();
4325            }
4326        }
4327    }
4328
4329    /**
4330     * @hide
4331     */
4332    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
4333        if (mService != null) {
4334            try {
4335                mService.setActivePasswordState(metrics, userHandle);
4336            } catch (RemoteException e) {
4337                throw e.rethrowFromSystemServer();
4338            }
4339        }
4340    }
4341
4342    /**
4343     * @hide
4344     */
4345    public void reportPasswordChanged(@UserIdInt int userId) {
4346        if (mService != null) {
4347            try {
4348                mService.reportPasswordChanged(userId);
4349            } catch (RemoteException e) {
4350                throw e.rethrowFromSystemServer();
4351            }
4352        }
4353    }
4354
4355    /**
4356     * @hide
4357     */
4358    public void reportFailedPasswordAttempt(int userHandle) {
4359        if (mService != null) {
4360            try {
4361                mService.reportFailedPasswordAttempt(userHandle);
4362            } catch (RemoteException e) {
4363                throw e.rethrowFromSystemServer();
4364            }
4365        }
4366    }
4367
4368    /**
4369     * @hide
4370     */
4371    public void reportSuccessfulPasswordAttempt(int userHandle) {
4372        if (mService != null) {
4373            try {
4374                mService.reportSuccessfulPasswordAttempt(userHandle);
4375            } catch (RemoteException e) {
4376                throw e.rethrowFromSystemServer();
4377            }
4378        }
4379    }
4380
4381    /**
4382     * @hide
4383     */
4384    public void reportFailedFingerprintAttempt(int userHandle) {
4385        if (mService != null) {
4386            try {
4387                mService.reportFailedFingerprintAttempt(userHandle);
4388            } catch (RemoteException e) {
4389                throw e.rethrowFromSystemServer();
4390            }
4391        }
4392    }
4393
4394    /**
4395     * @hide
4396     */
4397    public void reportSuccessfulFingerprintAttempt(int userHandle) {
4398        if (mService != null) {
4399            try {
4400                mService.reportSuccessfulFingerprintAttempt(userHandle);
4401            } catch (RemoteException e) {
4402                throw e.rethrowFromSystemServer();
4403            }
4404        }
4405    }
4406
4407    /**
4408     * Should be called when keyguard has been dismissed.
4409     * @hide
4410     */
4411    public void reportKeyguardDismissed(int userHandle) {
4412        if (mService != null) {
4413            try {
4414                mService.reportKeyguardDismissed(userHandle);
4415            } catch (RemoteException e) {
4416                throw e.rethrowFromSystemServer();
4417            }
4418        }
4419    }
4420
4421    /**
4422     * Should be called when keyguard view has been shown to the user.
4423     * @hide
4424     */
4425    public void reportKeyguardSecured(int userHandle) {
4426        if (mService != null) {
4427            try {
4428                mService.reportKeyguardSecured(userHandle);
4429            } catch (RemoteException e) {
4430                throw e.rethrowFromSystemServer();
4431            }
4432        }
4433    }
4434
4435    /**
4436     * @hide
4437     * Sets the given package as the device owner.
4438     * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
4439     * @param who the component name to be registered as device owner.
4440     * @return whether the package was successfully registered as the device owner.
4441     * @throws IllegalArgumentException if the package name is null or invalid
4442     * @throws IllegalStateException If the preconditions mentioned are not met.
4443     */
4444    public boolean setDeviceOwner(ComponentName who) {
4445        return setDeviceOwner(who, null);
4446    }
4447
4448    /**
4449     * @hide
4450     */
4451    public boolean setDeviceOwner(ComponentName who, int userId)  {
4452        return setDeviceOwner(who, null, userId);
4453    }
4454
4455    /**
4456     * @hide
4457     */
4458    public boolean setDeviceOwner(ComponentName who, String ownerName) {
4459        return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
4460    }
4461
4462    /**
4463     * @hide
4464     * Sets the given package as the device owner. The package must already be installed. There
4465     * must not already be a device owner.
4466     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
4467     * this method.
4468     * Calling this after the setup phase of the primary user has completed is allowed only if
4469     * the caller is the shell uid, and there are no additional users and no accounts.
4470     * @param who the component name to be registered as device owner.
4471     * @param ownerName the human readable name of the institution that owns this device.
4472     * @param userId ID of the user on which the device owner runs.
4473     * @return whether the package was successfully registered as the device owner.
4474     * @throws IllegalArgumentException if the package name is null or invalid
4475     * @throws IllegalStateException If the preconditions mentioned are not met.
4476     */
4477    public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
4478            throws IllegalArgumentException, IllegalStateException {
4479        if (mService != null) {
4480            try {
4481                return mService.setDeviceOwner(who, ownerName, userId);
4482            } catch (RemoteException re) {
4483                throw re.rethrowFromSystemServer();
4484            }
4485        }
4486        return false;
4487    }
4488
4489    /**
4490     * Used to determine if a particular package has been registered as a Device Owner app.
4491     * A device owner app is a special device admin that cannot be deactivated by the user, once
4492     * activated as a device admin. It also cannot be uninstalled. To check whether a particular
4493     * package is currently registered as the device owner app, pass in the package name from
4494     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
4495     * admin apps that want to check whether they are also registered as the device owner app. The
4496     * exact mechanism by which a device admin app is registered as a device owner app is defined by
4497     * the setup process.
4498     * @param packageName the package name of the app, to compare with the registered device owner
4499     * app, if any.
4500     * @return whether or not the package is registered as the device owner app.
4501     */
4502    public boolean isDeviceOwnerApp(String packageName) {
4503        throwIfParentInstance("isDeviceOwnerApp");
4504        return isDeviceOwnerAppOnCallingUser(packageName);
4505    }
4506
4507    /**
4508     * @return true if a package is registered as device owner, only when it's running on the
4509     * calling user.
4510     *
4511     * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
4512     * @hide
4513     */
4514    public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
4515        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
4516    }
4517
4518    /**
4519     * @return true if a package is registered as device owner, even if it's running on a different
4520     * user.
4521     *
4522     * <p>Requires the MANAGE_USERS permission.
4523     *
4524     * @hide
4525     */
4526    public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
4527        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
4528    }
4529
4530    /**
4531     * @return device owner component name, only when it's running on the calling user.
4532     *
4533     * @hide
4534     */
4535    public ComponentName getDeviceOwnerComponentOnCallingUser() {
4536        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
4537    }
4538
4539    /**
4540     * @return device owner component name, even if it's running on a different user.
4541     *
4542     * <p>Requires the MANAGE_USERS permission.
4543     *
4544     * @hide
4545     */
4546    @SystemApi
4547    public ComponentName getDeviceOwnerComponentOnAnyUser() {
4548        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
4549    }
4550
4551    private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
4552        if (packageName == null) {
4553            return false;
4554        }
4555        final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
4556        if (deviceOwner == null) {
4557            return false;
4558        }
4559        return packageName.equals(deviceOwner.getPackageName());
4560    }
4561
4562    private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
4563        if (mService != null) {
4564            try {
4565                return mService.getDeviceOwnerComponent(callingUserOnly);
4566            } catch (RemoteException re) {
4567                throw re.rethrowFromSystemServer();
4568            }
4569        }
4570        return null;
4571    }
4572
4573    /**
4574     * @return ID of the user who runs device owner, or {@link UserHandle#USER_NULL} if there's
4575     * no device owner.
4576     *
4577     * <p>Requires the MANAGE_USERS permission.
4578     *
4579     * @hide
4580     */
4581    public int getDeviceOwnerUserId() {
4582        if (mService != null) {
4583            try {
4584                return mService.getDeviceOwnerUserId();
4585            } catch (RemoteException re) {
4586                throw re.rethrowFromSystemServer();
4587            }
4588        }
4589        return UserHandle.USER_NULL;
4590    }
4591
4592    /**
4593     * Clears the current device owner. The caller must be the device owner. This function should be
4594     * used cautiously as once it is called it cannot be undone. The device owner can only be set as
4595     * a part of device setup, before it completes.
4596     * <p>
4597     * While some policies previously set by the device owner will be cleared by this method, it is
4598     * a best-effort process and some other policies will still remain in place after the device
4599     * owner is cleared.
4600     *
4601     * @param packageName The package name of the device owner.
4602     * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
4603     *             does not own the current device owner component.
4604     *
4605     * @deprecated This method is expected to be used for testing purposes only. The device owner
4606     * will lose control of the device and its data after calling it. In order to protect any
4607     * sensitive data that remains on the device, it is advised that the device owner factory resets
4608     * the device instead of calling this method. See {@link #wipeData(int)}.
4609     */
4610    @Deprecated
4611    public void clearDeviceOwnerApp(String packageName) {
4612        throwIfParentInstance("clearDeviceOwnerApp");
4613        if (mService != null) {
4614            try {
4615                mService.clearDeviceOwner(packageName);
4616            } catch (RemoteException re) {
4617                throw re.rethrowFromSystemServer();
4618            }
4619        }
4620    }
4621
4622    /**
4623     * Returns the device owner package name, only if it's running on the calling user.
4624     *
4625     * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
4626     *
4627     * @hide
4628     */
4629    @SystemApi
4630    public @Nullable String getDeviceOwner() {
4631        throwIfParentInstance("getDeviceOwner");
4632        final ComponentName name = getDeviceOwnerComponentOnCallingUser();
4633        return name != null ? name.getPackageName() : null;
4634    }
4635
4636    /**
4637     * Called by the system to find out whether the device is managed by a Device Owner.
4638     *
4639     * @return whether the device is managed by a Device Owner.
4640     * @throws SecurityException if the caller is not the device owner, does not hold the
4641     *         MANAGE_USERS permission and is not the system.
4642     *
4643     * @hide
4644     */
4645    @SystemApi
4646    @TestApi
4647    public boolean isDeviceManaged() {
4648        try {
4649            return mService.hasDeviceOwner();
4650        } catch (RemoteException re) {
4651            throw re.rethrowFromSystemServer();
4652        }
4653    }
4654
4655    /**
4656     * Returns the device owner name.  Note this method *will* return the device owner
4657     * name when it's running on a different user.
4658     *
4659     * <p>Requires the MANAGE_USERS permission.
4660     *
4661     * @hide
4662     */
4663    @SystemApi
4664    public String getDeviceOwnerNameOnAnyUser() {
4665        throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
4666        if (mService != null) {
4667            try {
4668                return mService.getDeviceOwnerName();
4669            } catch (RemoteException re) {
4670                throw re.rethrowFromSystemServer();
4671            }
4672        }
4673        return null;
4674    }
4675
4676    /**
4677     * @hide
4678     * @deprecated Do not use
4679     * @removed
4680     */
4681    @Deprecated
4682    @SystemApi
4683    public @Nullable String getDeviceInitializerApp() {
4684        return null;
4685    }
4686
4687    /**
4688     * @hide
4689     * @deprecated Do not use
4690     * @removed
4691     */
4692    @Deprecated
4693    @SystemApi
4694    public @Nullable ComponentName getDeviceInitializerComponent() {
4695        return null;
4696    }
4697
4698    /**
4699     * @hide
4700     * @deprecated Use #ACTION_SET_PROFILE_OWNER
4701     * Sets the given component as an active admin and registers the package as the profile
4702     * owner for this user. The package must already be installed and there shouldn't be
4703     * an existing profile owner registered for this user. Also, this method must be called
4704     * before the user setup has been completed.
4705     * <p>
4706     * This method can only be called by system apps that hold MANAGE_USERS permission and
4707     * MANAGE_DEVICE_ADMINS permission.
4708     * @param admin The component to register as an active admin and profile owner.
4709     * @param ownerName The user-visible name of the entity that is managing this user.
4710     * @return whether the admin was successfully registered as the profile owner.
4711     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
4712     *         the user has already been set up.
4713     */
4714    @Deprecated
4715    @SystemApi
4716    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     * The caller must hold {@link android.Manifest.permission#NOTIFY_PENDING_SYSTEM_UPDATE}
6804     * permission. This method should only be used when it is unknown whether the pending system
6805     * update is a security patch. Otherwise, use
6806     * {@link #notifyPendingSystemUpdate(long, boolean)}.
6807     *
6808     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
6809     *         indicating when the current pending update was first available. {@code -1} if no
6810     *         update is available.
6811     * @see #notifyPendingSystemUpdate(long, boolean)
6812     * @hide
6813     */
6814    @SystemApi
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     * The caller must hold {@link android.Manifest.permission#NOTIFY_PENDING_SYSTEM_UPDATE}
6831     * permission. This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
6832     * when it is known whether the pending system update is a security patch.
6833     *
6834     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
6835     *         indicating when the current pending update was first available. {@code -1} if no
6836     *         update is available.
6837     * @param isSecurityPatch {@code true} if this system update is purely a security patch;
6838     *         {@code false} if not.
6839     * @see #notifyPendingSystemUpdate(long)
6840     * @hide
6841     */
6842    @SystemApi
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     * STOPSHIP (b/37622682) Remove it before release.
7640     * @removed
7641     */
7642    public void setAffiliationIds(@NonNull ComponentName admin, @NonNull List<String> ids) {
7643        throwIfParentInstance("setAffiliationIds");
7644        if (ids == null) {
7645            throw new IllegalArgumentException("ids must not be null");
7646        }
7647        try {
7648            mService.setAffiliationIds(admin, ids);
7649        } catch (RemoteException e) {
7650            throw e.rethrowFromSystemServer();
7651        }
7652    }
7653
7654    /**
7655     * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
7656     * empty set if none have been set.
7657     */
7658    public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
7659        throwIfParentInstance("getAffiliationIds");
7660        try {
7661            return new ArraySet<>(mService.getAffiliationIds(admin));
7662        } catch (RemoteException e) {
7663            throw e.rethrowFromSystemServer();
7664        }
7665    }
7666
7667    /**
7668     * @hide
7669     * Returns whether this user/profile is affiliated with the device.
7670     * <p>
7671     * By definition, the user that the device owner runs on is always affiliated with the device.
7672     * Any other user/profile is considered affiliated with the device if the set specified by its
7673     * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
7674     *
7675     */
7676    public boolean isAffiliatedUser() {
7677        throwIfParentInstance("isAffiliatedUser");
7678        try {
7679            return mService.isAffiliatedUser();
7680        } catch (RemoteException e) {
7681            throw e.rethrowFromSystemServer();
7682        }
7683    }
7684
7685    /**
7686     * @hide
7687     * Returns whether the uninstall for {@code packageName} for the current user is in queue
7688     * to be started
7689     * @param packageName the package to check for
7690     * @return whether the uninstall intent for {@code packageName} is pending
7691     */
7692    public boolean isUninstallInQueue(String packageName) {
7693        try {
7694            return mService.isUninstallInQueue(packageName);
7695        } catch (RemoteException re) {
7696            throw re.rethrowFromSystemServer();
7697        }
7698    }
7699
7700    /**
7701     * @hide
7702     * @param packageName the package containing active DAs to be uninstalled
7703     */
7704    public void uninstallPackageWithActiveAdmins(String packageName) {
7705        try {
7706            mService.uninstallPackageWithActiveAdmins(packageName);
7707        } catch (RemoteException re) {
7708            throw re.rethrowFromSystemServer();
7709        }
7710    }
7711
7712    /**
7713     * @hide
7714     * Remove a test admin synchronously without sending it a broadcast about being removed.
7715     * If the admin is a profile owner or device owner it will still be removed.
7716     *
7717     * @param userHandle user id to remove the admin for.
7718     * @param admin The administration compononent to remove.
7719     * @throws SecurityException if the caller is not shell / root or the admin package
7720     *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
7721     */
7722    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
7723        try {
7724            mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
7725        } catch (RemoteException re) {
7726            throw re.rethrowFromSystemServer();
7727        }
7728    }
7729
7730    /**
7731     * Returns whether the device has been provisioned.
7732     *
7733     * <p>Not for use by third-party applications.
7734     *
7735     * @hide
7736     */
7737    @SystemApi
7738    public boolean isDeviceProvisioned() {
7739        try {
7740            return mService.isDeviceProvisioned();
7741        } catch (RemoteException re) {
7742            throw re.rethrowFromSystemServer();
7743        }
7744    }
7745
7746    /**
7747      * Writes that the provisioning configuration has been applied.
7748      *
7749      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
7750      * permission.
7751      *
7752      * <p>Not for use by third-party applications.
7753      *
7754      * @hide
7755      */
7756    @SystemApi
7757    public void setDeviceProvisioningConfigApplied() {
7758        try {
7759            mService.setDeviceProvisioningConfigApplied();
7760        } catch (RemoteException re) {
7761            throw re.rethrowFromSystemServer();
7762        }
7763    }
7764
7765    /**
7766     * Returns whether the provisioning configuration has been applied.
7767     *
7768     * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
7769     *
7770     * <p>Not for use by third-party applications.
7771     *
7772     * @return whether the provisioning configuration has been applied.
7773     *
7774     * @hide
7775     */
7776    @SystemApi
7777    public boolean isDeviceProvisioningConfigApplied() {
7778        try {
7779            return mService.isDeviceProvisioningConfigApplied();
7780        } catch (RemoteException re) {
7781            throw re.rethrowFromSystemServer();
7782        }
7783    }
7784
7785    /**
7786     * @hide
7787     * Force update user setup completed status. This API has no effect on user build.
7788     * @throws {@link SecurityException} if the caller has no
7789     *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
7790     *         not {@link UserHandle#SYSTEM_USER}
7791     */
7792    public void forceUpdateUserSetupComplete() {
7793        try {
7794            mService.forceUpdateUserSetupComplete();
7795        } catch (RemoteException re) {
7796            throw re.rethrowFromSystemServer();
7797        }
7798    }
7799
7800    private void throwIfParentInstance(String functionName) {
7801        if (mParentInstance) {
7802            throw new SecurityException(functionName + " cannot be called on the parent instance");
7803        }
7804    }
7805
7806    /**
7807     * Allows the device owner to enable or disable the backup service.
7808     *
7809     * <p> Backup service manages all backup and restore mechanisms on the device. Setting this to
7810     * false will prevent data from being backed up or restored.
7811     *
7812     * <p> Backup service is off by default when device owner is present.
7813     *
7814     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7815     * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
7816     * @throws SecurityException if {@code admin} is not a device owner.
7817     */
7818    public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
7819        throwIfParentInstance("setBackupServiceEnabled");
7820        try {
7821            mService.setBackupServiceEnabled(admin, enabled);
7822        } catch (RemoteException re) {
7823            throw re.rethrowFromSystemServer();
7824        }
7825    }
7826
7827    /**
7828     * Return whether the backup service is enabled by the device owner.
7829     *
7830     * <p> Backup service manages all backup and restore mechanisms on the device.
7831     *
7832     * @return {@code true} if backup service is enabled, {@code false} otherwise.
7833     * @see #setBackupServiceEnabled
7834     */
7835    public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
7836        throwIfParentInstance("isBackupServiceEnabled");
7837        try {
7838            return mService.isBackupServiceEnabled(admin);
7839        } catch (RemoteException re) {
7840            throw re.rethrowFromSystemServer();
7841        }
7842    }
7843
7844    /**
7845     * Called by a device owner to control the network logging feature.
7846     *
7847     * <p> Network logs contain DNS lookup and connect() library call events. The following library
7848     *     functions are recorded while network logging is active:
7849     *     <ul>
7850     *       <li>{@code getaddrinfo()}</li>
7851     *       <li>{@code gethostbyname()}</li>
7852     *       <li>{@code connect()}</li>
7853     *     </ul>
7854     *
7855     * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
7856     *     full system call logging; event reporting is enabled by default for all processes but not
7857     *     strongly enforced.
7858     *     Events from applications using alternative implementations of libc, making direct kernel
7859     *     calls, or deliberately obfuscating traffic may not be recorded.
7860     *
7861     * <p> Some common network events may not be reported. For example:
7862     *     <ul>
7863     *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
7864     *           an alternative system for name resolution, and so avoid calling
7865     *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
7866     *       <li>Applications may use datagram sockets for performance reasons, for example
7867     *           for a game client. Calling {@code connect()} is unnecessary for this kind of
7868     *           socket, so it will not trigger a network event.</li>
7869     *     </ul>
7870     *
7871     * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
7872     *     always-on VPN service.
7873     *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
7874     *     and {@link android.net.VpnService} for details.
7875     *
7876     * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
7877     * are unaffiliated secondary users or profiles on the device, regardless of whether the
7878     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
7879     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
7880     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
7881     *
7882     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7883     * @param enabled whether network logging should be enabled or not.
7884     * @throws SecurityException if {@code admin} is not a device owner.
7885     * @see #retrieveNetworkLogs
7886     */
7887    public void setNetworkLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
7888        throwIfParentInstance("setNetworkLoggingEnabled");
7889        try {
7890            mService.setNetworkLoggingEnabled(admin, enabled);
7891        } catch (RemoteException re) {
7892            throw re.rethrowFromSystemServer();
7893        }
7894    }
7895
7896    /**
7897     * Return whether network logging is enabled by a device owner.
7898     *
7899     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
7900     * be {@code null} if the caller has MANAGE_USERS permission.
7901     * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
7902     * @throws SecurityException if {@code admin} is not a device owner and caller has
7903     * no MANAGE_USERS permission
7904     */
7905    public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
7906        throwIfParentInstance("isNetworkLoggingEnabled");
7907        try {
7908            return mService.isNetworkLoggingEnabled(admin);
7909        } catch (RemoteException re) {
7910            throw re.rethrowFromSystemServer();
7911        }
7912    }
7913
7914    /**
7915     * Called by device owner to retrieve the most recent batch of network logging events.
7916     * A device owner has to provide a batchToken provided as part of
7917     * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
7918     * token of the most recent available batch of logs, {@code null} will be returned.
7919     *
7920     * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
7921     *
7922     * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
7923     *
7924     * <p> Access to the logs is rate limited and this method will only return a new batch of logs
7925     * after the device device owner has been notified via
7926     * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
7927     *
7928     * <p>If a secondary user or profile is created, calling this method will throw a
7929     * {@link SecurityException} until all users become affiliated again. It will also no longer be
7930     * possible to retrieve the network logs batch with the most recent batchToken provided
7931     * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
7932     * {@link DevicePolicyManager#setAffiliationIds}.
7933     *
7934     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7935     * @param batchToken A token of the batch to retrieve
7936     * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
7937     *        {@code null} if the batch represented by batchToken is no longer available or if
7938     *        logging is disabled.
7939     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
7940     * profile or secondary user that is not affiliated with the device owner user.
7941     * @see DeviceAdminReceiver#onNetworkLogsAvailable
7942     */
7943    public @Nullable List<NetworkEvent> retrieveNetworkLogs(@NonNull ComponentName admin,
7944            long batchToken) {
7945        throwIfParentInstance("retrieveNetworkLogs");
7946        try {
7947            return mService.retrieveNetworkLogs(admin, batchToken);
7948        } catch (RemoteException re) {
7949            throw re.rethrowFromSystemServer();
7950        }
7951    }
7952
7953    /**
7954     * Called by a device owner to bind to a service from a profile owner or vice versa.
7955     * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
7956     * device/profile owners are allowed to bind to services of another profile/device owner.
7957     * <p>
7958     * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
7959     * Note that the {@link Context} used to obtain this
7960     * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
7961     * to bind to the {@link android.app.Service}.
7962     *
7963     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7964     * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
7965     *        explicit component name or a package name to match an
7966     *        {@link IntentFilter} published by a service.
7967     * @param conn Receives information as the service is started and stopped in main thread. This
7968     *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
7969     * @param flags Operation options for the binding operation. See
7970     *        {@link Context#bindService(Intent, ServiceConnection, int)}.
7971     * @param targetUser Which user to bind to. Must be one of the users returned by
7972     *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
7973     *        be thrown.
7974     * @return If you have successfully bound to the service, {@code true} is returned;
7975     *         {@code false} is returned if the connection is not made and you will not
7976     *         receive the service object.
7977     *
7978     * @see Context#bindService(Intent, ServiceConnection, int)
7979     * @see #getBindDeviceAdminTargetUsers(ComponentName)
7980     */
7981    public boolean bindDeviceAdminServiceAsUser(
7982            @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
7983            @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
7984        throwIfParentInstance("bindDeviceAdminServiceAsUser");
7985        // Keep this in sync with ContextImpl.bindServiceCommon.
7986        try {
7987            final IServiceConnection sd = mContext.getServiceDispatcher(
7988                    conn, mContext.getMainThreadHandler(), flags);
7989            serviceIntent.prepareToLeaveProcess(mContext);
7990            return mService.bindDeviceAdminServiceAsUser(admin,
7991                    mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
7992                    sd, flags, targetUser.getIdentifier());
7993        } catch (RemoteException re) {
7994            throw re.rethrowFromSystemServer();
7995        }
7996    }
7997
7998    /**
7999     * Returns the list of target users that the calling device or profile owner can use when
8000     * calling {@link #bindDeviceAdminServiceAsUser}.
8001     * <p>
8002     * A device owner can bind to a service from a profile owner and vice versa, provided that:
8003     * <ul>
8004     * <li>Both belong to the same package name.
8005     * <li>Both users are affiliated. See {@link #setAffiliationIds}.
8006     * </ul>
8007     */
8008    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
8009        throwIfParentInstance("getBindDeviceAdminTargetUsers");
8010        try {
8011            return mService.getBindDeviceAdminTargetUsers(admin);
8012        } catch (RemoteException re) {
8013            throw re.rethrowFromSystemServer();
8014        }
8015    }
8016
8017    /**
8018     * Called by the system to get the time at which the device owner last retrieved security
8019     * logging entries.
8020     *
8021     * @return the time at which the device owner most recently retrieved security logging entries,
8022     *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
8023     * @throws SecurityException if the caller is not the device owner, does not hold the
8024     *         MANAGE_USERS permission and is not the system.
8025     *
8026     * @hide
8027     */
8028    @TestApi
8029    public long getLastSecurityLogRetrievalTime() {
8030        try {
8031            return mService.getLastSecurityLogRetrievalTime();
8032        } catch (RemoteException re) {
8033            throw re.rethrowFromSystemServer();
8034        }
8035    }
8036
8037    /**
8038     * Called by the system to get the time at which the device owner last requested a bug report.
8039     *
8040     * @return the time at which the device owner most recently requested a bug report, in
8041     *         milliseconds since epoch; -1 if a bug report was never requested.
8042     * @throws SecurityException if the caller is not the device owner, does not hold the
8043     *         MANAGE_USERS permission and is not the system.
8044     *
8045     * @hide
8046     */
8047    @TestApi
8048    public long getLastBugReportRequestTime() {
8049        try {
8050            return mService.getLastBugReportRequestTime();
8051        } catch (RemoteException re) {
8052            throw re.rethrowFromSystemServer();
8053        }
8054    }
8055
8056    /**
8057     * Called by the system to get the time at which the device owner last retrieved network logging
8058     * events.
8059     *
8060     * @return the time at which the device owner most recently retrieved network logging events, in
8061     *         milliseconds since epoch; -1 if network logging events were never retrieved.
8062     * @throws SecurityException if the caller is not the device owner, does not hold the
8063     *         MANAGE_USERS permission and is not the system.
8064     *
8065     * @hide
8066     */
8067    @TestApi
8068    public long getLastNetworkLogRetrievalTime() {
8069        try {
8070            return mService.getLastNetworkLogRetrievalTime();
8071        } catch (RemoteException re) {
8072            throw re.rethrowFromSystemServer();
8073        }
8074    }
8075
8076    /**
8077     * Called by the system to find out whether the current user's IME was set by the device/profile
8078     * owner or the user.
8079     *
8080     * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
8081     *         otherwise.
8082     * @throws SecurityException if the caller is not the device owner/profile owner.
8083     *
8084     * @hide
8085     */
8086    @TestApi
8087    public boolean isCurrentInputMethodSetByOwner() {
8088        try {
8089            return mService.isCurrentInputMethodSetByOwner();
8090        } catch (RemoteException re) {
8091            throw re.rethrowFromSystemServer();
8092        }
8093    }
8094
8095    /**
8096     * Called by the system to get a list of CA certificates that were installed by the device or
8097     * profile owner.
8098     *
8099     * <p> The caller must be the target user's device owner/profile Owner or hold the
8100     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
8101     *
8102     * @param user The user for whom to retrieve information.
8103     * @return list of aliases identifying CA certificates installed by the device or profile owner
8104     * @throws SecurityException if the caller does not have permission to retrieve information
8105     *         about the given user's CA certificates.
8106     *
8107     * @hide
8108     */
8109    @TestApi
8110    public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
8111        try {
8112            return mService.getOwnerInstalledCaCerts(user).getList();
8113        } catch (RemoteException re) {
8114            throw re.rethrowFromSystemServer();
8115        }
8116    }
8117}
8118