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