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