DevicePolicyManager.java revision d019d4c3156237d8bf2a993070331f61628c1046
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.
3933     *
3934     * @deprecated this version only exists for compability with previous developer preview builds.
3935     *             TODO: delete once there are no longer any live references.
3936     * @hide
3937     */
3938    @Deprecated
3939    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage)
3940            throws NameNotFoundException, UnsupportedOperationException {
3941        setAlwaysOnVpnPackage(admin, vpnPackage, /* lockdownEnabled */ true);
3942    }
3943
3944    /**
3945     * Called by a device or profile owner to configure an always-on VPN connection through a
3946     * specific application for the current user. This connection is automatically granted and
3947     * persisted after a reboot.
3948     * <p>
3949     * The designated package should declare a {@link android.net.VpnService} in its manifest
3950     * guarded by {@link android.Manifest.permission#BIND_VPN_SERVICE}, otherwise the call will
3951     * fail.
3952     *
3953     * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
3954     *        remove an existing always-on VPN configuration.
3955     * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
3956     *        {@code false} otherwise. This carries the risk that any failure of the VPN provider
3957     *        could break networking for all apps. This has no effect when clearing.
3958     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3959     * @throws NameNotFoundException if {@code vpnPackage} is not installed.
3960     * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
3961     *         set as always-on, or if always-on VPN is not available.
3962     */
3963    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
3964            boolean lockdownEnabled)
3965            throws NameNotFoundException, UnsupportedOperationException {
3966        throwIfParentInstance("setAlwaysOnVpnPackage");
3967        if (mService != null) {
3968            try {
3969                if (!mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled)) {
3970                    throw new NameNotFoundException(vpnPackage);
3971                }
3972            } catch (RemoteException e) {
3973                throw e.rethrowFromSystemServer();
3974            }
3975        }
3976    }
3977
3978    /**
3979     * Called by a device or profile owner to read the name of the package administering an
3980     * always-on VPN connection for the current user. If there is no such package, or the always-on
3981     * VPN is provided by the system instead of by an application, {@code null} will be returned.
3982     *
3983     * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
3984     *         is set.
3985     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3986     */
3987    public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
3988        throwIfParentInstance("getAlwaysOnVpnPackage");
3989        if (mService != null) {
3990            try {
3991                return mService.getAlwaysOnVpnPackage(admin);
3992            } catch (RemoteException e) {
3993                throw e.rethrowFromSystemServer();
3994            }
3995        }
3996        return null;
3997    }
3998
3999    /**
4000     * Called by an application that is administering the device to disable all cameras on the
4001     * device, for this user. After setting this, no applications running as this user will be able
4002     * to access any cameras on the device.
4003     * <p>
4004     * If the caller is device owner, then the restriction will be applied to all users.
4005     * <p>
4006     * The calling device admin must have requested
4007     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
4008     * not, a security exception will be thrown.
4009     *
4010     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4011     * @param disabled Whether or not the camera should be disabled.
4012     * @throws SecurityException if {@code admin} is not an active administrator or does not use
4013     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
4014     */
4015    public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
4016        throwIfParentInstance("setCameraDisabled");
4017        if (mService != null) {
4018            try {
4019                mService.setCameraDisabled(admin, disabled);
4020            } catch (RemoteException e) {
4021                throw e.rethrowFromSystemServer();
4022            }
4023        }
4024    }
4025
4026    /**
4027     * Determine whether or not the device's cameras have been disabled for this user,
4028     * either by the calling admin, if specified, or all admins.
4029     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4030     * have disabled the camera
4031     */
4032    public boolean getCameraDisabled(@Nullable ComponentName admin) {
4033        throwIfParentInstance("getCameraDisabled");
4034        return getCameraDisabled(admin, myUserId());
4035    }
4036
4037    /** @hide per-user version */
4038    public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
4039        if (mService != null) {
4040            try {
4041                return mService.getCameraDisabled(admin, userHandle);
4042            } catch (RemoteException e) {
4043                throw e.rethrowFromSystemServer();
4044            }
4045        }
4046        return false;
4047    }
4048
4049    /**
4050     * Called by a device owner to request a bugreport.
4051     * <p>
4052     * If the device contains secondary users or profiles, they must be affiliated with the device
4053     * owner user. Otherwise a {@link SecurityException} will be thrown. See
4054     * {@link #setAffiliationIds}.
4055     *
4056     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4057     * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
4058     *         wasn't triggered because a previous bugreport operation is still active (either the
4059     *         bugreport is still running or waiting for the user to share or decline)
4060     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
4061     *         profile or secondary user that is not affiliated with the device owner user.
4062     */
4063    public boolean requestBugreport(@NonNull ComponentName admin) {
4064        throwIfParentInstance("requestBugreport");
4065        if (mService != null) {
4066            try {
4067                return mService.requestBugreport(admin);
4068            } catch (RemoteException e) {
4069                throw e.rethrowFromSystemServer();
4070            }
4071        }
4072        return false;
4073    }
4074
4075    /**
4076     * Determine whether or not creating a guest user has been disabled for the device
4077     *
4078     * @hide
4079     */
4080    public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
4081        // Currently guest users can always be created if multi-user is enabled
4082        // TODO introduce a policy for guest user creation
4083        return false;
4084    }
4085
4086    /**
4087     * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
4088     * screen capture also prevents the content from being shown on display devices that do not have
4089     * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
4090     * secure surfaces and secure displays.
4091     * <p>
4092     * The calling device admin must be a device or profile owner. If it is not, a security
4093     * exception will be thrown.
4094     * <p>
4095     * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
4096     * assist requests for all activities of the relevant user.
4097     *
4098     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4099     * @param disabled Whether screen capture is disabled or not.
4100     * @throws SecurityException if {@code admin} is not a device or profile owner.
4101     */
4102    public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
4103        throwIfParentInstance("setScreenCaptureDisabled");
4104        if (mService != null) {
4105            try {
4106                mService.setScreenCaptureDisabled(admin, disabled);
4107            } catch (RemoteException e) {
4108                throw e.rethrowFromSystemServer();
4109            }
4110        }
4111    }
4112
4113    /**
4114     * Determine whether or not screen capture has been disabled by the calling
4115     * admin, if specified, or all admins.
4116     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4117     * have disabled screen capture.
4118     */
4119    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
4120        throwIfParentInstance("getScreenCaptureDisabled");
4121        return getScreenCaptureDisabled(admin, myUserId());
4122    }
4123
4124    /** @hide per-user version */
4125    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
4126        if (mService != null) {
4127            try {
4128                return mService.getScreenCaptureDisabled(admin, userHandle);
4129            } catch (RemoteException e) {
4130                throw e.rethrowFromSystemServer();
4131            }
4132        }
4133        return false;
4134    }
4135
4136    /**
4137     * Called by a device or profile owner to set whether auto time is required. If auto time is
4138     * required, no user will be able set the date and time and network date and time will be used.
4139     * <p>
4140     * Note: if auto time is required the user can still manually set the time zone.
4141     * <p>
4142     * The calling device admin must be a device or profile owner. If it is not, a security
4143     * exception will be thrown.
4144     *
4145     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4146     * @param required Whether auto time is set required or not.
4147     * @throws SecurityException if {@code admin} is not a device owner.
4148     */
4149    public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
4150        throwIfParentInstance("setAutoTimeRequired");
4151        if (mService != null) {
4152            try {
4153                mService.setAutoTimeRequired(admin, required);
4154            } catch (RemoteException e) {
4155                throw e.rethrowFromSystemServer();
4156            }
4157        }
4158    }
4159
4160    /**
4161     * @return true if auto time is required.
4162     */
4163    public boolean getAutoTimeRequired() {
4164        throwIfParentInstance("getAutoTimeRequired");
4165        if (mService != null) {
4166            try {
4167                return mService.getAutoTimeRequired();
4168            } catch (RemoteException e) {
4169                throw e.rethrowFromSystemServer();
4170            }
4171        }
4172        return false;
4173    }
4174
4175    /**
4176     * Called by a device owner to set whether all users created on the device should be ephemeral.
4177     * <p>
4178     * The system user is exempt from this policy - it is never ephemeral.
4179     * <p>
4180     * The calling device admin must be the device owner. If it is not, a security exception will be
4181     * thrown.
4182     *
4183     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4184     * @param forceEphemeralUsers If true, all the existing users will be deleted and all
4185     *            subsequently created users will be ephemeral.
4186     * @throws SecurityException if {@code admin} is not a device owner.
4187     * @hide
4188     */
4189    public void setForceEphemeralUsers(
4190            @NonNull ComponentName admin, boolean forceEphemeralUsers) {
4191        throwIfParentInstance("setForceEphemeralUsers");
4192        if (mService != null) {
4193            try {
4194                mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
4195            } catch (RemoteException e) {
4196                throw e.rethrowFromSystemServer();
4197            }
4198        }
4199    }
4200
4201    /**
4202     * @return true if all users are created ephemeral.
4203     * @throws SecurityException if {@code admin} is not a device owner.
4204     * @hide
4205     */
4206    public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
4207        throwIfParentInstance("getForceEphemeralUsers");
4208        if (mService != null) {
4209            try {
4210                return mService.getForceEphemeralUsers(admin);
4211            } catch (RemoteException e) {
4212                throw e.rethrowFromSystemServer();
4213            }
4214        }
4215        return false;
4216    }
4217
4218    /**
4219     * Called by an application that is administering the device to disable keyguard customizations,
4220     * such as widgets. After setting this, keyguard features will be disabled according to the
4221     * provided feature list.
4222     * <p>
4223     * The calling device admin must have requested
4224     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
4225     * if it has not, a security exception will be thrown.
4226     * <p>
4227     * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
4228     * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
4229     * profile owner of a managed profile can set:
4230     * <ul>
4231     * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
4232     * is no separate challenge set on the managed profile.
4233     * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT} which affects the managed profile challenge if
4234     * there is one, or the parent user otherwise.
4235     * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
4236     * by applications in the managed profile.
4237     * </ul>
4238     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and {@link #KEYGUARD_DISABLE_FINGERPRINT} can also be
4239     * set on the {@link DevicePolicyManager} instance returned by
4240     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4241     * profile.
4242     * <p>
4243     * Requests to disable other features on a managed profile will be ignored.
4244     * <p>
4245     * The admin can check which features have been disabled by calling
4246     * {@link #getKeyguardDisabledFeatures(ComponentName)}
4247     *
4248     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4249     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
4250     *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
4251     *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
4252     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
4253     *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
4254     *            {@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
4255     * @throws SecurityException if {@code admin} is not an active administrator or does not user
4256     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
4257     */
4258    public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
4259        if (mService != null) {
4260            try {
4261                mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
4262            } catch (RemoteException e) {
4263                throw e.rethrowFromSystemServer();
4264            }
4265        }
4266    }
4267
4268    /**
4269     * Determine whether or not features have been disabled in keyguard either by the calling
4270     * admin, if specified, or all admins that set restrictions on this user and its participating
4271     * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
4272     *
4273     * <p>This method can be called on the {@link DevicePolicyManager} instance
4274     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4275     * restrictions on the parent profile.
4276     *
4277     * @param admin The name of the admin component to check, or {@code null} to check whether any
4278     * admins have disabled features in keyguard.
4279     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
4280     * for a list.
4281     */
4282    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
4283        return getKeyguardDisabledFeatures(admin, myUserId());
4284    }
4285
4286    /** @hide per-user version */
4287    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
4288        if (mService != null) {
4289            try {
4290                return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
4291            } catch (RemoteException e) {
4292                throw e.rethrowFromSystemServer();
4293            }
4294        }
4295        return KEYGUARD_DISABLE_FEATURES_NONE;
4296    }
4297
4298    /**
4299     * @hide
4300     */
4301    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
4302            int userHandle) {
4303        if (mService != null) {
4304            try {
4305                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
4306            } catch (RemoteException e) {
4307                throw e.rethrowFromSystemServer();
4308            }
4309        }
4310    }
4311
4312    /**
4313     * @hide
4314     */
4315    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
4316        setActiveAdmin(policyReceiver, refreshing, myUserId());
4317    }
4318
4319    /**
4320     * @hide
4321     */
4322    public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
4323        if (mService != null) {
4324            try {
4325                mService.getRemoveWarning(admin, result, myUserId());
4326            } catch (RemoteException e) {
4327                throw e.rethrowFromSystemServer();
4328            }
4329        }
4330    }
4331
4332    /**
4333     * @hide
4334     */
4335    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
4336        if (mService != null) {
4337            try {
4338                mService.setActivePasswordState(metrics, userHandle);
4339            } catch (RemoteException e) {
4340                throw e.rethrowFromSystemServer();
4341            }
4342        }
4343    }
4344
4345    /**
4346     * @hide
4347     */
4348    public void reportPasswordChanged(@UserIdInt int userId) {
4349        if (mService != null) {
4350            try {
4351                mService.reportPasswordChanged(userId);
4352            } catch (RemoteException e) {
4353                throw e.rethrowFromSystemServer();
4354            }
4355        }
4356    }
4357
4358    /**
4359     * @hide
4360     */
4361    public void reportFailedPasswordAttempt(int userHandle) {
4362        if (mService != null) {
4363            try {
4364                mService.reportFailedPasswordAttempt(userHandle);
4365            } catch (RemoteException e) {
4366                throw e.rethrowFromSystemServer();
4367            }
4368        }
4369    }
4370
4371    /**
4372     * @hide
4373     */
4374    public void reportSuccessfulPasswordAttempt(int userHandle) {
4375        if (mService != null) {
4376            try {
4377                mService.reportSuccessfulPasswordAttempt(userHandle);
4378            } catch (RemoteException e) {
4379                throw e.rethrowFromSystemServer();
4380            }
4381        }
4382    }
4383
4384    /**
4385     * @hide
4386     */
4387    public void reportFailedFingerprintAttempt(int userHandle) {
4388        if (mService != null) {
4389            try {
4390                mService.reportFailedFingerprintAttempt(userHandle);
4391            } catch (RemoteException e) {
4392                throw e.rethrowFromSystemServer();
4393            }
4394        }
4395    }
4396
4397    /**
4398     * @hide
4399     */
4400    public void reportSuccessfulFingerprintAttempt(int userHandle) {
4401        if (mService != null) {
4402            try {
4403                mService.reportSuccessfulFingerprintAttempt(userHandle);
4404            } catch (RemoteException e) {
4405                throw e.rethrowFromSystemServer();
4406            }
4407        }
4408    }
4409
4410    /**
4411     * Should be called when keyguard has been dismissed.
4412     * @hide
4413     */
4414    public void reportKeyguardDismissed(int userHandle) {
4415        if (mService != null) {
4416            try {
4417                mService.reportKeyguardDismissed(userHandle);
4418            } catch (RemoteException e) {
4419                throw e.rethrowFromSystemServer();
4420            }
4421        }
4422    }
4423
4424    /**
4425     * Should be called when keyguard view has been shown to the user.
4426     * @hide
4427     */
4428    public void reportKeyguardSecured(int userHandle) {
4429        if (mService != null) {
4430            try {
4431                mService.reportKeyguardSecured(userHandle);
4432            } catch (RemoteException e) {
4433                throw e.rethrowFromSystemServer();
4434            }
4435        }
4436    }
4437
4438    /**
4439     * @hide
4440     * Sets the given package as the device owner.
4441     * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
4442     * @param who the component name to be registered as device owner.
4443     * @return whether the package was successfully registered as the device owner.
4444     * @throws IllegalArgumentException if the package name is null or invalid
4445     * @throws IllegalStateException If the preconditions mentioned are not met.
4446     */
4447    public boolean setDeviceOwner(ComponentName who) {
4448        return setDeviceOwner(who, null);
4449    }
4450
4451    /**
4452     * @hide
4453     */
4454    public boolean setDeviceOwner(ComponentName who, int userId)  {
4455        return setDeviceOwner(who, null, userId);
4456    }
4457
4458    /**
4459     * @hide
4460     */
4461    public boolean setDeviceOwner(ComponentName who, String ownerName) {
4462        return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
4463    }
4464
4465    /**
4466     * @hide
4467     * Sets the given package as the device owner. The package must already be installed. There
4468     * must not already be a device owner.
4469     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
4470     * this method.
4471     * Calling this after the setup phase of the primary user has completed is allowed only if
4472     * the caller is the shell uid, and there are no additional users and no accounts.
4473     * @param who the component name to be registered as device owner.
4474     * @param ownerName the human readable name of the institution that owns this device.
4475     * @param userId ID of the user on which the device owner runs.
4476     * @return whether the package was successfully registered as the device owner.
4477     * @throws IllegalArgumentException if the package name is null or invalid
4478     * @throws IllegalStateException If the preconditions mentioned are not met.
4479     */
4480    public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
4481            throws IllegalArgumentException, IllegalStateException {
4482        if (mService != null) {
4483            try {
4484                return mService.setDeviceOwner(who, ownerName, userId);
4485            } catch (RemoteException re) {
4486                throw re.rethrowFromSystemServer();
4487            }
4488        }
4489        return false;
4490    }
4491
4492    /**
4493     * Used to determine if a particular package has been registered as a Device Owner app.
4494     * A device owner app is a special device admin that cannot be deactivated by the user, once
4495     * activated as a device admin. It also cannot be uninstalled. To check whether a particular
4496     * package is currently registered as the device owner app, pass in the package name from
4497     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
4498     * admin apps that want to check whether they are also registered as the device owner app. The
4499     * exact mechanism by which a device admin app is registered as a device owner app is defined by
4500     * the setup process.
4501     * @param packageName the package name of the app, to compare with the registered device owner
4502     * app, if any.
4503     * @return whether or not the package is registered as the device owner app.
4504     */
4505    public boolean isDeviceOwnerApp(String packageName) {
4506        throwIfParentInstance("isDeviceOwnerApp");
4507        return isDeviceOwnerAppOnCallingUser(packageName);
4508    }
4509
4510    /**
4511     * @return true if a package is registered as device owner, only when it's running on the
4512     * calling user.
4513     *
4514     * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
4515     * @hide
4516     */
4517    public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
4518        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
4519    }
4520
4521    /**
4522     * @return true if a package is registered as device owner, even if it's running on a different
4523     * user.
4524     *
4525     * <p>Requires the MANAGE_USERS permission.
4526     *
4527     * @hide
4528     */
4529    public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
4530        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
4531    }
4532
4533    /**
4534     * @return device owner component name, only when it's running on the calling user.
4535     *
4536     * @hide
4537     */
4538    public ComponentName getDeviceOwnerComponentOnCallingUser() {
4539        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
4540    }
4541
4542    /**
4543     * @return device owner component name, even if it's running on a different user.
4544     *
4545     * @hide
4546     */
4547    @SystemApi
4548    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
4549    public ComponentName getDeviceOwnerComponentOnAnyUser() {
4550        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
4551    }
4552
4553    private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
4554        if (packageName == null) {
4555            return false;
4556        }
4557        final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
4558        if (deviceOwner == null) {
4559            return false;
4560        }
4561        return packageName.equals(deviceOwner.getPackageName());
4562    }
4563
4564    private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
4565        if (mService != null) {
4566            try {
4567                return mService.getDeviceOwnerComponent(callingUserOnly);
4568            } catch (RemoteException re) {
4569                throw re.rethrowFromSystemServer();
4570            }
4571        }
4572        return null;
4573    }
4574
4575    /**
4576     * @return ID of the user who runs device owner, or {@link UserHandle#USER_NULL} if there's
4577     * no device owner.
4578     *
4579     * <p>Requires the MANAGE_USERS permission.
4580     *
4581     * @hide
4582     */
4583    public int getDeviceOwnerUserId() {
4584        if (mService != null) {
4585            try {
4586                return mService.getDeviceOwnerUserId();
4587            } catch (RemoteException re) {
4588                throw re.rethrowFromSystemServer();
4589            }
4590        }
4591        return UserHandle.USER_NULL;
4592    }
4593
4594    /**
4595     * Clears the current device owner. The caller must be the device owner. This function should be
4596     * used cautiously as once it is called it cannot be undone. The device owner can only be set as
4597     * a part of device setup, before it completes.
4598     * <p>
4599     * While some policies previously set by the device owner will be cleared by this method, it is
4600     * a best-effort process and some other policies will still remain in place after the device
4601     * owner is cleared.
4602     *
4603     * @param packageName The package name of the device owner.
4604     * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
4605     *             does not own the current device owner component.
4606     *
4607     * @deprecated This method is expected to be used for testing purposes only. The device owner
4608     * will lose control of the device and its data after calling it. In order to protect any
4609     * sensitive data that remains on the device, it is advised that the device owner factory resets
4610     * the device instead of calling this method. See {@link #wipeData(int)}.
4611     */
4612    @Deprecated
4613    public void clearDeviceOwnerApp(String packageName) {
4614        throwIfParentInstance("clearDeviceOwnerApp");
4615        if (mService != null) {
4616            try {
4617                mService.clearDeviceOwner(packageName);
4618            } catch (RemoteException re) {
4619                throw re.rethrowFromSystemServer();
4620            }
4621        }
4622    }
4623
4624    /**
4625     * Returns the device owner package name, only if it's running on the calling user.
4626     *
4627     * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
4628     *
4629     * @hide
4630     */
4631    @SystemApi
4632    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
4633    public @Nullable String getDeviceOwner() {
4634        throwIfParentInstance("getDeviceOwner");
4635        final ComponentName name = getDeviceOwnerComponentOnCallingUser();
4636        return name != null ? name.getPackageName() : null;
4637    }
4638
4639    /**
4640     * Called by the system to find out whether the device is managed by a Device Owner.
4641     *
4642     * @return whether the device is managed by a Device Owner.
4643     * @throws SecurityException if the caller is not the device owner, does not hold the
4644     *         MANAGE_USERS permission and is not the system.
4645     *
4646     * @hide
4647     */
4648    @SystemApi
4649    @TestApi
4650    @SuppressLint("Doclava125")
4651    public boolean isDeviceManaged() {
4652        try {
4653            return mService.hasDeviceOwner();
4654        } catch (RemoteException re) {
4655            throw re.rethrowFromSystemServer();
4656        }
4657    }
4658
4659    /**
4660     * Returns the device owner name.  Note this method *will* return the device owner
4661     * name when it's running on a different user.
4662     *
4663     * @hide
4664     */
4665    @SystemApi
4666    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
4667    public String getDeviceOwnerNameOnAnyUser() {
4668        throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
4669        if (mService != null) {
4670            try {
4671                return mService.getDeviceOwnerName();
4672            } catch (RemoteException re) {
4673                throw re.rethrowFromSystemServer();
4674            }
4675        }
4676        return null;
4677    }
4678
4679    /**
4680     * @hide
4681     * @deprecated Do not use
4682     * @removed
4683     */
4684    @Deprecated
4685    @SystemApi
4686    @SuppressLint("Doclava125")
4687    public @Nullable String getDeviceInitializerApp() {
4688        return null;
4689    }
4690
4691    /**
4692     * @hide
4693     * @deprecated Do not use
4694     * @removed
4695     */
4696    @Deprecated
4697    @SystemApi
4698    @SuppressLint("Doclava125")
4699    public @Nullable ComponentName getDeviceInitializerComponent() {
4700        return null;
4701    }
4702
4703    /**
4704     * @hide
4705     * @deprecated Use #ACTION_SET_PROFILE_OWNER
4706     * Sets the given component as an active admin and registers the package as the profile
4707     * owner for this user. The package must already be installed and there shouldn't be
4708     * an existing profile owner registered for this user. Also, this method must be called
4709     * before the user setup has been completed.
4710     * <p>
4711     * This method can only be called by system apps that hold MANAGE_USERS permission and
4712     * MANAGE_DEVICE_ADMINS permission.
4713     * @param admin The component to register as an active admin and profile owner.
4714     * @param ownerName The user-visible name of the entity that is managing this user.
4715     * @return whether the admin was successfully registered as the profile owner.
4716     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
4717     *         the user has already been set up.
4718     */
4719    @Deprecated
4720    @SystemApi
4721    @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
4722    public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
4723            throws IllegalArgumentException {
4724        throwIfParentInstance("setActiveProfileOwner");
4725        if (mService != null) {
4726            try {
4727                final int myUserId = myUserId();
4728                mService.setActiveAdmin(admin, false, myUserId);
4729                return mService.setProfileOwner(admin, ownerName, myUserId);
4730            } catch (RemoteException re) {
4731                throw re.rethrowFromSystemServer();
4732            }
4733        }
4734        return false;
4735    }
4736
4737    /**
4738     * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
4739     * a SecurityException will be thrown. This method is not available to managed profile owners.
4740     * <p>
4741     * While some policies previously set by the profile owner will be cleared by this method, it is
4742     * a best-effort process and some other policies will still remain in place after the profile
4743     * owner is cleared.
4744     *
4745     * @param admin The component to remove as the profile owner.
4746     * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
4747     * being called from a managed profile.
4748     *
4749     * @deprecated This method is expected to be used for testing purposes only. The profile owner
4750     * will lose control of the user and its data after calling it. In order to protect any
4751     * sensitive data that remains on this user, it is advised that the profile owner deletes it
4752     * instead of calling this method. See {@link #wipeData(int)}.
4753     */
4754    @Deprecated
4755    public void clearProfileOwner(@NonNull ComponentName admin) {
4756        throwIfParentInstance("clearProfileOwner");
4757        if (mService != null) {
4758            try {
4759                mService.clearProfileOwner(admin);
4760            } catch (RemoteException re) {
4761                throw re.rethrowFromSystemServer();
4762            }
4763        }
4764    }
4765
4766    /**
4767     * @hide
4768     * Checks whether the user was already setup.
4769     */
4770    public boolean hasUserSetupCompleted() {
4771        if (mService != null) {
4772            try {
4773                return mService.hasUserSetupCompleted();
4774            } catch (RemoteException re) {
4775                throw re.rethrowFromSystemServer();
4776            }
4777        }
4778        return true;
4779    }
4780
4781    /**
4782     * @hide
4783     * Sets the given component as the profile owner of the given user profile. The package must
4784     * already be installed. There must not already be a profile owner for this user.
4785     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
4786     * this method.
4787     * Calling this after the setup phase of the specified user has completed is allowed only if:
4788     * - the caller is SYSTEM_UID.
4789     * - or the caller is the shell uid, and there are no accounts on the specified user.
4790     * @param admin the component name to be registered as profile owner.
4791     * @param ownerName the human readable name of the organisation associated with this DPM.
4792     * @param userHandle the userId to set the profile owner for.
4793     * @return whether the component was successfully registered as the profile owner.
4794     * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
4795     * preconditions mentioned are not met.
4796     */
4797    public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
4798            int userHandle) throws IllegalArgumentException {
4799        if (mService != null) {
4800            try {
4801                if (ownerName == null) {
4802                    ownerName = "";
4803                }
4804                return mService.setProfileOwner(admin, ownerName, userHandle);
4805            } catch (RemoteException re) {
4806                throw re.rethrowFromSystemServer();
4807            }
4808        }
4809        return false;
4810    }
4811
4812    /**
4813     * Sets the device owner information to be shown on the lock screen.
4814     * <p>
4815     * If the device owner information is {@code null} or empty then the device owner info is
4816     * cleared and the user owner info is shown on the lock screen if it is set.
4817     * <p>
4818     * If the device owner information contains only whitespaces then the message on the lock screen
4819     * will be blank and the user will not be allowed to change it.
4820     * <p>
4821     * If the device owner information needs to be localized, it is the responsibility of the
4822     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
4823     * and set a new version of this string accordingly.
4824     *
4825     * @param admin The name of the admin component to check.
4826     * @param info Device owner information which will be displayed instead of the user owner info.
4827     * @throws SecurityException if {@code admin} is not a device owner.
4828     */
4829    public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
4830        throwIfParentInstance("setDeviceOwnerLockScreenInfo");
4831        if (mService != null) {
4832            try {
4833                mService.setDeviceOwnerLockScreenInfo(admin, info);
4834            } catch (RemoteException re) {
4835                throw re.rethrowFromSystemServer();
4836            }
4837        }
4838    }
4839
4840    /**
4841     * @return The device owner information. If it is not set returns {@code null}.
4842     */
4843    public CharSequence getDeviceOwnerLockScreenInfo() {
4844        throwIfParentInstance("getDeviceOwnerLockScreenInfo");
4845        if (mService != null) {
4846            try {
4847                return mService.getDeviceOwnerLockScreenInfo();
4848            } catch (RemoteException re) {
4849                throw re.rethrowFromSystemServer();
4850            }
4851        }
4852        return null;
4853    }
4854
4855    /**
4856     * Called by device or profile owners to suspend packages for this user. This function can be
4857     * called by a device owner, profile owner, or by a delegate given the
4858     * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
4859     * <p>
4860     * A suspended package will not be able to start activities. Its notifications will be hidden,
4861     * it will not show up in recents, will not be able to show toasts or dialogs or ring the
4862     * device.
4863     * <p>
4864     * The package must already be installed. If the package is uninstalled while suspended the
4865     * package will no longer be suspended. The admin can block this by using
4866     * {@link #setUninstallBlocked}.
4867     *
4868     * @param admin The name of the admin component to check, or {@code null} if the caller is a
4869     *            package access delegate.
4870     * @param packageNames The package names to suspend or unsuspend.
4871     * @param suspended If set to {@code true} than the packages will be suspended, if set to
4872     *            {@code false} the packages will be unsuspended.
4873     * @return an array of package names for which the suspended status is not set as requested in
4874     *         this method.
4875     * @throws SecurityException if {@code admin} is not a device or profile owner.
4876     * @see #setDelegatedScopes
4877     * @see #DELEGATION_PACKAGE_ACCESS
4878     */
4879    public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
4880            @NonNull String[] packageNames, boolean suspended) {
4881        throwIfParentInstance("setPackagesSuspended");
4882        if (mService != null) {
4883            try {
4884                return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
4885                        suspended);
4886            } catch (RemoteException re) {
4887                throw re.rethrowFromSystemServer();
4888            }
4889        }
4890        return packageNames;
4891    }
4892
4893    /**
4894     * Determine if a package is suspended. This function can be called by a device owner, profile
4895     * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
4896     * {@link #setDelegatedScopes}.
4897     *
4898     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4899     *            {@code null} if the caller is a package access delegate.
4900     * @param packageName The name of the package to retrieve the suspended status of.
4901     * @return {@code true} if the package is suspended or {@code false} if the package is not
4902     *         suspended, could not be found or an error occurred.
4903     * @throws SecurityException if {@code admin} is not a device or profile owner.
4904     * @throws NameNotFoundException if the package could not be found.
4905     * @see #setDelegatedScopes
4906     * @see #DELEGATION_PACKAGE_ACCESS
4907     */
4908    public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
4909            throws NameNotFoundException {
4910        throwIfParentInstance("isPackageSuspended");
4911        if (mService != null) {
4912            try {
4913                return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
4914            } catch (RemoteException e) {
4915                throw e.rethrowFromSystemServer();
4916            } catch (IllegalArgumentException ex) {
4917                throw new NameNotFoundException(packageName);
4918            }
4919        }
4920        return false;
4921    }
4922
4923    /**
4924     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
4925     * be used. Only the profile owner can call this.
4926     *
4927     * @see #isProfileOwnerApp
4928     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4929     * @throws SecurityException if {@code admin} is not a profile owner.
4930     */
4931    public void setProfileEnabled(@NonNull ComponentName admin) {
4932        throwIfParentInstance("setProfileEnabled");
4933        if (mService != null) {
4934            try {
4935                mService.setProfileEnabled(admin);
4936            } catch (RemoteException e) {
4937                throw e.rethrowFromSystemServer();
4938            }
4939        }
4940    }
4941
4942    /**
4943     * Sets the name of the profile. In the device owner case it sets the name of the user which it
4944     * is called from. Only a profile owner or device owner can call this. If this is never called
4945     * by the profile or device owner, the name will be set to default values.
4946     *
4947     * @see #isProfileOwnerApp
4948     * @see #isDeviceOwnerApp
4949     * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
4950     * @param profileName The name of the profile.
4951     * @throws SecurityException if {@code admin} is not a device or profile owner.
4952     */
4953    public void setProfileName(@NonNull ComponentName admin, String profileName) {
4954        throwIfParentInstance("setProfileName");
4955        if (mService != null) {
4956            try {
4957                mService.setProfileName(admin, profileName);
4958            } catch (RemoteException e) {
4959                throw e.rethrowFromSystemServer();
4960            }
4961        }
4962    }
4963
4964    /**
4965     * Used to determine if a particular package is registered as the profile owner for the
4966     * user. A profile owner is a special device admin that has additional privileges
4967     * within the profile.
4968     *
4969     * @param packageName The package name of the app to compare with the registered profile owner.
4970     * @return Whether or not the package is registered as the profile owner.
4971     */
4972    public boolean isProfileOwnerApp(String packageName) {
4973        throwIfParentInstance("isProfileOwnerApp");
4974        if (mService != null) {
4975            try {
4976                ComponentName profileOwner = mService.getProfileOwner(myUserId());
4977                return profileOwner != null
4978                        && profileOwner.getPackageName().equals(packageName);
4979            } catch (RemoteException re) {
4980                throw re.rethrowFromSystemServer();
4981            }
4982        }
4983        return false;
4984    }
4985
4986    /**
4987     * @hide
4988     * @return the packageName of the owner of the given user profile or {@code null} if no profile
4989     * owner has been set for that user.
4990     * @throws IllegalArgumentException if the userId is invalid.
4991     */
4992    @SystemApi
4993    public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
4994        throwIfParentInstance("getProfileOwner");
4995        return getProfileOwnerAsUser(Process.myUserHandle().getIdentifier());
4996    }
4997
4998    /**
4999     * @see #getProfileOwner()
5000     * @hide
5001     */
5002    public @Nullable ComponentName getProfileOwnerAsUser(final int userId)
5003            throws IllegalArgumentException {
5004        if (mService != null) {
5005            try {
5006                return mService.getProfileOwner(userId);
5007            } catch (RemoteException re) {
5008                throw re.rethrowFromSystemServer();
5009            }
5010        }
5011        return null;
5012    }
5013
5014    /**
5015     * @hide
5016     * @return the human readable name of the organisation associated with this DPM or {@code null}
5017     *         if one is not set.
5018     * @throws IllegalArgumentException if the userId is invalid.
5019     */
5020    public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
5021        if (mService != null) {
5022            try {
5023                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
5024            } catch (RemoteException re) {
5025                throw re.rethrowFromSystemServer();
5026            }
5027        }
5028        return null;
5029    }
5030
5031    /**
5032     * @hide
5033     * @param userId The user for whom to fetch the profile owner name, if any.
5034     * @return the human readable name of the organisation associated with this profile owner or
5035     *         null if one is not set.
5036     * @throws IllegalArgumentException if the userId is invalid.
5037     */
5038    @SystemApi
5039    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5040    public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
5041        throwIfParentInstance("getProfileOwnerNameAsUser");
5042        if (mService != null) {
5043            try {
5044                return mService.getProfileOwnerName(userId);
5045            } catch (RemoteException re) {
5046                throw re.rethrowFromSystemServer();
5047            }
5048        }
5049        return null;
5050    }
5051
5052    /**
5053     * Called by a profile owner or device owner to add a default intent handler activity for
5054     * intents that match a certain intent filter. This activity will remain the default intent
5055     * handler even if the set of potential event handlers for the intent filter changes and if the
5056     * intent preferences are reset.
5057     * <p>
5058     * The default disambiguation mechanism takes over if the activity is not installed (anymore).
5059     * When the activity is (re)installed, it is automatically reset as default intent handler for
5060     * the filter.
5061     * <p>
5062     * The calling device admin must be a profile owner or device owner. If it is not, a security
5063     * exception will be thrown.
5064     *
5065     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5066     * @param filter The IntentFilter for which a default handler is added.
5067     * @param activity The Activity that is added as default intent handler.
5068     * @throws SecurityException if {@code admin} is not a device or profile owner.
5069     */
5070    public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
5071            @NonNull ComponentName activity) {
5072        throwIfParentInstance("addPersistentPreferredActivity");
5073        if (mService != null) {
5074            try {
5075                mService.addPersistentPreferredActivity(admin, filter, activity);
5076            } catch (RemoteException e) {
5077                throw e.rethrowFromSystemServer();
5078            }
5079        }
5080    }
5081
5082    /**
5083     * Called by a profile owner or device owner to remove all persistent intent handler preferences
5084     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
5085     * <p>
5086     * The calling device admin must be a profile owner. If it is not, a security exception will be
5087     * thrown.
5088     *
5089     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5090     * @param packageName The name of the package for which preferences are removed.
5091     * @throws SecurityException if {@code admin} is not a device or profile owner.
5092     */
5093    public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
5094            String packageName) {
5095        throwIfParentInstance("clearPackagePersistentPreferredActivities");
5096        if (mService != null) {
5097            try {
5098                mService.clearPackagePersistentPreferredActivities(admin, packageName);
5099            } catch (RemoteException e) {
5100                throw e.rethrowFromSystemServer();
5101            }
5102        }
5103    }
5104
5105    /**
5106     * Called by a profile owner or device owner to grant permission to a package to manage
5107     * application restrictions for the calling user via {@link #setApplicationRestrictions} and
5108     * {@link #getApplicationRestrictions}.
5109     * <p>
5110     * This permission is persistent until it is later cleared by calling this method with a
5111     * {@code null} value or uninstalling the managing package.
5112     * <p>
5113     * The supplied application restriction managing package must be installed when calling this
5114     * API, otherwise an {@link NameNotFoundException} will be thrown.
5115     *
5116     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5117     * @param packageName The package name which will be given access to application restrictions
5118     *            APIs. If {@code null} is given the current package will be cleared.
5119     * @throws SecurityException if {@code admin} is not a device or profile owner.
5120     * @throws NameNotFoundException if {@code packageName} is not found
5121     *
5122     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5123     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5124     */
5125    @Deprecated
5126    public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
5127            @Nullable String packageName) throws NameNotFoundException {
5128        throwIfParentInstance("setApplicationRestrictionsManagingPackage");
5129        if (mService != null) {
5130            try {
5131                if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
5132                    throw new NameNotFoundException(packageName);
5133                }
5134            } catch (RemoteException e) {
5135                throw e.rethrowFromSystemServer();
5136            }
5137        }
5138    }
5139
5140    /**
5141     * Called by a profile owner or device owner to retrieve the application restrictions managing
5142     * package for the current user, or {@code null} if none is set. If there are multiple
5143     * delegates this function will return one of them.
5144     *
5145     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5146     * @return The package name allowed to manage application restrictions on the current user, or
5147     *         {@code null} if none is set.
5148     * @throws SecurityException if {@code admin} is not a device or profile owner.
5149     *
5150     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5151     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5152     */
5153    @Deprecated
5154    @Nullable
5155    public String getApplicationRestrictionsManagingPackage(
5156            @NonNull ComponentName admin) {
5157        throwIfParentInstance("getApplicationRestrictionsManagingPackage");
5158        if (mService != null) {
5159            try {
5160                return mService.getApplicationRestrictionsManagingPackage(admin);
5161            } catch (RemoteException e) {
5162                throw e.rethrowFromSystemServer();
5163            }
5164        }
5165        return null;
5166    }
5167
5168    /**
5169     * Called by any application to find out whether it has been granted permission via
5170     * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
5171     * for the calling user.
5172     *
5173     * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
5174     * that method.
5175     *
5176     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
5177     * instead.
5178     */
5179    @Deprecated
5180    public boolean isCallerApplicationRestrictionsManagingPackage() {
5181        throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
5182        if (mService != null) {
5183            try {
5184                return mService.isCallerApplicationRestrictionsManagingPackage(
5185                        mContext.getPackageName());
5186            } catch (RemoteException e) {
5187                throw e.rethrowFromSystemServer();
5188            }
5189        }
5190        return false;
5191    }
5192
5193    /**
5194     * Sets the application restrictions for a given target application running in the calling user.
5195     * <p>
5196     * The caller must be a profile or device owner on that user, or the package allowed to manage
5197     * application restrictions via {@link #setDelegatedScopes} with the
5198     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
5199     * <p>
5200     * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
5201     * <ul>
5202     * <li>{@code boolean}
5203     * <li>{@code int}
5204     * <li>{@code String} or {@code String[]}
5205     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
5206     * </ul>
5207     * <p>
5208     * If the restrictions are not available yet, but may be applied in the near future, the caller
5209     * can notify the target application of that by adding
5210     * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
5211     * <p>
5212     * The application restrictions are only made visible to the target application via
5213     * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
5214     * owner, and the application restrictions managing package via
5215     * {@link #getApplicationRestrictions}.
5216     *
5217     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
5218     *
5219     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5220     *            {@code null} if called by the application restrictions managing package.
5221     * @param packageName The name of the package to update restricted settings for.
5222     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
5223     *            set of active restrictions.
5224     * @throws SecurityException if {@code admin} is not a device or profile owner.
5225     * @see #setDelegatedScopes
5226     * @see #DELEGATION_APP_RESTRICTIONS
5227     * @see UserManager#KEY_RESTRICTIONS_PENDING
5228     */
5229    @WorkerThread
5230    public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
5231            Bundle settings) {
5232        throwIfParentInstance("setApplicationRestrictions");
5233        if (mService != null) {
5234            try {
5235                mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
5236                        settings);
5237            } catch (RemoteException e) {
5238                throw e.rethrowFromSystemServer();
5239            }
5240        }
5241    }
5242
5243    /**
5244     * Sets a list of configuration features to enable for a TrustAgent component. This is meant to
5245     * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
5246     * agents but those enabled by this function call. If flag
5247     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
5248     * <p>
5249     * The calling device admin must have requested
5250     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
5251     * if not, a security exception will be thrown.
5252     * <p>
5253     * This method can be called on the {@link DevicePolicyManager} instance returned by
5254     * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
5255     * the parent profile.
5256     *
5257     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5258     * @param target Component name of the agent to be enabled.
5259     * @param configuration TrustAgent-specific feature bundle. If null for any admin, agent will be
5260     *            strictly disabled according to the state of the
5261     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS} flag.
5262     *            <p>
5263     *            If {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is set and options is not null for all
5264     *            admins, then it's up to the TrustAgent itself to aggregate the values from all
5265     *            device admins.
5266     *            <p>
5267     *            Consult documentation for the specific TrustAgent to determine legal options
5268     *            parameters.
5269     * @throws SecurityException if {@code admin} is not an active administrator or does not use
5270     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
5271     */
5272    public void setTrustAgentConfiguration(@NonNull ComponentName admin,
5273            @NonNull ComponentName target, PersistableBundle configuration) {
5274        if (mService != null) {
5275            try {
5276                mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
5277            } catch (RemoteException e) {
5278                throw e.rethrowFromSystemServer();
5279            }
5280        }
5281    }
5282
5283    /**
5284     * Gets configuration for the given trust agent based on aggregating all calls to
5285     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
5286     * all device admins.
5287     * <p>
5288     * This method can be called on the {@link DevicePolicyManager} instance returned by
5289     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
5290     * on the parent profile.
5291     *
5292     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
5293     * this function returns a list of configurations for all admins that declare
5294     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
5295     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
5296     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
5297     * for this {@param agent} or calls it with a null configuration, null is returned.
5298     * @param agent Which component to get enabled features for.
5299     * @return configuration for the given trust agent.
5300     */
5301    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5302            @Nullable ComponentName admin, @NonNull ComponentName agent) {
5303        return getTrustAgentConfiguration(admin, agent, myUserId());
5304    }
5305
5306    /** @hide per-user version */
5307    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5308            @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
5309        if (mService != null) {
5310            try {
5311                return mService.getTrustAgentConfiguration(admin, agent, userHandle,
5312                        mParentInstance);
5313            } catch (RemoteException e) {
5314                throw e.rethrowFromSystemServer();
5315            }
5316        }
5317        return new ArrayList<PersistableBundle>(); // empty list
5318    }
5319
5320    /**
5321     * Called by a profile owner of a managed profile to set whether caller-Id information from the
5322     * managed profile will be shown in the parent profile, for incoming calls.
5323     * <p>
5324     * The calling device admin must be a profile owner. If it is not, a security exception will be
5325     * thrown.
5326     *
5327     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5328     * @param disabled If true caller-Id information in the managed profile is not displayed.
5329     * @throws SecurityException if {@code admin} is not a device or profile owner.
5330     */
5331    public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
5332        throwIfParentInstance("setCrossProfileCallerIdDisabled");
5333        if (mService != null) {
5334            try {
5335                mService.setCrossProfileCallerIdDisabled(admin, disabled);
5336            } catch (RemoteException e) {
5337                throw e.rethrowFromSystemServer();
5338            }
5339        }
5340    }
5341
5342    /**
5343     * Called by a profile owner of a managed profile to determine whether or not caller-Id
5344     * information has been disabled.
5345     * <p>
5346     * The calling device admin must be a profile owner. If it is not, a security exception will be
5347     * thrown.
5348     *
5349     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5350     * @throws SecurityException if {@code admin} is not a device or profile owner.
5351     */
5352    public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
5353        throwIfParentInstance("getCrossProfileCallerIdDisabled");
5354        if (mService != null) {
5355            try {
5356                return mService.getCrossProfileCallerIdDisabled(admin);
5357            } catch (RemoteException e) {
5358                throw e.rethrowFromSystemServer();
5359            }
5360        }
5361        return false;
5362    }
5363
5364    /**
5365     * Determine whether or not caller-Id information has been disabled.
5366     *
5367     * @param userHandle The user for whom to check the caller-id permission
5368     * @hide
5369     */
5370    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
5371        if (mService != null) {
5372            try {
5373                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
5374            } catch (RemoteException e) {
5375                throw e.rethrowFromSystemServer();
5376            }
5377        }
5378        return false;
5379    }
5380
5381    /**
5382     * Called by a profile owner of a managed profile to set whether contacts search from the
5383     * managed profile will be shown in the parent profile, for incoming calls.
5384     * <p>
5385     * The calling device admin must be a profile owner. If it is not, a security exception will be
5386     * thrown.
5387     *
5388     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5389     * @param disabled If true contacts search in the managed profile is not displayed.
5390     * @throws SecurityException if {@code admin} is not a device or profile owner.
5391     */
5392    public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
5393            boolean disabled) {
5394        throwIfParentInstance("setCrossProfileContactsSearchDisabled");
5395        if (mService != null) {
5396            try {
5397                mService.setCrossProfileContactsSearchDisabled(admin, disabled);
5398            } catch (RemoteException e) {
5399                throw e.rethrowFromSystemServer();
5400            }
5401        }
5402    }
5403
5404    /**
5405     * Called by a profile owner of a managed profile to determine whether or not contacts search
5406     * has been disabled.
5407     * <p>
5408     * The calling device admin must be a profile owner. If it is not, a security exception will be
5409     * thrown.
5410     *
5411     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5412     * @throws SecurityException if {@code admin} is not a device or profile owner.
5413     */
5414    public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
5415        throwIfParentInstance("getCrossProfileContactsSearchDisabled");
5416        if (mService != null) {
5417            try {
5418                return mService.getCrossProfileContactsSearchDisabled(admin);
5419            } catch (RemoteException e) {
5420                throw e.rethrowFromSystemServer();
5421            }
5422        }
5423        return false;
5424    }
5425
5426
5427    /**
5428     * Determine whether or not contacts search has been disabled.
5429     *
5430     * @param userHandle The user for whom to check the contacts search permission
5431     * @hide
5432     */
5433    public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
5434        if (mService != null) {
5435            try {
5436                return mService
5437                        .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
5438            } catch (RemoteException e) {
5439                throw e.rethrowFromSystemServer();
5440            }
5441        }
5442        return false;
5443    }
5444
5445    /**
5446     * Start Quick Contact on the managed profile for the user, if the policy allows.
5447     *
5448     * @hide
5449     */
5450    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5451            boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
5452        if (mService != null) {
5453            try {
5454                mService.startManagedQuickContact(actualLookupKey, actualContactId,
5455                        isContactIdIgnored, directoryId, originalIntent);
5456            } catch (RemoteException e) {
5457                throw e.rethrowFromSystemServer();
5458            }
5459        }
5460    }
5461
5462    /**
5463     * Start Quick Contact on the managed profile for the user, if the policy allows.
5464     * @hide
5465     */
5466    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5467            Intent originalIntent) {
5468        startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
5469                originalIntent);
5470    }
5471
5472    /**
5473     * Called by a profile owner of a managed profile to set whether bluetooth devices can access
5474     * enterprise contacts.
5475     * <p>
5476     * The calling device admin must be a profile owner. If it is not, a security exception will be
5477     * thrown.
5478     * <p>
5479     * This API works on managed profile only.
5480     *
5481     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5482     * @param disabled If true, bluetooth devices cannot access enterprise contacts.
5483     * @throws SecurityException if {@code admin} is not a device or profile owner.
5484     */
5485    public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
5486        throwIfParentInstance("setBluetoothContactSharingDisabled");
5487        if (mService != null) {
5488            try {
5489                mService.setBluetoothContactSharingDisabled(admin, disabled);
5490            } catch (RemoteException e) {
5491                throw e.rethrowFromSystemServer();
5492            }
5493        }
5494    }
5495
5496    /**
5497     * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
5498     * cannot access enterprise contacts.
5499     * <p>
5500     * The calling device admin must be a profile owner. If it is not, a security exception will be
5501     * thrown.
5502     * <p>
5503     * This API works on managed profile only.
5504     *
5505     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5506     * @throws SecurityException if {@code admin} is not a device or profile owner.
5507     */
5508    public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
5509        throwIfParentInstance("getBluetoothContactSharingDisabled");
5510        if (mService != null) {
5511            try {
5512                return mService.getBluetoothContactSharingDisabled(admin);
5513            } catch (RemoteException e) {
5514                throw e.rethrowFromSystemServer();
5515            }
5516        }
5517        return true;
5518    }
5519
5520    /**
5521     * Determine whether or not Bluetooth devices cannot access contacts.
5522     * <p>
5523     * This API works on managed profile UserHandle only.
5524     *
5525     * @param userHandle The user for whom to check the caller-id permission
5526     * @hide
5527     */
5528    public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
5529        if (mService != null) {
5530            try {
5531                return mService.getBluetoothContactSharingDisabledForUser(userHandle
5532                        .getIdentifier());
5533            } catch (RemoteException e) {
5534                throw e.rethrowFromSystemServer();
5535            }
5536        }
5537        return true;
5538    }
5539
5540    /**
5541     * Called by the profile owner of a managed profile so that some intents sent in the managed
5542     * profile can also be resolved in the parent, or vice versa. Only activity intents are
5543     * supported.
5544     *
5545     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5546     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
5547     *            other profile
5548     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
5549     *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
5550     * @throws SecurityException if {@code admin} is not a device or profile owner.
5551     */
5552    public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
5553        throwIfParentInstance("addCrossProfileIntentFilter");
5554        if (mService != null) {
5555            try {
5556                mService.addCrossProfileIntentFilter(admin, filter, flags);
5557            } catch (RemoteException e) {
5558                throw e.rethrowFromSystemServer();
5559            }
5560        }
5561    }
5562
5563    /**
5564     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
5565     * that go from the managed profile to the parent, or from the parent to the managed profile.
5566     * Only removes those that have been set by the profile owner.
5567     *
5568     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5569     * @throws SecurityException if {@code admin} is not a device or profile owner.
5570     */
5571    public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
5572        throwIfParentInstance("clearCrossProfileIntentFilters");
5573        if (mService != null) {
5574            try {
5575                mService.clearCrossProfileIntentFilters(admin);
5576            } catch (RemoteException e) {
5577                throw e.rethrowFromSystemServer();
5578            }
5579        }
5580    }
5581
5582    /**
5583     * Called by a profile or device owner to set the permitted accessibility services. When set by
5584     * a device owner or profile owner the restriction applies to all profiles of the user the
5585     * device owner or profile owner is an admin for. By default the user can use any accessiblity
5586     * service. When zero or more packages have been added, accessiblity services that are not in
5587     * the list and not part of the system can not be enabled by the user.
5588     * <p>
5589     * Calling with a null value for the list disables the restriction so that all services can be
5590     * used, calling with an empty list only allows the builtin system's services.
5591     * <p>
5592     * System accessibility services are always available to the user the list can't modify this.
5593     *
5594     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5595     * @param packageNames List of accessibility service package names.
5596     * @return true if setting the restriction succeeded. It fail if there is one or more non-system
5597     *         accessibility services enabled, that are not in the list.
5598     * @throws SecurityException if {@code admin} is not a device or profile owner.
5599     */
5600    public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
5601            List<String> packageNames) {
5602        throwIfParentInstance("setPermittedAccessibilityServices");
5603        if (mService != null) {
5604            try {
5605                return mService.setPermittedAccessibilityServices(admin, packageNames);
5606            } catch (RemoteException e) {
5607                throw e.rethrowFromSystemServer();
5608            }
5609        }
5610        return false;
5611    }
5612
5613    /**
5614     * Returns the list of permitted accessibility services set by this device or profile owner.
5615     * <p>
5616     * An empty list means no accessibility services except system services are allowed. Null means
5617     * all accessibility services are allowed.
5618     *
5619     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5620     * @return List of accessiblity service package names.
5621     * @throws SecurityException if {@code admin} is not a device or profile owner.
5622     */
5623    public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
5624        throwIfParentInstance("getPermittedAccessibilityServices");
5625        if (mService != null) {
5626            try {
5627                return mService.getPermittedAccessibilityServices(admin);
5628            } catch (RemoteException e) {
5629                throw e.rethrowFromSystemServer();
5630            }
5631        }
5632        return null;
5633    }
5634
5635    /**
5636     * Called by the system to check if a specific accessibility service is disabled by admin.
5637     *
5638     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5639     * @param packageName Accessibility service package name that needs to be checked.
5640     * @param userHandle user id the admin is running as.
5641     * @return true if the accessibility service is permitted, otherwise false.
5642     *
5643     * @hide
5644     */
5645    public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
5646            @NonNull String packageName, int userHandle) {
5647        if (mService != null) {
5648            try {
5649                return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
5650                        userHandle);
5651            } catch (RemoteException e) {
5652                throw e.rethrowFromSystemServer();
5653            }
5654        }
5655        return false;
5656    }
5657
5658    /**
5659     * Returns the list of accessibility services permitted by the device or profiles
5660     * owners of this user.
5661     *
5662     * <p>Null means all accessibility services are allowed, if a non-null list is returned
5663     * it will contain the intersection of the permitted lists for any device or profile
5664     * owners that apply to this user. It will also include any system accessibility services.
5665     *
5666     * @param userId which user to check for.
5667     * @return List of accessiblity service package names.
5668     * @hide
5669     */
5670     @SystemApi
5671     public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
5672        throwIfParentInstance("getPermittedAccessibilityServices");
5673        if (mService != null) {
5674            try {
5675                return mService.getPermittedAccessibilityServicesForUser(userId);
5676            } catch (RemoteException e) {
5677                throw e.rethrowFromSystemServer();
5678            }
5679        }
5680        return null;
5681     }
5682
5683    /**
5684     * Called by a profile or device owner to set the permitted input methods services. When set by
5685     * a device owner or profile owner the restriction applies to all profiles of the user the
5686     * device owner or profile owner is an admin for. By default the user can use any input method.
5687     * When zero or more packages have been added, input method that are not in the list and not
5688     * part of the system can not be enabled by the user. This method will fail if it is called for
5689     * a admin that is not for the foreground user or a profile of the foreground user.
5690     * <p>
5691     * Calling with a null value for the list disables the restriction so that all input methods can
5692     * be used, calling with an empty list disables all but the system's own input methods.
5693     * <p>
5694     * System input methods are always available to the user this method can't modify this.
5695     *
5696     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5697     * @param packageNames List of input method package names.
5698     * @return true if setting the restriction succeeded. It will fail if there are one or more
5699     *         non-system input methods currently enabled that are not in the packageNames list.
5700     * @throws SecurityException if {@code admin} is not a device or profile owner.
5701     */
5702    public boolean setPermittedInputMethods(
5703            @NonNull ComponentName admin, List<String> packageNames) {
5704        throwIfParentInstance("setPermittedInputMethods");
5705        if (mService != null) {
5706            try {
5707                return mService.setPermittedInputMethods(admin, packageNames);
5708            } catch (RemoteException e) {
5709                throw e.rethrowFromSystemServer();
5710            }
5711        }
5712        return false;
5713    }
5714
5715
5716    /**
5717     * Returns the list of permitted input methods set by this device or profile owner.
5718     * <p>
5719     * An empty list means no input methods except system input methods are allowed. Null means all
5720     * input methods are allowed.
5721     *
5722     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5723     * @return List of input method package names.
5724     * @throws SecurityException if {@code admin} is not a device or profile owner.
5725     */
5726    public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
5727        throwIfParentInstance("getPermittedInputMethods");
5728        if (mService != null) {
5729            try {
5730                return mService.getPermittedInputMethods(admin);
5731            } catch (RemoteException e) {
5732                throw e.rethrowFromSystemServer();
5733            }
5734        }
5735        return null;
5736    }
5737
5738    /**
5739     * Called by the system to check if a specific input method is disabled by admin.
5740     *
5741     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5742     * @param packageName Input method package name that needs to be checked.
5743     * @param userHandle user id the admin is running as.
5744     * @return true if the input method is permitted, otherwise false.
5745     *
5746     * @hide
5747     */
5748    public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
5749            @NonNull String packageName, int userHandle) {
5750        if (mService != null) {
5751            try {
5752                return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
5753            } catch (RemoteException e) {
5754                throw e.rethrowFromSystemServer();
5755            }
5756        }
5757        return false;
5758    }
5759
5760    /**
5761     * Returns the list of input methods permitted by the device or profiles
5762     * owners of the current user.  (*Not* calling user, due to a limitation in InputMethodManager.)
5763     *
5764     * <p>Null means all input methods are allowed, if a non-null list is returned
5765     * it will contain the intersection of the permitted lists for any device or profile
5766     * owners that apply to this user. It will also include any system input methods.
5767     *
5768     * @return List of input method package names.
5769     * @hide
5770     */
5771    @SystemApi
5772    public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
5773        throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
5774        if (mService != null) {
5775            try {
5776                return mService.getPermittedInputMethodsForCurrentUser();
5777            } catch (RemoteException e) {
5778                throw e.rethrowFromSystemServer();
5779            }
5780        }
5781        return null;
5782    }
5783
5784    /**
5785     * Called by a profile owner of a managed profile to set the packages that are allowed to use
5786     * a {@link android.service.notification.NotificationListenerService} in the primary user to
5787     * see notifications from the managed profile. By default all packages are permitted by this
5788     * policy. When zero or more packages have been added, notification listeners installed on the
5789     * primary user that are not in the list and are not part of the system won't receive events
5790     * for managed profile notifications.
5791     * <p>
5792     * Calling with a {@code null} value for the list disables the restriction so that all
5793     * notification listener services be used. Calling with an empty list disables all but the
5794     * system's own notification listeners. System notification listener services are always
5795     * available to the user.
5796     * <p>
5797     * If a device or profile owner want to stop notification listeners in their user from seeing
5798     * that user's notifications they should prevent that service from running instead (e.g. via
5799     * {@link #setApplicationHidden(ComponentName, String, boolean)})
5800     *
5801     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5802     * @param packageList List of package names to whitelist
5803     * @return true if setting the restriction succeeded. It will fail if called outside a managed
5804     * profile
5805     * @throws SecurityException if {@code admin} is not a profile owner.
5806     *
5807     * @see android.service.notification.NotificationListenerService
5808     */
5809    public boolean setPermittedCrossProfileNotificationListeners(
5810            @NonNull ComponentName admin, @Nullable List<String> packageList) {
5811        throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
5812        if (mService != null) {
5813            try {
5814                return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
5815            } catch (RemoteException e) {
5816                throw e.rethrowFromSystemServer();
5817            }
5818        }
5819        return false;
5820    }
5821
5822    /**
5823     * Returns the list of packages installed on the primary user that allowed to use a
5824     * {@link android.service.notification.NotificationListenerService} to receive
5825     * notifications from this managed profile, as set by the profile owner.
5826     * <p>
5827     * An empty list means no notification listener services except system ones are allowed.
5828     * A {@code null} return value indicates that all notification listeners are allowed.
5829     */
5830    public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
5831            @NonNull ComponentName admin) {
5832        throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
5833        if (mService != null) {
5834            try {
5835                return mService.getPermittedCrossProfileNotificationListeners(admin);
5836            } catch (RemoteException e) {
5837                throw e.rethrowFromSystemServer();
5838            }
5839        }
5840        return null;
5841    }
5842
5843    /**
5844     * Returns true if {@code NotificationListenerServices} from the given package are allowed to
5845     * receive events for notifications from the given user id. Can only be called by the system uid
5846     *
5847     * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
5848     *
5849     * @hide
5850     */
5851    public boolean isNotificationListenerServicePermitted(
5852            @NonNull String packageName, @UserIdInt int userId) {
5853        if (mService != null) {
5854            try {
5855                return mService.isNotificationListenerServicePermitted(packageName, userId);
5856            } catch (RemoteException e) {
5857                throw e.rethrowFromSystemServer();
5858            }
5859        }
5860        return true;
5861    }
5862
5863    /**
5864     * Get the list of apps to keep around as APKs even if no user has currently installed it. This
5865     * function can be called by a device owner or by a delegate given the
5866     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
5867     * <p>
5868     * Please note that packages returned in this method are not automatically pre-cached.
5869     *
5870     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5871     *            {@code null} if the caller is a keep uninstalled packages delegate.
5872     * @return List of package names to keep cached.
5873     * @see #setDelegatedScopes
5874     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
5875     * @hide
5876     */
5877    public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
5878        throwIfParentInstance("getKeepUninstalledPackages");
5879        if (mService != null) {
5880            try {
5881                return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
5882            } catch (RemoteException e) {
5883                throw e.rethrowFromSystemServer();
5884            }
5885        }
5886        return null;
5887    }
5888
5889    /**
5890     * Set a list of apps to keep around as APKs even if no user has currently installed it. This
5891     * function can be called by a device owner or by a delegate given the
5892     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
5893     *
5894     * <p>Please note that setting this policy does not imply that specified apps will be
5895     * automatically pre-cached.</p>
5896     *
5897     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5898     *            {@code null} if the caller is a keep uninstalled packages delegate.
5899     * @param packageNames List of package names to keep cached.
5900     * @throws SecurityException if {@code admin} is not a device owner.
5901     * @see #setDelegatedScopes
5902     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
5903     * @hide
5904     */
5905    public void setKeepUninstalledPackages(@Nullable ComponentName admin,
5906            @NonNull List<String> packageNames) {
5907        throwIfParentInstance("setKeepUninstalledPackages");
5908        if (mService != null) {
5909            try {
5910                mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
5911            } catch (RemoteException e) {
5912                throw e.rethrowFromSystemServer();
5913            }
5914        }
5915    }
5916
5917    /**
5918     * Called by a device owner to create a user with the specified name. The UserHandle returned
5919     * by this method should not be persisted as user handles are recycled as users are removed and
5920     * created. If you need to persist an identifier for this user, use
5921     * {@link UserManager#getSerialNumberForUser}.
5922     *
5923     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5924     * @param name the user's name
5925     * @see UserHandle
5926     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
5927     *         user could not be created.
5928     *
5929     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
5930     * @removed From {@link android.os.Build.VERSION_CODES#N}
5931     */
5932    @Deprecated
5933    public @Nullable UserHandle createUser(@NonNull ComponentName admin, String name) {
5934        return null;
5935    }
5936
5937    /**
5938     * Called by a device owner to create a user with the specified name. The UserHandle returned
5939     * by this method should not be persisted as user handles are recycled as users are removed and
5940     * created. If you need to persist an identifier for this user, use
5941     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
5942     * immediately.
5943     *
5944     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
5945     * as registered as an active admin on the new user.  The profile owner package will be
5946     * installed on the new user if it already is installed on the device.
5947     *
5948     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
5949     * profileOwnerComponent when onEnable is called.
5950     *
5951     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5952     * @param name the user's name
5953     * @param ownerName the human readable name of the organisation associated with this DPM.
5954     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
5955     *      the user.
5956     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
5957     *      on the new user.
5958     * @see UserHandle
5959     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
5960     *         user could not be created.
5961     *
5962     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
5963     * @removed From {@link android.os.Build.VERSION_CODES#N}
5964     */
5965    @Deprecated
5966    public @Nullable UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
5967            String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
5968        return null;
5969    }
5970
5971    /**
5972      * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
5973      */
5974    public static final int SKIP_SETUP_WIZARD = 0x0001;
5975
5976    /**
5977     * Flag used by {@link #createAndManageUser} to specify that the user should be created
5978     * ephemeral.
5979     * @hide
5980     */
5981    public static final int MAKE_USER_EPHEMERAL = 0x0002;
5982
5983    /**
5984     * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
5985     * demo user.
5986     * @hide
5987     */
5988    public static final int MAKE_USER_DEMO = 0x0004;
5989
5990    /**
5991     * Called by a device owner to create a user with the specified name and a given component of
5992     * the calling package as profile owner. The UserHandle returned by this method should not be
5993     * persisted as user handles are recycled as users are removed and created. If you need to
5994     * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
5995     * user will not be started in the background.
5996     * <p>
5997     * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
5998     * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
5999     * be registered as an active admin on the new user. The profile owner package will be installed
6000     * on the new user.
6001     * <p>
6002     * If the adminExtras are not null, they will be stored on the device until the user is started
6003     * for the first time. Then the extras will be passed to the admin when onEnable is called.
6004     *
6005     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6006     * @param name The user's name.
6007     * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
6008     *            same package as admin, otherwise no user is created and an
6009     *            IllegalArgumentException is thrown.
6010     * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
6011     *            user.
6012     * @param flags {@link #SKIP_SETUP_WIZARD} is supported.
6013     * @see UserHandle
6014     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6015     *         user could not be created.
6016     * @throws SecurityException if {@code admin} is not a device owner.
6017     */
6018    public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
6019            @NonNull String name,
6020            @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
6021            int flags) {
6022        throwIfParentInstance("createAndManageUser");
6023        try {
6024            return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
6025        } catch (RemoteException re) {
6026            throw re.rethrowFromSystemServer();
6027        }
6028    }
6029
6030    /**
6031     * Called by a device owner to remove a user and all associated data. The primary user can not
6032     * be removed.
6033     *
6034     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6035     * @param userHandle the user to remove.
6036     * @return {@code true} if the user was removed, {@code false} otherwise.
6037     * @throws SecurityException if {@code admin} is not a device owner.
6038     */
6039    public boolean removeUser(@NonNull ComponentName admin, UserHandle userHandle) {
6040        throwIfParentInstance("removeUser");
6041        try {
6042            return mService.removeUser(admin, userHandle);
6043        } catch (RemoteException re) {
6044            throw re.rethrowFromSystemServer();
6045        }
6046    }
6047
6048    /**
6049     * Called by a device owner to switch the specified user to the foreground.
6050     *
6051     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6052     * @param userHandle the user to switch to; null will switch to primary.
6053     * @return {@code true} if the switch was successful, {@code false} otherwise.
6054     * @throws SecurityException if {@code admin} is not a device owner.
6055     * @see Intent#ACTION_USER_FOREGROUND
6056     */
6057    public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
6058        throwIfParentInstance("switchUser");
6059        try {
6060            return mService.switchUser(admin, userHandle);
6061        } catch (RemoteException re) {
6062            throw re.rethrowFromSystemServer();
6063        }
6064    }
6065
6066    /**
6067     * Retrieves the application restrictions for a given target application running in the calling
6068     * user.
6069     * <p>
6070     * The caller must be a profile or device owner on that user, or the package allowed to manage
6071     * application restrictions via {@link #setDelegatedScopes} with the
6072     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
6073     *
6074     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
6075     *
6076     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6077     *            {@code null} if called by the application restrictions managing package.
6078     * @param packageName The name of the package to fetch restricted settings of.
6079     * @return {@link Bundle} of settings corresponding to what was set last time
6080     *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
6081     *         {@link Bundle} if no restrictions have been set.
6082     * @throws SecurityException if {@code admin} is not a device or profile owner.
6083     * @see #setDelegatedScopes
6084     * @see #DELEGATION_APP_RESTRICTIONS
6085     */
6086    @WorkerThread
6087    public @NonNull Bundle getApplicationRestrictions(
6088            @Nullable ComponentName admin, String packageName) {
6089        throwIfParentInstance("getApplicationRestrictions");
6090        if (mService != null) {
6091            try {
6092                return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
6093                        packageName);
6094            } catch (RemoteException e) {
6095                throw e.rethrowFromSystemServer();
6096            }
6097        }
6098        return null;
6099    }
6100
6101    /**
6102     * Called by a profile or device owner to set a user restriction specified by the key.
6103     * <p>
6104     * The calling device admin must be a profile or device owner; if it is not, a security
6105     * exception will be thrown.
6106     *
6107     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6108     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6109     *            for the list of keys.
6110     * @throws SecurityException if {@code admin} is not a device or profile owner.
6111     */
6112    public void addUserRestriction(@NonNull ComponentName admin, String key) {
6113        throwIfParentInstance("addUserRestriction");
6114        if (mService != null) {
6115            try {
6116                mService.setUserRestriction(admin, key, true);
6117            } catch (RemoteException e) {
6118                throw e.rethrowFromSystemServer();
6119            }
6120        }
6121    }
6122
6123    /**
6124     * Called by a profile or device owner to clear a user restriction specified by the key.
6125     * <p>
6126     * The calling device admin must be a profile or device owner; if it is not, a security
6127     * exception will be thrown.
6128     *
6129     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6130     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6131     *            for the list of keys.
6132     * @throws SecurityException if {@code admin} is not a device or profile owner.
6133     */
6134    public void clearUserRestriction(@NonNull ComponentName admin, String key) {
6135        throwIfParentInstance("clearUserRestriction");
6136        if (mService != null) {
6137            try {
6138                mService.setUserRestriction(admin, key, false);
6139            } catch (RemoteException e) {
6140                throw e.rethrowFromSystemServer();
6141            }
6142        }
6143    }
6144
6145    /**
6146     * Called by a profile or device owner to get user restrictions set with
6147     * {@link #addUserRestriction(ComponentName, String)}.
6148     * <p>
6149     * The target user may have more restrictions set by the system or other device owner / profile
6150     * owner. To get all the user restrictions currently set, use
6151     * {@link UserManager#getUserRestrictions()}.
6152     *
6153     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6154     * @throws SecurityException if {@code admin} is not a device or profile owner.
6155     */
6156    public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
6157        throwIfParentInstance("getUserRestrictions");
6158        Bundle ret = null;
6159        if (mService != null) {
6160            try {
6161                ret = mService.getUserRestrictions(admin);
6162            } catch (RemoteException e) {
6163                throw e.rethrowFromSystemServer();
6164            }
6165        }
6166        return ret == null ? new Bundle() : ret;
6167    }
6168
6169    /**
6170     * Called by any app to display a support dialog when a feature was disabled by an admin.
6171     * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
6172     * display the dialog. It will tell the user that the feature indicated by {@code restriction}
6173     * was disabled by an admin, and include a link for more information. The default content of
6174     * the dialog can be changed by the restricting admin via
6175     * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
6176     * set (i.e. the feature is available), then the return value will be {@code null}.
6177     * @param restriction Indicates for which feature the dialog should be displayed. Can be a
6178     *            user restriction from {@link UserManager}, e.g.
6179     *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
6180     *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
6181     * @return Intent An intent to be used to start the dialog-activity if the restriction is
6182     *            set by an admin, or null if the restriction does not exist or no admin set it.
6183     */
6184    public Intent createAdminSupportIntent(@NonNull String restriction) {
6185        throwIfParentInstance("createAdminSupportIntent");
6186        if (mService != null) {
6187            try {
6188                return mService.createAdminSupportIntent(restriction);
6189            } catch (RemoteException e) {
6190                throw e.rethrowFromSystemServer();
6191            }
6192        }
6193        return null;
6194    }
6195
6196    /**
6197     * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
6198     * actual package file remain. This function can be called by a device owner, profile owner, or
6199     * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6200     * {@link #setDelegatedScopes}.
6201     *
6202     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6203     *            {@code null} if the caller is a package access delegate.
6204     * @param packageName The name of the package to hide or unhide.
6205     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
6206     *            unhidden.
6207     * @return boolean Whether the hidden setting of the package was successfully updated.
6208     * @throws SecurityException if {@code admin} is not a device or profile owner.
6209     * @see #setDelegatedScopes
6210     * @see #DELEGATION_PACKAGE_ACCESS
6211     */
6212    public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
6213            boolean hidden) {
6214        throwIfParentInstance("setApplicationHidden");
6215        if (mService != null) {
6216            try {
6217                return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
6218                        hidden);
6219            } catch (RemoteException e) {
6220                throw e.rethrowFromSystemServer();
6221            }
6222        }
6223        return false;
6224    }
6225
6226    /**
6227     * Determine if a package is hidden. This function can be called by a device owner, profile
6228     * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6229     * {@link #setDelegatedScopes}.
6230     *
6231     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6232     *            {@code null} if the caller is a package access delegate.
6233     * @param packageName The name of the package to retrieve the hidden status of.
6234     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
6235     * @throws SecurityException if {@code admin} is not a device or profile owner.
6236     * @see #setDelegatedScopes
6237     * @see #DELEGATION_PACKAGE_ACCESS
6238     */
6239    public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
6240        throwIfParentInstance("isApplicationHidden");
6241        if (mService != null) {
6242            try {
6243                return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName);
6244            } catch (RemoteException e) {
6245                throw e.rethrowFromSystemServer();
6246            }
6247        }
6248        return false;
6249    }
6250
6251    /**
6252     * Re-enable a system app that was disabled by default when the user was initialized. This
6253     * function can be called by a device owner, profile owner, or by a delegate given the
6254     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6255     *
6256     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6257     *            {@code null} if the caller is an enable system app delegate.
6258     * @param packageName The package to be re-enabled in the calling profile.
6259     * @throws SecurityException if {@code admin} is not a device or profile owner.
6260     * @see #setDelegatedScopes
6261     * @see #DELEGATION_PACKAGE_ACCESS
6262     */
6263    public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
6264        throwIfParentInstance("enableSystemApp");
6265        if (mService != null) {
6266            try {
6267                mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
6268            } catch (RemoteException e) {
6269                throw e.rethrowFromSystemServer();
6270            }
6271        }
6272    }
6273
6274    /**
6275     * Re-enable system apps by intent that were disabled by default when the user was initialized.
6276     * This function can be called by a device owner, profile owner, or by a delegate given the
6277     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6278     *
6279     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6280     *            {@code null} if the caller is an enable system app delegate.
6281     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
6282     *            intent will be re-enabled in the calling profile.
6283     * @return int The number of activities that matched the intent and were installed.
6284     * @throws SecurityException if {@code admin} is not a device or profile owner.
6285     * @see #setDelegatedScopes
6286     * @see #DELEGATION_PACKAGE_ACCESS
6287     */
6288    public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
6289        throwIfParentInstance("enableSystemApp");
6290        if (mService != null) {
6291            try {
6292                return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
6293            } catch (RemoteException e) {
6294                throw e.rethrowFromSystemServer();
6295            }
6296        }
6297        return 0;
6298    }
6299
6300    /**
6301     * Called by a device owner or profile owner to disable account management for a specific type
6302     * of account.
6303     * <p>
6304     * The calling device admin must be a device owner or profile owner. If it is not, a security
6305     * exception will be thrown.
6306     * <p>
6307     * When account management is disabled for an account type, adding or removing an account of
6308     * that type will not be possible.
6309     * <p>
6310     * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
6311     * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
6312     * management for a specific type is disabled.
6313     *
6314     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6315     * @param accountType For which account management is disabled or enabled.
6316     * @param disabled The boolean indicating that account management will be disabled (true) or
6317     *            enabled (false).
6318     * @throws SecurityException if {@code admin} is not a device or profile owner.
6319     */
6320    public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
6321            boolean disabled) {
6322        throwIfParentInstance("setAccountManagementDisabled");
6323        if (mService != null) {
6324            try {
6325                mService.setAccountManagementDisabled(admin, accountType, disabled);
6326            } catch (RemoteException e) {
6327                throw e.rethrowFromSystemServer();
6328            }
6329        }
6330    }
6331
6332    /**
6333     * Gets the array of accounts for which account management is disabled by the profile owner.
6334     *
6335     * <p> Account management can be disabled/enabled by calling
6336     * {@link #setAccountManagementDisabled}.
6337     *
6338     * @return a list of account types for which account management has been disabled.
6339     *
6340     * @see #setAccountManagementDisabled
6341     */
6342    public @Nullable String[] getAccountTypesWithManagementDisabled() {
6343        throwIfParentInstance("getAccountTypesWithManagementDisabled");
6344        return getAccountTypesWithManagementDisabledAsUser(myUserId());
6345    }
6346
6347    /**
6348     * @see #getAccountTypesWithManagementDisabled()
6349     * @hide
6350     */
6351    public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
6352        if (mService != null) {
6353            try {
6354                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
6355            } catch (RemoteException e) {
6356                throw e.rethrowFromSystemServer();
6357            }
6358        }
6359
6360        return null;
6361    }
6362
6363    /**
6364     * Sets which packages may enter lock task mode.
6365     * <p>
6366     * Any packages that share uid with an allowed package will also be allowed to activate lock
6367     * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
6368     * package list results in locked tasks belonging to those packages to be finished.
6369     * <p>
6370     * This function can only be called by the device owner or by a profile owner of a user/profile
6371     * that is affiliated with the device owner user. See {@link #setAffiliationIds}. Any packages
6372     * set via this method will be cleared if the user becomes unaffiliated.
6373     *
6374     * @param packages The list of packages allowed to enter lock task mode
6375     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6376     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
6377     * an affiliated user or profile.
6378     * @see Activity#startLockTask()
6379     * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
6380     * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
6381     * @see UserManager#DISALLOW_CREATE_WINDOWS
6382     */
6383    public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
6384            throws SecurityException {
6385        throwIfParentInstance("setLockTaskPackages");
6386        if (mService != null) {
6387            try {
6388                mService.setLockTaskPackages(admin, packages);
6389            } catch (RemoteException e) {
6390                throw e.rethrowFromSystemServer();
6391            }
6392        }
6393    }
6394
6395    /**
6396     * Returns the list of packages allowed to start the lock task mode.
6397     *
6398     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
6399     * an affiliated user or profile.
6400     * @see #setLockTaskPackages
6401     */
6402    public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
6403        throwIfParentInstance("getLockTaskPackages");
6404        if (mService != null) {
6405            try {
6406                return mService.getLockTaskPackages(admin);
6407            } catch (RemoteException e) {
6408                throw e.rethrowFromSystemServer();
6409            }
6410        }
6411        return new String[0];
6412    }
6413
6414    /**
6415     * This function lets the caller know whether the given component is allowed to start the
6416     * lock task mode.
6417     * @param pkg The package to check
6418     */
6419    public boolean isLockTaskPermitted(String pkg) {
6420        throwIfParentInstance("isLockTaskPermitted");
6421        if (mService != null) {
6422            try {
6423                return mService.isLockTaskPermitted(pkg);
6424            } catch (RemoteException e) {
6425                throw e.rethrowFromSystemServer();
6426            }
6427        }
6428        return false;
6429    }
6430
6431    /**
6432     * Called by device owners to update {@link android.provider.Settings.Global} settings.
6433     * Validation that the value of the setting is in the correct form for the setting type should
6434     * be performed by the caller.
6435     * <p>
6436     * The settings that can be updated with this method are:
6437     * <ul>
6438     * <li>{@link android.provider.Settings.Global#ADB_ENABLED}</li>
6439     * <li>{@link android.provider.Settings.Global#AUTO_TIME}</li>
6440     * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE}</li>
6441     * <li>{@link android.provider.Settings.Global#DATA_ROAMING}</li>
6442     * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
6443     * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}</li>
6444     * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
6445     * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
6446     * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
6447     * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
6448     * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
6449     * </ul>
6450     * <p>
6451     * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
6452     * <ul>
6453     * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
6454     * {@link android.bluetooth.BluetoothAdapter#enable()} and
6455     * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
6456     * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
6457     * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
6458     * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
6459     * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
6460     * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
6461     * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
6462     * </ul>
6463     *
6464     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6465     * @param setting The name of the setting to update.
6466     * @param value The value to update the setting to.
6467     * @throws SecurityException if {@code admin} is not a device owner.
6468     */
6469    public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
6470        throwIfParentInstance("setGlobalSetting");
6471        if (mService != null) {
6472            try {
6473                mService.setGlobalSetting(admin, setting, value);
6474            } catch (RemoteException e) {
6475                throw e.rethrowFromSystemServer();
6476            }
6477        }
6478    }
6479
6480    /**
6481     * Called by profile or device owners to update {@link android.provider.Settings.Secure}
6482     * settings. Validation that the value of the setting is in the correct form for the setting
6483     * type should be performed by the caller.
6484     * <p>
6485     * The settings that can be updated by a profile or device owner with this method are:
6486     * <ul>
6487     * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
6488     * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
6489     * </ul>
6490     * <p>
6491     * A device owner can additionally update the following settings:
6492     * <ul>
6493     * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}</li>
6494     * </ul>
6495     *
6496     * <strong>Note: Starting from Android O, apps should no longer call this method with the
6497     * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
6498     * deprecated. Instead, device owners or profile owners should use the restriction
6499     * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
6500     * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
6501     * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
6502     * an {@link UnsupportedOperationException} is thrown.
6503     * </strong>
6504     *
6505     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6506     * @param setting The name of the setting to update.
6507     * @param value The value to update the setting to.
6508     * @throws SecurityException if {@code admin} is not a device or profile owner.
6509     */
6510    public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
6511        throwIfParentInstance("setSecureSetting");
6512        if (mService != null) {
6513            try {
6514                mService.setSecureSetting(admin, setting, value);
6515            } catch (RemoteException e) {
6516                throw e.rethrowFromSystemServer();
6517            }
6518        }
6519    }
6520
6521    /**
6522     * Designates a specific service component as the provider for making permission requests of a
6523     * local or remote administrator of the user.
6524     * <p/>
6525     * Only a profile owner can designate the restrictions provider.
6526     *
6527     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6528     * @param provider The component name of the service that implements
6529     *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
6530     *            provider previously assigned.
6531     * @throws SecurityException if {@code admin} is not a device or profile owner.
6532     */
6533    public void setRestrictionsProvider(@NonNull ComponentName admin,
6534            @Nullable ComponentName provider) {
6535        throwIfParentInstance("setRestrictionsProvider");
6536        if (mService != null) {
6537            try {
6538                mService.setRestrictionsProvider(admin, provider);
6539            } catch (RemoteException re) {
6540                throw re.rethrowFromSystemServer();
6541            }
6542        }
6543    }
6544
6545    /**
6546     * Called by profile or device owners to set the master volume mute on or off.
6547     * This has no effect when set on a managed profile.
6548     *
6549     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6550     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
6551     * @throws SecurityException if {@code admin} is not a device or profile owner.
6552     */
6553    public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
6554        throwIfParentInstance("setMasterVolumeMuted");
6555        if (mService != null) {
6556            try {
6557                mService.setMasterVolumeMuted(admin, on);
6558            } catch (RemoteException re) {
6559                throw re.rethrowFromSystemServer();
6560            }
6561        }
6562    }
6563
6564    /**
6565     * Called by profile or device owners to check whether the master volume mute is on or off.
6566     *
6567     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6568     * @return {@code true} if master volume is muted, {@code false} if it's not.
6569     * @throws SecurityException if {@code admin} is not a device or profile owner.
6570     */
6571    public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
6572        throwIfParentInstance("isMasterVolumeMuted");
6573        if (mService != null) {
6574            try {
6575                return mService.isMasterVolumeMuted(admin);
6576            } catch (RemoteException re) {
6577                throw re.rethrowFromSystemServer();
6578            }
6579        }
6580        return false;
6581    }
6582
6583    /**
6584     * Change whether a user can uninstall a package. This function can be called by a device owner,
6585     * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
6586     * {@link #setDelegatedScopes}.
6587     *
6588     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6589     *             {@code null} if the caller is a block uninstall delegate.
6590     * @param packageName package to change.
6591     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
6592     * @throws SecurityException if {@code admin} is not a device or profile owner.
6593     * @see #setDelegatedScopes
6594     * @see #DELEGATION_BLOCK_UNINSTALL
6595     */
6596    public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
6597            boolean uninstallBlocked) {
6598        throwIfParentInstance("setUninstallBlocked");
6599        if (mService != null) {
6600            try {
6601                mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
6602                    uninstallBlocked);
6603            } catch (RemoteException re) {
6604                throw re.rethrowFromSystemServer();
6605            }
6606        }
6607    }
6608
6609    /**
6610     * Check whether the user has been blocked by device policy from uninstalling a package.
6611     * Requires the caller to be the profile owner if checking a specific admin's policy.
6612     * <p>
6613     * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
6614     * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
6615     * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
6616     * will cause a NullPointerException to be raised.
6617     *
6618     * @param admin The name of the admin component whose blocking policy will be checked, or
6619     *            {@code null} to check whether any admin has blocked the uninstallation.
6620     * @param packageName package to check.
6621     * @return true if uninstallation is blocked.
6622     * @throws SecurityException if {@code admin} is not a device or profile owner.
6623     */
6624    public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
6625        throwIfParentInstance("isUninstallBlocked");
6626        if (mService != null) {
6627            try {
6628                return mService.isUninstallBlocked(admin, packageName);
6629            } catch (RemoteException re) {
6630                throw re.rethrowFromSystemServer();
6631            }
6632        }
6633        return false;
6634    }
6635
6636    /**
6637     * Called by the profile owner of a managed profile to enable widget providers from a given
6638     * package to be available in the parent profile. As a result the user will be able to add
6639     * widgets from the white-listed package running under the profile to a widget host which runs
6640     * under the parent profile, for example the home screen. Note that a package may have zero or
6641     * more provider components, where each component provides a different widget type.
6642     * <p>
6643     * <strong>Note:</strong> By default no widget provider package is white-listed.
6644     *
6645     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6646     * @param packageName The package from which widget providers are white-listed.
6647     * @return Whether the package was added.
6648     * @throws SecurityException if {@code admin} is not a profile owner.
6649     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
6650     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
6651     */
6652    public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
6653        throwIfParentInstance("addCrossProfileWidgetProvider");
6654        if (mService != null) {
6655            try {
6656                return mService.addCrossProfileWidgetProvider(admin, packageName);
6657            } catch (RemoteException re) {
6658                throw re.rethrowFromSystemServer();
6659            }
6660        }
6661        return false;
6662    }
6663
6664    /**
6665     * Called by the profile owner of a managed profile to disable widget providers from a given
6666     * package to be available in the parent profile. For this method to take effect the package
6667     * should have been added via
6668     * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
6669     * <p>
6670     * <strong>Note:</strong> By default no widget provider package is white-listed.
6671     *
6672     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6673     * @param packageName The package from which widget providers are no longer white-listed.
6674     * @return Whether the package was removed.
6675     * @throws SecurityException if {@code admin} is not a profile owner.
6676     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
6677     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
6678     */
6679    public boolean removeCrossProfileWidgetProvider(
6680            @NonNull ComponentName admin, String packageName) {
6681        throwIfParentInstance("removeCrossProfileWidgetProvider");
6682        if (mService != null) {
6683            try {
6684                return mService.removeCrossProfileWidgetProvider(admin, packageName);
6685            } catch (RemoteException re) {
6686                throw re.rethrowFromSystemServer();
6687            }
6688        }
6689        return false;
6690    }
6691
6692    /**
6693     * Called by the profile owner of a managed profile to query providers from which packages are
6694     * available in the parent profile.
6695     *
6696     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6697     * @return The white-listed package list.
6698     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
6699     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
6700     * @throws SecurityException if {@code admin} is not a profile owner.
6701     */
6702    public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
6703        throwIfParentInstance("getCrossProfileWidgetProviders");
6704        if (mService != null) {
6705            try {
6706                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
6707                if (providers != null) {
6708                    return providers;
6709                }
6710            } catch (RemoteException re) {
6711                throw re.rethrowFromSystemServer();
6712            }
6713        }
6714        return Collections.emptyList();
6715    }
6716
6717    /**
6718     * Called by profile or device owners to set the user's photo.
6719     *
6720     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6721     * @param icon the bitmap to set as the photo.
6722     * @throws SecurityException if {@code admin} is not a device or profile owner.
6723     */
6724    public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
6725        throwIfParentInstance("setUserIcon");
6726        try {
6727            mService.setUserIcon(admin, icon);
6728        } catch (RemoteException re) {
6729            throw re.rethrowFromSystemServer();
6730        }
6731    }
6732
6733    /**
6734     * Called by device owners to set a local system update policy. When a new policy is set,
6735     * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
6736     *
6737     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
6738     *            components in the device owner package can set system update policies and the most
6739     *            recent policy takes effect.
6740     * @param policy the new policy, or {@code null} to clear the current policy.
6741     * @throws SecurityException if {@code admin} is not a device owner.
6742     * @see SystemUpdatePolicy
6743     */
6744    public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
6745        throwIfParentInstance("setSystemUpdatePolicy");
6746        if (mService != null) {
6747            try {
6748                mService.setSystemUpdatePolicy(admin, policy);
6749            } catch (RemoteException re) {
6750                throw re.rethrowFromSystemServer();
6751            }
6752        }
6753    }
6754
6755    /**
6756     * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
6757     *
6758     * @return The current policy object, or {@code null} if no policy is set.
6759     */
6760    public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
6761        throwIfParentInstance("getSystemUpdatePolicy");
6762        if (mService != null) {
6763            try {
6764                return mService.getSystemUpdatePolicy();
6765            } catch (RemoteException re) {
6766                throw re.rethrowFromSystemServer();
6767            }
6768        }
6769        return null;
6770    }
6771
6772    /**
6773     * Called by a device owner to disable the keyguard altogether.
6774     * <p>
6775     * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
6776     * type. However, this call has no effect if a password, pin or pattern is currently set. If a
6777     * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
6778     * disabled.
6779     *
6780     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6781     * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
6782     * @return {@code false} if attempting to disable the keyguard while a lock password was in
6783     *         place. {@code true} otherwise.
6784     * @throws SecurityException if {@code admin} is not a device owner.
6785     */
6786    public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
6787        throwIfParentInstance("setKeyguardDisabled");
6788        try {
6789            return mService.setKeyguardDisabled(admin, disabled);
6790        } catch (RemoteException re) {
6791            throw re.rethrowFromSystemServer();
6792        }
6793    }
6794
6795    /**
6796     * Called by device owner to disable the status bar. Disabling the status bar blocks
6797     * notifications, quick settings and other screen overlays that allow escaping from a single use
6798     * device.
6799     *
6800     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6801     * @param disabled {@code true} disables the status bar, {@code false} reenables it.
6802     * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
6803     * @throws SecurityException if {@code admin} is not a device owner.
6804     */
6805    public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
6806        throwIfParentInstance("setStatusBarDisabled");
6807        try {
6808            return mService.setStatusBarDisabled(admin, disabled);
6809        } catch (RemoteException re) {
6810            throw re.rethrowFromSystemServer();
6811        }
6812    }
6813
6814    /**
6815     * Called by the system update service to notify device and profile owners of pending system
6816     * updates.
6817     *
6818     * This method should only be used when it is unknown whether the pending system
6819     * update is a security patch. Otherwise, use
6820     * {@link #notifyPendingSystemUpdate(long, boolean)}.
6821     *
6822     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
6823     *         indicating when the current pending update was first available. {@code -1} if no
6824     *         update is available.
6825     * @see #notifyPendingSystemUpdate(long, boolean)
6826     * @hide
6827     */
6828    @SystemApi
6829    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
6830    public void notifyPendingSystemUpdate(long updateReceivedTime) {
6831        throwIfParentInstance("notifyPendingSystemUpdate");
6832        if (mService != null) {
6833            try {
6834                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
6835            } catch (RemoteException re) {
6836                throw re.rethrowFromSystemServer();
6837            }
6838        }
6839    }
6840
6841    /**
6842     * Called by the system update service to notify device and profile owners of pending system
6843     * updates.
6844     *
6845     * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
6846     * when it is known whether the pending system update is a security patch.
6847     *
6848     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
6849     *         indicating when the current pending update was first available. {@code -1} if no
6850     *         update is available.
6851     * @param isSecurityPatch {@code true} if this system update is purely a security patch;
6852     *         {@code false} if not.
6853     * @see #notifyPendingSystemUpdate(long)
6854     * @hide
6855     */
6856    @SystemApi
6857    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
6858    public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
6859        throwIfParentInstance("notifyPendingSystemUpdate");
6860        if (mService != null) {
6861            try {
6862                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
6863                        isSecurityPatch));
6864            } catch (RemoteException re) {
6865                throw re.rethrowFromSystemServer();
6866            }
6867        }
6868    }
6869
6870    /**
6871     * Called by device or profile owners to get information about a pending system update.
6872     *
6873     * @param admin Which profile or device owner this request is associated with.
6874     * @return Information about a pending system update or {@code null} if no update pending.
6875     * @throws SecurityException if {@code admin} is not a device or profile owner.
6876     * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
6877     */
6878    public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
6879        throwIfParentInstance("getPendingSystemUpdate");
6880        try {
6881            return mService.getPendingSystemUpdate(admin);
6882        } catch (RemoteException re) {
6883            throw re.rethrowFromSystemServer();
6884        }
6885    }
6886
6887    /**
6888     * Set the default response for future runtime permission requests by applications. This
6889     * function can be called by a device owner, profile owner, or by a delegate given the
6890     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
6891     * The policy can allow for normal operation which prompts the user to grant a permission, or
6892     * can allow automatic granting or denying of runtime permission requests by an application.
6893     * This also applies to new permissions declared by app updates. When a permission is denied or
6894     * granted this way, the effect is equivalent to setting the permission * grant state via
6895     * {@link #setPermissionGrantState}.
6896     * <p/>
6897     * As this policy only acts on runtime permission requests, it only applies to applications
6898     * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
6899     *
6900     * @param admin Which profile or device owner this request is associated with.
6901     * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
6902     *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
6903     * @throws SecurityException if {@code admin} is not a device or profile owner.
6904     * @see #setPermissionGrantState
6905     * @see #setDelegatedScopes
6906     * @see #DELEGATION_PERMISSION_GRANT
6907     */
6908    public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
6909        throwIfParentInstance("setPermissionPolicy");
6910        try {
6911            mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
6912        } catch (RemoteException re) {
6913            throw re.rethrowFromSystemServer();
6914        }
6915    }
6916
6917    /**
6918     * Returns the current runtime permission policy set by the device or profile owner. The
6919     * default is {@link #PERMISSION_POLICY_PROMPT}.
6920     *
6921     * @param admin Which profile or device owner this request is associated with.
6922     * @return the current policy for future permission requests.
6923     */
6924    public int getPermissionPolicy(ComponentName admin) {
6925        throwIfParentInstance("getPermissionPolicy");
6926        try {
6927            return mService.getPermissionPolicy(admin);
6928        } catch (RemoteException re) {
6929            throw re.rethrowFromSystemServer();
6930        }
6931    }
6932
6933    /**
6934     * Sets the grant state of a runtime permission for a specific application. The state can be
6935     * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
6936     * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
6937     * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
6938     * the permission is granted and the user cannot manage it through the UI. This might affect all
6939     * permissions in a group that the runtime permission belongs to. This method can only be called
6940     * by a profile owner, device owner, or a delegate given the
6941     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
6942     * <p/>
6943     * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
6944     * the permission. It retains the previous grant, if any.
6945     * <p/>
6946     * Permissions can be granted or revoked only for applications built with a
6947     * {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
6948     *
6949     * @param admin Which profile or device owner this request is associated with.
6950     * @param packageName The application to grant or revoke a permission to.
6951     * @param permission The permission to grant or revoke.
6952     * @param grantState The permission grant state which is one of
6953     *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
6954     *            {@link #PERMISSION_GRANT_STATE_GRANTED},
6955     * @return whether the permission was successfully granted or revoked.
6956     * @throws SecurityException if {@code admin} is not a device or profile owner.
6957     * @see #PERMISSION_GRANT_STATE_DENIED
6958     * @see #PERMISSION_GRANT_STATE_DEFAULT
6959     * @see #PERMISSION_GRANT_STATE_GRANTED
6960     * @see #setDelegatedScopes
6961     * @see #DELEGATION_PERMISSION_GRANT
6962     */
6963    public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName,
6964            String permission, int grantState) {
6965        throwIfParentInstance("setPermissionGrantState");
6966        try {
6967            return mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
6968                    permission, grantState);
6969        } catch (RemoteException re) {
6970            throw re.rethrowFromSystemServer();
6971        }
6972    }
6973
6974    /**
6975     * Returns the current grant state of a runtime permission for a specific application. This
6976     * function can be called by a device owner, profile owner, or by a delegate given the
6977     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
6978     *
6979     * @param admin Which profile or device owner this request is associated with, or {@code null}
6980     *            if the caller is a permission grant delegate.
6981     * @param packageName The application to check the grant state for.
6982     * @param permission The permission to check for.
6983     * @return the current grant state specified by device policy. If the profile or device owner
6984     *         has not set a grant state, the return value is
6985     *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
6986     *         permission is currently granted for the package.
6987     *         <p/>
6988     *         If a grant state was set by the profile or device owner, then the return value will
6989     *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
6990     *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
6991     *         currently denied or granted.
6992     * @throws SecurityException if {@code admin} is not a device or profile owner.
6993     * @see #setPermissionGrantState(ComponentName, String, String, int)
6994     * @see PackageManager#checkPermission(String, String)
6995     * @see #setDelegatedScopes
6996     * @see #DELEGATION_PERMISSION_GRANT
6997     */
6998    public int getPermissionGrantState(@Nullable ComponentName admin, String packageName,
6999            String permission) {
7000        throwIfParentInstance("getPermissionGrantState");
7001        try {
7002            return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
7003                    permission);
7004        } catch (RemoteException re) {
7005            throw re.rethrowFromSystemServer();
7006        }
7007    }
7008
7009    /**
7010     * Returns whether it is possible for the caller to initiate provisioning of a managed profile
7011     * or device, setting itself as the device or profile owner.
7012     *
7013     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7014     * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
7015     * @return whether provisioning a managed profile or device is possible.
7016     * @throws IllegalArgumentException if the supplied action is not valid.
7017     */
7018    public boolean isProvisioningAllowed(@NonNull String action) {
7019        throwIfParentInstance("isProvisioningAllowed");
7020        try {
7021            return mService.isProvisioningAllowed(action, mContext.getPackageName());
7022        } catch (RemoteException re) {
7023            throw re.rethrowFromSystemServer();
7024        }
7025    }
7026
7027    /**
7028     * Checks whether it is possible to initiate provisioning a managed device,
7029     * profile or user, setting the given package as owner.
7030     *
7031     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7032     *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
7033     *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
7034     *        {@link #ACTION_PROVISION_MANAGED_USER}
7035     * @param packageName The package of the component that would be set as device, user, or profile
7036     *        owner.
7037     * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
7038     * @hide
7039     */
7040    public @ProvisioningPreCondition int checkProvisioningPreCondition(
7041            String action, @NonNull String packageName) {
7042        try {
7043            return mService.checkProvisioningPreCondition(action, packageName);
7044        } catch (RemoteException re) {
7045            throw re.rethrowFromSystemServer();
7046        }
7047    }
7048
7049    /**
7050     * Return if this user is a managed profile of another user. An admin can become the profile
7051     * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
7052     * user with {@link #createAndManageUser}
7053     * @param admin Which profile owner this request is associated with.
7054     * @return if this user is a managed profile of another user.
7055     */
7056    public boolean isManagedProfile(@NonNull ComponentName admin) {
7057        throwIfParentInstance("isManagedProfile");
7058        try {
7059            return mService.isManagedProfile(admin);
7060        } catch (RemoteException re) {
7061            throw re.rethrowFromSystemServer();
7062        }
7063    }
7064
7065    /**
7066     * @hide
7067     * Return if this user is a system-only user. An admin can manage a device from a system only
7068     * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
7069     * @param admin Which device owner this request is associated with.
7070     * @return if this user is a system-only user.
7071     */
7072    public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
7073        try {
7074            return mService.isSystemOnlyUser(admin);
7075        } catch (RemoteException re) {
7076            throw re.rethrowFromSystemServer();
7077        }
7078    }
7079
7080    /**
7081     * Called by device owner to get the MAC address of the Wi-Fi device.
7082     *
7083     * @param admin Which device owner this request is associated with.
7084     * @return the MAC address of the Wi-Fi device, or null when the information is not available.
7085     *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
7086     *         <p>
7087     *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
7088     * @throws SecurityException if {@code admin} is not a device owner.
7089     */
7090    public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
7091        throwIfParentInstance("getWifiMacAddress");
7092        try {
7093            return mService.getWifiMacAddress(admin);
7094        } catch (RemoteException re) {
7095            throw re.rethrowFromSystemServer();
7096        }
7097    }
7098
7099    /**
7100     * Called by device owner to reboot the device. If there is an ongoing call on the device,
7101     * throws an {@link IllegalStateException}.
7102     * @param admin Which device owner the request is associated with.
7103     * @throws IllegalStateException if device has an ongoing call.
7104     * @throws SecurityException if {@code admin} is not a device owner.
7105     * @see TelephonyManager#CALL_STATE_IDLE
7106     */
7107    public void reboot(@NonNull ComponentName admin) {
7108        throwIfParentInstance("reboot");
7109        try {
7110            mService.reboot(admin);
7111        } catch (RemoteException re) {
7112            throw re.rethrowFromSystemServer();
7113        }
7114    }
7115
7116    /**
7117     * Called by a device admin to set the short support message. This will be displayed to the user
7118     * in settings screens where funtionality has been disabled by the admin. The message should be
7119     * limited to a short statement such as "This setting is disabled by your administrator. Contact
7120     * someone@example.com for support." If the message is longer than 200 characters it may be
7121     * truncated.
7122     * <p>
7123     * If the short support message needs to be localized, it is the responsibility of the
7124     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7125     * and set a new version of this string accordingly.
7126     *
7127     * @see #setLongSupportMessage
7128     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7129     * @param message Short message to be displayed to the user in settings or null to clear the
7130     *            existing message.
7131     * @throws SecurityException if {@code admin} is not an active administrator.
7132     */
7133    public void setShortSupportMessage(@NonNull ComponentName admin,
7134            @Nullable CharSequence message) {
7135        throwIfParentInstance("setShortSupportMessage");
7136        if (mService != null) {
7137            try {
7138                mService.setShortSupportMessage(admin, message);
7139            } catch (RemoteException e) {
7140                throw e.rethrowFromSystemServer();
7141            }
7142        }
7143    }
7144
7145    /**
7146     * Called by a device admin to get the short support message.
7147     *
7148     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7149     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
7150     *         null if no message has been set.
7151     * @throws SecurityException if {@code admin} is not an active administrator.
7152     */
7153    public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
7154        throwIfParentInstance("getShortSupportMessage");
7155        if (mService != null) {
7156            try {
7157                return mService.getShortSupportMessage(admin);
7158            } catch (RemoteException e) {
7159                throw e.rethrowFromSystemServer();
7160            }
7161        }
7162        return null;
7163    }
7164
7165    /**
7166     * Called by a device admin to set the long support message. This will be displayed to the user
7167     * in the device administators settings screen.
7168     * <p>
7169     * If the long support message needs to be localized, it is the responsibility of the
7170     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7171     * and set a new version of this string accordingly.
7172     *
7173     * @see #setShortSupportMessage
7174     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7175     * @param message Long message to be displayed to the user in settings or null to clear the
7176     *            existing message.
7177     * @throws SecurityException if {@code admin} is not an active administrator.
7178     */
7179    public void setLongSupportMessage(@NonNull ComponentName admin,
7180            @Nullable CharSequence message) {
7181        throwIfParentInstance("setLongSupportMessage");
7182        if (mService != null) {
7183            try {
7184                mService.setLongSupportMessage(admin, message);
7185            } catch (RemoteException e) {
7186                throw e.rethrowFromSystemServer();
7187            }
7188        }
7189    }
7190
7191    /**
7192     * Called by a device admin to get the long support message.
7193     *
7194     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7195     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
7196     *         null if no message has been set.
7197     * @throws SecurityException if {@code admin} is not an active administrator.
7198     */
7199    public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
7200        throwIfParentInstance("getLongSupportMessage");
7201        if (mService != null) {
7202            try {
7203                return mService.getLongSupportMessage(admin);
7204            } catch (RemoteException e) {
7205                throw e.rethrowFromSystemServer();
7206            }
7207        }
7208        return null;
7209    }
7210
7211    /**
7212     * Called by the system to get the short support message.
7213     *
7214     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7215     * @param userHandle user id the admin is running as.
7216     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
7217     *
7218     * @hide
7219     */
7220    public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
7221            int userHandle) {
7222        if (mService != null) {
7223            try {
7224                return mService.getShortSupportMessageForUser(admin, userHandle);
7225            } catch (RemoteException e) {
7226                throw e.rethrowFromSystemServer();
7227            }
7228        }
7229        return null;
7230    }
7231
7232
7233    /**
7234     * Called by the system to get the long support message.
7235     *
7236     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7237     * @param userHandle user id the admin is running as.
7238     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
7239     *
7240     * @hide
7241     */
7242    public @Nullable CharSequence getLongSupportMessageForUser(
7243            @NonNull ComponentName admin, int userHandle) {
7244        if (mService != null) {
7245            try {
7246                return mService.getLongSupportMessageForUser(admin, userHandle);
7247            } catch (RemoteException e) {
7248                throw e.rethrowFromSystemServer();
7249            }
7250        }
7251        return null;
7252    }
7253
7254    /**
7255     * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
7256     * whose calls act on the parent profile.
7257     *
7258     * <p>The following methods are supported for the parent instance, all other methods will
7259     * throw a SecurityException when called on the parent instance:
7260     * <ul>
7261     * <li>{@link #getPasswordQuality}</li>
7262     * <li>{@link #setPasswordQuality}</li>
7263     * <li>{@link #getPasswordMinimumLength}</li>
7264     * <li>{@link #setPasswordMinimumLength}</li>
7265     * <li>{@link #getPasswordMinimumUpperCase}</li>
7266     * <li>{@link #setPasswordMinimumUpperCase}</li>
7267     * <li>{@link #getPasswordMinimumLowerCase}</li>
7268     * <li>{@link #setPasswordMinimumLowerCase}</li>
7269     * <li>{@link #getPasswordMinimumLetters}</li>
7270     * <li>{@link #setPasswordMinimumLetters}</li>
7271     * <li>{@link #getPasswordMinimumNumeric}</li>
7272     * <li>{@link #setPasswordMinimumNumeric}</li>
7273     * <li>{@link #getPasswordMinimumSymbols}</li>
7274     * <li>{@link #setPasswordMinimumSymbols}</li>
7275     * <li>{@link #getPasswordMinimumNonLetter}</li>
7276     * <li>{@link #setPasswordMinimumNonLetter}</li>
7277     * <li>{@link #getPasswordHistoryLength}</li>
7278     * <li>{@link #setPasswordHistoryLength}</li>
7279     * <li>{@link #getPasswordExpirationTimeout}</li>
7280     * <li>{@link #setPasswordExpirationTimeout}</li>
7281     * <li>{@link #getPasswordExpiration}</li>
7282     * <li>{@link #getPasswordMaximumLength}</li>
7283     * <li>{@link #isActivePasswordSufficient}</li>
7284     * <li>{@link #getCurrentFailedPasswordAttempts}</li>
7285     * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
7286     * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
7287     * <li>{@link #getMaximumTimeToLock}</li>
7288     * <li>{@link #setMaximumTimeToLock}</li>
7289     * <li>{@link #lockNow}</li>
7290     * <li>{@link #getKeyguardDisabledFeatures}</li>
7291     * <li>{@link #setKeyguardDisabledFeatures}</li>
7292     * <li>{@link #getTrustAgentConfiguration}</li>
7293     * <li>{@link #setTrustAgentConfiguration}</li>
7294     * <li>{@link #getRequiredStrongAuthTimeout}</li>
7295     * <li>{@link #setRequiredStrongAuthTimeout}</li>
7296     * </ul>
7297     *
7298     * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
7299     * @throws SecurityException if {@code admin} is not a profile owner.
7300     */
7301    public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
7302        throwIfParentInstance("getParentProfileInstance");
7303        try {
7304            if (!mService.isManagedProfile(admin)) {
7305                throw new SecurityException("The current user does not have a parent profile.");
7306            }
7307            return new DevicePolicyManager(mContext, mService, true);
7308        } catch (RemoteException e) {
7309            throw e.rethrowFromSystemServer();
7310        }
7311    }
7312
7313    /**
7314     * Called by device owner to control the security logging feature.
7315     *
7316     * <p> Security logs contain various information intended for security auditing purposes.
7317     * See {@link SecurityEvent} for details.
7318     *
7319     * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
7320     * are unaffiliated secondary users or profiles on the device, regardless of whether the
7321     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
7322     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
7323     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
7324     *
7325     * @param admin Which device owner this request is associated with.
7326     * @param enabled whether security logging should be enabled or not.
7327     * @throws SecurityException if {@code admin} is not a device owner.
7328     * @see #retrieveSecurityLogs
7329     */
7330    public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
7331        throwIfParentInstance("setSecurityLoggingEnabled");
7332        try {
7333            mService.setSecurityLoggingEnabled(admin, enabled);
7334        } catch (RemoteException re) {
7335            throw re.rethrowFromSystemServer();
7336        }
7337    }
7338
7339    /**
7340     * Return whether security logging is enabled or not by the device owner.
7341     *
7342     * <p>Can only be called by the device owner, otherwise a {@link SecurityException} will be
7343     * thrown.
7344     *
7345     * @param admin Which device owner this request is associated with.
7346     * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
7347     * @throws SecurityException if {@code admin} is not a device owner.
7348     */
7349    public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
7350        throwIfParentInstance("isSecurityLoggingEnabled");
7351        try {
7352            return mService.isSecurityLoggingEnabled(admin);
7353        } catch (RemoteException re) {
7354            throw re.rethrowFromSystemServer();
7355        }
7356    }
7357
7358    /**
7359     * Called by device owner to retrieve all new security logging entries since the last call to
7360     * this API after device boots.
7361     *
7362     * <p> Access to the logs is rate limited and it will only return new logs after the device
7363     * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
7364     *
7365     * <p>If there is any other user or profile on the device, it must be affiliated with the
7366     * device owner. Otherwise a {@link SecurityException} will be thrown. See
7367     * {@link #setAffiliationIds}
7368     *
7369     * @param admin Which device owner this request is associated with.
7370     * @return the new batch of security logs which is a list of {@link SecurityEvent},
7371     * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
7372     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
7373     * profile or secondary user that is not affiliated with the device owner user.
7374     * @see DeviceAdminReceiver#onSecurityLogsAvailable
7375     */
7376    public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
7377        throwIfParentInstance("retrieveSecurityLogs");
7378        try {
7379            ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
7380            if (list != null) {
7381                return list.getList();
7382            } else {
7383                // Rate limit exceeded.
7384                return null;
7385            }
7386        } catch (RemoteException re) {
7387            throw re.rethrowFromSystemServer();
7388        }
7389    }
7390
7391    /**
7392     * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
7393     * profile.
7394     *
7395     * @hide
7396     */
7397    public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
7398        mContext.checkSelfPermission(
7399                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
7400        if (!uInfo.isManagedProfile()) {
7401            throw new SecurityException("The user " + uInfo.id
7402                    + " does not have a parent profile.");
7403        }
7404        return new DevicePolicyManager(mContext, mService, true);
7405    }
7406
7407    /**
7408     * Called by device owners to retrieve device logs from before the device's last reboot.
7409     * <p>
7410     * <strong> This API is not supported on all devices. Calling this API on unsupported devices
7411     * will result in {@code null} being returned. The device logs are retrieved from a RAM region
7412     * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
7413     * about data corruption when parsing. </strong>
7414     *
7415     * <p>If there is any other user or profile on the device, it must be affiliated with the
7416     * device owner. Otherwise a {@link SecurityException} will be thrown. See
7417     * {@link #setAffiliationIds}
7418     *
7419     * @param admin Which device owner this request is associated with.
7420     * @return Device logs from before the latest reboot of the system, or {@code null} if this API
7421     *         is not supported on the device.
7422     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
7423     * profile or secondary user that is not affiliated with the device owner user.
7424     * @see #retrieveSecurityLogs
7425     */
7426    public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
7427            @NonNull ComponentName admin) {
7428        throwIfParentInstance("retrievePreRebootSecurityLogs");
7429        try {
7430            ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
7431            if (list != null) {
7432                return list.getList();
7433            } else {
7434                return null;
7435            }
7436        } catch (RemoteException re) {
7437            throw re.rethrowFromSystemServer();
7438        }
7439    }
7440
7441    /**
7442     * Called by a profile owner of a managed profile to set the color used for customization. This
7443     * color is used as background color of the confirm credentials screen for that user. The
7444     * default color is teal (#00796B).
7445     * <p>
7446     * The confirm credentials screen can be created using
7447     * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
7448     *
7449     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7450     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
7451     * @throws SecurityException if {@code admin} is not a profile owner.
7452     */
7453    public void setOrganizationColor(@NonNull ComponentName admin, int color) {
7454        throwIfParentInstance("setOrganizationColor");
7455        try {
7456            // always enforce alpha channel to have 100% opacity
7457            color |= 0xFF000000;
7458            mService.setOrganizationColor(admin, color);
7459        } catch (RemoteException re) {
7460            throw re.rethrowFromSystemServer();
7461        }
7462    }
7463
7464    /**
7465     * @hide
7466     *
7467     * Sets the color used for customization.
7468     *
7469     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
7470     * @param userId which user to set the color to.
7471     * @RequiresPermission(allOf = {
7472     *       Manifest.permission.MANAGE_USERS,
7473     *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
7474     */
7475    public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
7476        try {
7477            // always enforce alpha channel to have 100% opacity
7478            color |= 0xFF000000;
7479            mService.setOrganizationColorForUser(color, userId);
7480        } catch (RemoteException re) {
7481            throw re.rethrowFromSystemServer();
7482        }
7483    }
7484
7485    /**
7486     * Called by a profile owner of a managed profile to retrieve the color used for customization.
7487     * This color is used as background color of the confirm credentials screen for that user.
7488     *
7489     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7490     * @return The 24bit (0xRRGGBB) representation of the color to be used.
7491     * @throws SecurityException if {@code admin} is not a profile owner.
7492     */
7493    public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
7494        throwIfParentInstance("getOrganizationColor");
7495        try {
7496            return mService.getOrganizationColor(admin);
7497        } catch (RemoteException re) {
7498            throw re.rethrowFromSystemServer();
7499        }
7500    }
7501
7502    /**
7503     * @hide
7504     * Retrieve the customization color for a given user.
7505     *
7506     * @param userHandle The user id of the user we're interested in.
7507     * @return The 24bit (0xRRGGBB) representation of the color to be used.
7508     */
7509    public @ColorInt int getOrganizationColorForUser(int userHandle) {
7510        try {
7511            return mService.getOrganizationColorForUser(userHandle);
7512        } catch (RemoteException re) {
7513            throw re.rethrowFromSystemServer();
7514        }
7515    }
7516
7517    /**
7518     * Called by the device owner or profile owner to set the name of the organization under
7519     * management.
7520     * <p>
7521     * If the organization name needs to be localized, it is the responsibility of the
7522     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7523     * and set a new version of this string accordingly.
7524     *
7525     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7526     * @param title The organization name or {@code null} to clear a previously set name.
7527     * @throws SecurityException if {@code admin} is not a device or profile owner.
7528     */
7529    public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
7530        throwIfParentInstance("setOrganizationName");
7531        try {
7532            mService.setOrganizationName(admin, title);
7533        } catch (RemoteException re) {
7534            throw re.rethrowFromSystemServer();
7535        }
7536    }
7537
7538    /**
7539     * Called by a profile owner of a managed profile to retrieve the name of the organization under
7540     * management.
7541     *
7542     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7543     * @return The organization name or {@code null} if none is set.
7544     * @throws SecurityException if {@code admin} is not a profile owner.
7545     */
7546    public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
7547        throwIfParentInstance("getOrganizationName");
7548        try {
7549            return mService.getOrganizationName(admin);
7550        } catch (RemoteException re) {
7551            throw re.rethrowFromSystemServer();
7552        }
7553    }
7554
7555    /**
7556     * Called by the system to retrieve the name of the organization managing the device.
7557     *
7558     * @return The organization name or {@code null} if none is set.
7559     * @throws SecurityException if the caller is not the device owner, does not hold the
7560     *         MANAGE_USERS permission and is not the system.
7561     *
7562     * @hide
7563     */
7564    @SystemApi
7565    @TestApi
7566    @SuppressLint("Doclava125")
7567    public @Nullable CharSequence getDeviceOwnerOrganizationName() {
7568        try {
7569            return mService.getDeviceOwnerOrganizationName();
7570        } catch (RemoteException re) {
7571            throw re.rethrowFromSystemServer();
7572        }
7573    }
7574
7575    /**
7576     * Retrieve the default title message used in the confirm credentials screen for a given user.
7577     *
7578     * @param userHandle The user id of the user we're interested in.
7579     * @return The organization name or {@code null} if none is set.
7580     *
7581     * @hide
7582     */
7583    public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
7584        try {
7585            return mService.getOrganizationNameForUser(userHandle);
7586        } catch (RemoteException re) {
7587            throw re.rethrowFromSystemServer();
7588        }
7589    }
7590
7591    /**
7592     * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
7593     *         return {@link #STATE_USER_UNMANAGED}
7594     * @hide
7595     */
7596    @SystemApi
7597    @UserProvisioningState
7598    public int getUserProvisioningState() {
7599        throwIfParentInstance("getUserProvisioningState");
7600        if (mService != null) {
7601            try {
7602                return mService.getUserProvisioningState();
7603            } catch (RemoteException e) {
7604                throw e.rethrowFromSystemServer();
7605            }
7606        }
7607        return STATE_USER_UNMANAGED;
7608    }
7609
7610    /**
7611     * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
7612     *
7613     * @param state to store
7614     * @param userHandle for user
7615     * @hide
7616     */
7617    public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
7618        if (mService != null) {
7619            try {
7620                mService.setUserProvisioningState(state, userHandle);
7621            } catch (RemoteException e) {
7622                throw e.rethrowFromSystemServer();
7623            }
7624        }
7625    }
7626
7627    /**
7628     * Indicates the entity that controls the device or profile owner. Two users/profiles are
7629     * affiliated if the set of ids set by their device or profile owners intersect.
7630     *
7631     * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
7632     * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user or profile
7633     * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
7634     * affiliation ids are set by its profile owner as soon as possible after the user/profile is
7635     * created.
7636     *
7637     * @param admin Which profile or device owner this request is associated with.
7638     * @param ids A set of opaque non-empty affiliation ids.
7639     *
7640     * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
7641     */
7642    public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
7643        throwIfParentInstance("setAffiliationIds");
7644        if (ids == null) {
7645            throw new IllegalArgumentException("ids must not be null");
7646        }
7647        try {
7648            mService.setAffiliationIds(admin, new ArrayList<>(ids));
7649        } catch (RemoteException e) {
7650            throw e.rethrowFromSystemServer();
7651        }
7652    }
7653
7654    /**
7655     * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
7656     * empty set if none have been set.
7657     */
7658    public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
7659        throwIfParentInstance("getAffiliationIds");
7660        try {
7661            return new ArraySet<>(mService.getAffiliationIds(admin));
7662        } catch (RemoteException e) {
7663            throw e.rethrowFromSystemServer();
7664        }
7665    }
7666
7667    /**
7668     * @hide
7669     * Returns whether this user/profile is affiliated with the device.
7670     * <p>
7671     * By definition, the user that the device owner runs on is always affiliated with the device.
7672     * Any other user/profile is considered affiliated with the device if the set specified by its
7673     * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
7674     *
7675     */
7676    public boolean isAffiliatedUser() {
7677        throwIfParentInstance("isAffiliatedUser");
7678        try {
7679            return mService.isAffiliatedUser();
7680        } catch (RemoteException e) {
7681            throw e.rethrowFromSystemServer();
7682        }
7683    }
7684
7685    /**
7686     * @hide
7687     * Returns whether the uninstall for {@code packageName} for the current user is in queue
7688     * to be started
7689     * @param packageName the package to check for
7690     * @return whether the uninstall intent for {@code packageName} is pending
7691     */
7692    public boolean isUninstallInQueue(String packageName) {
7693        try {
7694            return mService.isUninstallInQueue(packageName);
7695        } catch (RemoteException re) {
7696            throw re.rethrowFromSystemServer();
7697        }
7698    }
7699
7700    /**
7701     * @hide
7702     * @param packageName the package containing active DAs to be uninstalled
7703     */
7704    public void uninstallPackageWithActiveAdmins(String packageName) {
7705        try {
7706            mService.uninstallPackageWithActiveAdmins(packageName);
7707        } catch (RemoteException re) {
7708            throw re.rethrowFromSystemServer();
7709        }
7710    }
7711
7712    /**
7713     * @hide
7714     * Remove a test admin synchronously without sending it a broadcast about being removed.
7715     * If the admin is a profile owner or device owner it will still be removed.
7716     *
7717     * @param userHandle user id to remove the admin for.
7718     * @param admin The administration compononent to remove.
7719     * @throws SecurityException if the caller is not shell / root or the admin package
7720     *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
7721     */
7722    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
7723        try {
7724            mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
7725        } catch (RemoteException re) {
7726            throw re.rethrowFromSystemServer();
7727        }
7728    }
7729
7730    /**
7731     * Returns whether the device has been provisioned.
7732     *
7733     * <p>Not for use by third-party applications.
7734     *
7735     * @hide
7736     */
7737    @SystemApi
7738    public boolean isDeviceProvisioned() {
7739        try {
7740            return mService.isDeviceProvisioned();
7741        } catch (RemoteException re) {
7742            throw re.rethrowFromSystemServer();
7743        }
7744    }
7745
7746    /**
7747      * Writes that the provisioning configuration has been applied.
7748      *
7749      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
7750      * permission.
7751      *
7752      * <p>Not for use by third-party applications.
7753      *
7754      * @hide
7755      */
7756    @SystemApi
7757    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
7758    public void setDeviceProvisioningConfigApplied() {
7759        try {
7760            mService.setDeviceProvisioningConfigApplied();
7761        } catch (RemoteException re) {
7762            throw re.rethrowFromSystemServer();
7763        }
7764    }
7765
7766    /**
7767     * Returns whether the provisioning configuration has been applied.
7768     *
7769     * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
7770     *
7771     * <p>Not for use by third-party applications.
7772     *
7773     * @return whether the provisioning configuration has been applied.
7774     *
7775     * @hide
7776     */
7777    @SystemApi
7778    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
7779    public boolean isDeviceProvisioningConfigApplied() {
7780        try {
7781            return mService.isDeviceProvisioningConfigApplied();
7782        } catch (RemoteException re) {
7783            throw re.rethrowFromSystemServer();
7784        }
7785    }
7786
7787    /**
7788     * @hide
7789     * Force update user setup completed status. This API has no effect on user build.
7790     * @throws {@link SecurityException} if the caller has no
7791     *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
7792     *         not {@link UserHandle#SYSTEM_USER}
7793     */
7794    public void forceUpdateUserSetupComplete() {
7795        try {
7796            mService.forceUpdateUserSetupComplete();
7797        } catch (RemoteException re) {
7798            throw re.rethrowFromSystemServer();
7799        }
7800    }
7801
7802    private void throwIfParentInstance(String functionName) {
7803        if (mParentInstance) {
7804            throw new SecurityException(functionName + " cannot be called on the parent instance");
7805        }
7806    }
7807
7808    /**
7809     * Allows the device owner to enable or disable the backup service.
7810     *
7811     * <p> Backup service manages all backup and restore mechanisms on the device. Setting this to
7812     * false will prevent data from being backed up or restored.
7813     *
7814     * <p> Backup service is off by default when device owner is present.
7815     *
7816     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7817     * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
7818     * @throws SecurityException if {@code admin} is not a device owner.
7819     */
7820    public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
7821        throwIfParentInstance("setBackupServiceEnabled");
7822        try {
7823            mService.setBackupServiceEnabled(admin, enabled);
7824        } catch (RemoteException re) {
7825            throw re.rethrowFromSystemServer();
7826        }
7827    }
7828
7829    /**
7830     * Return whether the backup service is enabled by the device owner.
7831     *
7832     * <p> Backup service manages all backup and restore mechanisms on the device.
7833     *
7834     * @return {@code true} if backup service is enabled, {@code false} otherwise.
7835     * @see #setBackupServiceEnabled
7836     */
7837    public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
7838        throwIfParentInstance("isBackupServiceEnabled");
7839        try {
7840            return mService.isBackupServiceEnabled(admin);
7841        } catch (RemoteException re) {
7842            throw re.rethrowFromSystemServer();
7843        }
7844    }
7845
7846    /**
7847     * Called by a device owner to control the network logging feature.
7848     *
7849     * <p> Network logs contain DNS lookup and connect() library call events. The following library
7850     *     functions are recorded while network logging is active:
7851     *     <ul>
7852     *       <li>{@code getaddrinfo()}</li>
7853     *       <li>{@code gethostbyname()}</li>
7854     *       <li>{@code connect()}</li>
7855     *     </ul>
7856     *
7857     * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
7858     *     full system call logging; event reporting is enabled by default for all processes but not
7859     *     strongly enforced.
7860     *     Events from applications using alternative implementations of libc, making direct kernel
7861     *     calls, or deliberately obfuscating traffic may not be recorded.
7862     *
7863     * <p> Some common network events may not be reported. For example:
7864     *     <ul>
7865     *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
7866     *           an alternative system for name resolution, and so avoid calling
7867     *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
7868     *       <li>Applications may use datagram sockets for performance reasons, for example
7869     *           for a game client. Calling {@code connect()} is unnecessary for this kind of
7870     *           socket, so it will not trigger a network event.</li>
7871     *     </ul>
7872     *
7873     * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
7874     *     always-on VPN service.
7875     *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
7876     *     and {@link android.net.VpnService} for details.
7877     *
7878     * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
7879     * are unaffiliated secondary users or profiles on the device, regardless of whether the
7880     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
7881     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
7882     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
7883     *
7884     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7885     * @param enabled whether network logging should be enabled or not.
7886     * @throws SecurityException if {@code admin} is not a device owner.
7887     * @see #retrieveNetworkLogs
7888     */
7889    public void setNetworkLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
7890        throwIfParentInstance("setNetworkLoggingEnabled");
7891        try {
7892            mService.setNetworkLoggingEnabled(admin, enabled);
7893        } catch (RemoteException re) {
7894            throw re.rethrowFromSystemServer();
7895        }
7896    }
7897
7898    /**
7899     * Return whether network logging is enabled by a device owner.
7900     *
7901     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
7902     * be {@code null} if the caller has MANAGE_USERS permission.
7903     * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
7904     * @throws SecurityException if {@code admin} is not a device owner and caller has
7905     * no MANAGE_USERS permission
7906     */
7907    public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
7908        throwIfParentInstance("isNetworkLoggingEnabled");
7909        try {
7910            return mService.isNetworkLoggingEnabled(admin);
7911        } catch (RemoteException re) {
7912            throw re.rethrowFromSystemServer();
7913        }
7914    }
7915
7916    /**
7917     * Called by device owner to retrieve the most recent batch of network logging events.
7918     * A device owner has to provide a batchToken provided as part of
7919     * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
7920     * token of the most recent available batch of logs, {@code null} will be returned.
7921     *
7922     * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
7923     *
7924     * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
7925     *
7926     * <p> Access to the logs is rate limited and this method will only return a new batch of logs
7927     * after the device device owner has been notified via
7928     * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
7929     *
7930     * <p>If a secondary user or profile is created, calling this method will throw a
7931     * {@link SecurityException} until all users become affiliated again. It will also no longer be
7932     * possible to retrieve the network logs batch with the most recent batchToken provided
7933     * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
7934     * {@link DevicePolicyManager#setAffiliationIds}.
7935     *
7936     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7937     * @param batchToken A token of the batch to retrieve
7938     * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
7939     *        {@code null} if the batch represented by batchToken is no longer available or if
7940     *        logging is disabled.
7941     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
7942     * profile or secondary user that is not affiliated with the device owner user.
7943     * @see DeviceAdminReceiver#onNetworkLogsAvailable
7944     */
7945    public @Nullable List<NetworkEvent> retrieveNetworkLogs(@NonNull ComponentName admin,
7946            long batchToken) {
7947        throwIfParentInstance("retrieveNetworkLogs");
7948        try {
7949            return mService.retrieveNetworkLogs(admin, batchToken);
7950        } catch (RemoteException re) {
7951            throw re.rethrowFromSystemServer();
7952        }
7953    }
7954
7955    /**
7956     * Called by a device owner to bind to a service from a profile owner or vice versa.
7957     * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
7958     * device/profile owners are allowed to bind to services of another profile/device owner.
7959     * <p>
7960     * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
7961     * Note that the {@link Context} used to obtain this
7962     * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
7963     * to bind to the {@link android.app.Service}.
7964     *
7965     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7966     * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
7967     *        explicit component name or a package name to match an
7968     *        {@link IntentFilter} published by a service.
7969     * @param conn Receives information as the service is started and stopped in main thread. This
7970     *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
7971     * @param flags Operation options for the binding operation. See
7972     *        {@link Context#bindService(Intent, ServiceConnection, int)}.
7973     * @param targetUser Which user to bind to. Must be one of the users returned by
7974     *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
7975     *        be thrown.
7976     * @return If you have successfully bound to the service, {@code true} is returned;
7977     *         {@code false} is returned if the connection is not made and you will not
7978     *         receive the service object.
7979     *
7980     * @see Context#bindService(Intent, ServiceConnection, int)
7981     * @see #getBindDeviceAdminTargetUsers(ComponentName)
7982     */
7983    public boolean bindDeviceAdminServiceAsUser(
7984            @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
7985            @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
7986        throwIfParentInstance("bindDeviceAdminServiceAsUser");
7987        // Keep this in sync with ContextImpl.bindServiceCommon.
7988        try {
7989            final IServiceConnection sd = mContext.getServiceDispatcher(
7990                    conn, mContext.getMainThreadHandler(), flags);
7991            serviceIntent.prepareToLeaveProcess(mContext);
7992            return mService.bindDeviceAdminServiceAsUser(admin,
7993                    mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
7994                    sd, flags, targetUser.getIdentifier());
7995        } catch (RemoteException re) {
7996            throw re.rethrowFromSystemServer();
7997        }
7998    }
7999
8000    /**
8001     * Returns the list of target users that the calling device or profile owner can use when
8002     * calling {@link #bindDeviceAdminServiceAsUser}.
8003     * <p>
8004     * A device owner can bind to a service from a profile owner and vice versa, provided that:
8005     * <ul>
8006     * <li>Both belong to the same package name.
8007     * <li>Both users are affiliated. See {@link #setAffiliationIds}.
8008     * </ul>
8009     */
8010    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
8011        throwIfParentInstance("getBindDeviceAdminTargetUsers");
8012        try {
8013            return mService.getBindDeviceAdminTargetUsers(admin);
8014        } catch (RemoteException re) {
8015            throw re.rethrowFromSystemServer();
8016        }
8017    }
8018
8019    /**
8020     * Called by the system to get the time at which the device owner last retrieved security
8021     * logging entries.
8022     *
8023     * @return the time at which the device owner most recently retrieved security logging entries,
8024     *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
8025     * @throws SecurityException if the caller is not the device owner, does not hold the
8026     *         MANAGE_USERS permission and is not the system.
8027     *
8028     * @hide
8029     */
8030    @TestApi
8031    public long getLastSecurityLogRetrievalTime() {
8032        try {
8033            return mService.getLastSecurityLogRetrievalTime();
8034        } catch (RemoteException re) {
8035            throw re.rethrowFromSystemServer();
8036        }
8037    }
8038
8039    /**
8040     * Called by the system to get the time at which the device owner last requested a bug report.
8041     *
8042     * @return the time at which the device owner most recently requested a bug report, in
8043     *         milliseconds since epoch; -1 if a bug report was never requested.
8044     * @throws SecurityException if the caller is not the device owner, does not hold the
8045     *         MANAGE_USERS permission and is not the system.
8046     *
8047     * @hide
8048     */
8049    @TestApi
8050    public long getLastBugReportRequestTime() {
8051        try {
8052            return mService.getLastBugReportRequestTime();
8053        } catch (RemoteException re) {
8054            throw re.rethrowFromSystemServer();
8055        }
8056    }
8057
8058    /**
8059     * Called by the system to get the time at which the device owner last retrieved network logging
8060     * events.
8061     *
8062     * @return the time at which the device owner most recently retrieved network logging events, in
8063     *         milliseconds since epoch; -1 if network logging events were never retrieved.
8064     * @throws SecurityException if the caller is not the device owner, does not hold the
8065     *         MANAGE_USERS permission and is not the system.
8066     *
8067     * @hide
8068     */
8069    @TestApi
8070    public long getLastNetworkLogRetrievalTime() {
8071        try {
8072            return mService.getLastNetworkLogRetrievalTime();
8073        } catch (RemoteException re) {
8074            throw re.rethrowFromSystemServer();
8075        }
8076    }
8077
8078    /**
8079     * Called by the system to find out whether the current user's IME was set by the device/profile
8080     * owner or the user.
8081     *
8082     * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
8083     *         otherwise.
8084     * @throws SecurityException if the caller is not the device owner/profile owner.
8085     *
8086     * @hide
8087     */
8088    @TestApi
8089    public boolean isCurrentInputMethodSetByOwner() {
8090        try {
8091            return mService.isCurrentInputMethodSetByOwner();
8092        } catch (RemoteException re) {
8093            throw re.rethrowFromSystemServer();
8094        }
8095    }
8096
8097    /**
8098     * Called by the system to get a list of CA certificates that were installed by the device or
8099     * profile owner.
8100     *
8101     * <p> The caller must be the target user's device owner/profile Owner or hold the
8102     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
8103     *
8104     * @param user The user for whom to retrieve information.
8105     * @return list of aliases identifying CA certificates installed by the device or profile owner
8106     * @throws SecurityException if the caller does not have permission to retrieve information
8107     *         about the given user's CA certificates.
8108     *
8109     * @hide
8110     */
8111    @TestApi
8112    public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
8113        try {
8114            return mService.getOwnerInstalledCaCerts(user).getList();
8115        } catch (RemoteException re) {
8116            throw re.rethrowFromSystemServer();
8117        }
8118    }
8119}
8120