DevicePolicyManager.java revision 3c13b64267e1724660aed96ffd461f05a5008cfe
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.CallbackExecutor;
20import android.annotation.ColorInt;
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.annotation.RequiresPermission;
25import android.annotation.SdkConstant;
26import android.annotation.SdkConstant.SdkConstantType;
27import android.annotation.SuppressLint;
28import android.annotation.SystemApi;
29import android.annotation.SystemService;
30import android.annotation.TestApi;
31import android.annotation.UserIdInt;
32import android.annotation.WorkerThread;
33import android.app.Activity;
34import android.app.IServiceConnection;
35import android.app.KeyguardManager;
36import android.app.admin.SecurityLog.SecurityEvent;
37import android.content.ComponentName;
38import android.content.Context;
39import android.content.Intent;
40import android.content.IntentFilter;
41import android.content.ServiceConnection;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.IPackageDataObserver;
44import android.content.pm.PackageManager;
45import android.content.pm.PackageManager.NameNotFoundException;
46import android.content.pm.ParceledListSlice;
47import android.content.pm.UserInfo;
48import android.graphics.Bitmap;
49import android.net.ProxyInfo;
50import android.net.Uri;
51import android.os.Bundle;
52import android.os.Parcelable;
53import android.os.PersistableBundle;
54import android.os.Process;
55import android.os.RemoteCallback;
56import android.os.RemoteException;
57import android.os.UserHandle;
58import android.os.UserManager;
59import android.provider.ContactsContract.Directory;
60import android.security.AttestedKeyPair;
61import android.security.Credentials;
62import android.security.KeyChain;
63import android.security.KeyChainException;
64import android.security.keymaster.KeymasterCertificateChain;
65import android.security.keystore.AttestationUtils;
66import android.security.keystore.KeyAttestationException;
67import android.security.keystore.KeyGenParameterSpec;
68import android.security.keystore.ParcelableKeyGenParameterSpec;
69import android.service.restrictions.RestrictionsReceiver;
70import android.telephony.TelephonyManager;
71import android.util.ArraySet;
72import android.util.Log;
73
74import com.android.internal.R;
75import com.android.internal.annotations.VisibleForTesting;
76import com.android.internal.util.Preconditions;
77import com.android.org.conscrypt.TrustedCertificateStore;
78
79import java.io.ByteArrayInputStream;
80import java.io.IOException;
81import java.lang.annotation.Retention;
82import java.lang.annotation.RetentionPolicy;
83import java.net.InetSocketAddress;
84import java.net.Proxy;
85import java.security.KeyFactory;
86import java.security.KeyPair;
87import java.security.NoSuchAlgorithmException;
88import java.security.PrivateKey;
89import java.security.cert.Certificate;
90import java.security.cert.CertificateException;
91import java.security.cert.CertificateFactory;
92import java.security.cert.X509Certificate;
93import java.security.spec.InvalidKeySpecException;
94import java.security.spec.PKCS8EncodedKeySpec;
95import java.util.ArrayList;
96import java.util.Arrays;
97import java.util.Collections;
98import java.util.List;
99import java.util.Set;
100import java.util.concurrent.Executor;
101
102/**
103 * Public interface for managing policies enforced on a device. Most clients of this class must be
104 * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
105 * administrator</a>. Additionally, a device administrator may be registered as either a profile or
106 * device owner. A given method is accessible to all device administrators unless the documentation
107 * for that method specifies that it is restricted to either device or profile owners. Any
108 * application calling an api may only pass as an argument a device administrator component it
109 * owns. Otherwise, a {@link SecurityException} will be thrown.
110 * <div class="special reference">
111 * <h3>Developer Guides</h3>
112 * <p>
113 * For more information about managing policies for device administration, read the <a href=
114 * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
115 * guide. </div>
116 */
117@SystemService(Context.DEVICE_POLICY_SERVICE)
118public class DevicePolicyManager {
119    private static String TAG = "DevicePolicyManager";
120
121    private final Context mContext;
122    private final IDevicePolicyManager mService;
123    private final boolean mParentInstance;
124
125    /** @hide */
126    public DevicePolicyManager(Context context, IDevicePolicyManager service) {
127        this(context, service, false);
128    }
129
130    /** @hide */
131    @VisibleForTesting
132    protected DevicePolicyManager(Context context, IDevicePolicyManager service,
133            boolean parentInstance) {
134        mContext = context;
135        mService = service;
136        mParentInstance = parentInstance;
137    }
138
139    /** @hide test will override it. */
140    @VisibleForTesting
141    protected int myUserId() {
142        return UserHandle.myUserId();
143    }
144
145    /**
146     * Activity action: Starts the provisioning flow which sets up a managed profile.
147     *
148     * <p>A managed profile allows data separation for example for the usage of a
149     * device as a personal and corporate device. The user which provisioning is started from and
150     * the managed profile share a launcher.
151     *
152     * <p>This intent will typically be sent by a mobile device management application (MDM).
153     * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
154     * control over the profile.
155     *
156     * <p>It is possible to check if provisioning is allowed or not by querying the method
157     * {@link #isProvisioningAllowed(String)}.
158     *
159     * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
160     * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
161     * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
162     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
163     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
164     *
165     * <p>The intent may also contain the following extras:
166     * <ul>
167     * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
168     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
169     * {@link android.os.Build.VERSION_CODES#N}</li>
170     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
171     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
172     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
173     * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
174     * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
175     * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
176     * </ul>
177     *
178     * <p>When managed provisioning has completed, broadcasts are sent to the application specified
179     * in the provisioning intent. The
180     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
181     * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
182     * the primary profile.
183     *
184     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
185     * completed, along with the above broadcast, activity intent
186     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
187     *
188     * <p>If provisioning fails, the managedProfile is removed so the device returns to its
189     * previous state.
190     *
191     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
192     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
193     * the provisioning flow was successful, although this doesn't guarantee the full flow will
194     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
195     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
196     */
197    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
198    public static final String ACTION_PROVISION_MANAGED_PROFILE
199        = "android.app.action.PROVISION_MANAGED_PROFILE";
200
201    /**
202     * Activity action: Starts the provisioning flow which sets up a managed user.
203     *
204     * <p>This intent will typically be sent by a mobile device management application (MDM).
205     * Provisioning configures the user as managed user and sets the MDM as the profile
206     * owner who has full control over the user. Provisioning can only happen before user setup has
207     * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
208     * allowed.
209     *
210     * <p>The intent contains the following extras:
211     * <ul>
212     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
213     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
214     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
215     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
216     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
217     * </ul>
218     *
219     * <p>If provisioning fails, the device returns to its previous state.
220     *
221     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
222     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
223     * the provisioning flow was successful, although this doesn't guarantee the full flow will
224     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
225     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
226     *
227     * @hide
228     */
229    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
230    public static final String ACTION_PROVISION_MANAGED_USER
231        = "android.app.action.PROVISION_MANAGED_USER";
232
233    /**
234     * Activity action: Starts the provisioning flow which sets up a managed device.
235     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
236     *
237     * <p> During device owner provisioning a device admin app is set as the owner of the device.
238     * A device owner has full control over the device. The device owner can not be modified by the
239     * user.
240     *
241     * <p> A typical use case would be a device that is owned by a company, but used by either an
242     * employee or client.
243     *
244     * <p> An intent with this action can be sent only on an unprovisioned device.
245     * It is possible to check if provisioning is allowed or not by querying the method
246     * {@link #isProvisioningAllowed(String)}.
247     *
248     * <p>The intent contains the following extras:
249     * <ul>
250     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
251     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
252     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
253     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
254     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
255     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
256     * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
257     * </ul>
258     *
259     * <p>When device owner provisioning has completed, an intent of the type
260     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
261     * device owner.
262     *
263     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
264     * completed, along with the above broadcast, activity intent
265     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
266     *
267     * <p>If provisioning fails, the device is factory reset.
268     *
269     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
270     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
271     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
272     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
273     */
274    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
275    public static final String ACTION_PROVISION_MANAGED_DEVICE
276        = "android.app.action.PROVISION_MANAGED_DEVICE";
277
278    /**
279     * Activity action: launch when user provisioning completed, i.e.
280     * {@link #getUserProvisioningState()} returns one of the complete state.
281     *
282     * <p> Please note that the API behavior is not necessarily consistent across various releases,
283     * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
284     * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
285     *
286     * <p> The activity must be protected by permission
287     * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
288     * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
289     * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
290     * components are not started by this intent.
291     * @hide
292     */
293    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
294    @SystemApi
295    public static final String ACTION_STATE_USER_SETUP_COMPLETE =
296            "android.app.action.STATE_USER_SETUP_COMPLETE";
297
298    /**
299     * Activity action: Starts the provisioning flow which sets up a managed device.
300     *
301     * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
302     * the device. A device owner has full control over the device. The device owner can not be
303     * modified by the user and the only way of resetting the device is via factory reset.
304     *
305     * <p>A typical use case would be a device that is owned by a company, but used by either an
306     * employee or client.
307     *
308     * <p>The provisioning message should be sent to an unprovisioned device.
309     *
310     * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
311     * by a privileged app with the permission
312     * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
313     *
314     * <p>The provisioning intent contains the following properties:
315     * <ul>
316     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
317     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
318     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
319     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
320     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL}, optional</li>
321     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI}, optional</li>
322     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
323     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
324     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
325     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
326     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
327     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
328     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
329     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
330     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
331     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
332     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
333     * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
334     * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
335     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li></ul>
336     *
337     * @hide
338     */
339    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
340    @SystemApi
341    public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
342            "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
343
344    /**
345     * Activity action: Starts the provisioning flow which sets up a managed device.
346     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
347     *
348     * <p>NOTE: This is only supported on split system user devices, and puts the device into a
349     * management state that is distinct from that reached by
350     * {@link #ACTION_PROVISION_MANAGED_DEVICE} - specifically the device owner runs on the system
351     * user, and only has control over device-wide policies, not individual users and their data.
352     * The primary benefit is that multiple non-system users are supported when provisioning using
353     * this form of device management.
354     *
355     * <p>During device owner provisioning a device admin app is set as the owner of the device.
356     * A device owner has full control over the device. The device owner can not be modified by the
357     * user.
358     *
359     * <p>A typical use case would be a device that is owned by a company, but used by either an
360     * employee or client.
361     *
362     * <p>An intent with this action can be sent only on an unprovisioned device.
363     * It is possible to check if provisioning is allowed or not by querying the method
364     * {@link #isProvisioningAllowed(String)}.
365     *
366     * <p>The intent contains the following extras:
367     * <ul>
368     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
369     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
370     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
371     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
372     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
373     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
374     * </ul>
375     *
376     * <p>When device owner provisioning has completed, an intent of the type
377     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
378     * device owner.
379     *
380     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
381     * completed, along with the above broadcast, activity intent
382     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
383     *
384     * <p>If provisioning fails, the device is factory reset.
385     *
386     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
387     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
388     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
389     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
390     *
391     * @hide
392     */
393    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
394    public static final String ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE
395        = "android.app.action.PROVISION_MANAGED_SHAREABLE_DEVICE";
396
397    /**
398     * Activity action: Finalizes management provisioning, should be used after user-setup
399     * has been completed and {@link #getUserProvisioningState()} returns one of:
400     * <ul>
401     * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
402     * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
403     * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
404     * </ul>
405     *
406     * @hide
407     */
408    @SystemApi
409    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
410    public static final String ACTION_PROVISION_FINALIZATION
411            = "android.app.action.PROVISION_FINALIZATION";
412
413    /**
414     * Action: Bugreport sharing with device owner has been accepted by the user.
415     *
416     * @hide
417     */
418    public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
419            "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
420
421    /**
422     * Action: Bugreport sharing with device owner has been declined by the user.
423     *
424     * @hide
425     */
426    public static final String ACTION_BUGREPORT_SHARING_DECLINED =
427            "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
428
429    /**
430     * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
431     *
432     * @hide
433     */
434    public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
435            "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
436
437    /**
438     * Extra for shared bugreport's SHA-256 hash.
439     *
440     * @hide
441     */
442    public static final String EXTRA_REMOTE_BUGREPORT_HASH =
443            "android.intent.extra.REMOTE_BUGREPORT_HASH";
444
445    /**
446     * Extra for remote bugreport notification shown type.
447     *
448     * @hide
449     */
450    public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
451            "android.app.extra.bugreport_notification_type";
452
453    /**
454     * Notification type for a started remote bugreport flow.
455     *
456     * @hide
457     */
458    public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
459
460    /**
461     * Notification type for a bugreport that has already been accepted to be shared, but is still
462     * being taken.
463     *
464     * @hide
465     */
466    public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
467
468    /**
469     * Notification type for a bugreport that has been taken and can be shared or declined.
470     *
471     * @hide
472     */
473    public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
474
475    /**
476     * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
477     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
478     *
479     * @hide
480     */
481    public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
482
483    /**
484     * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
485     * allows a mobile device management application or NFC programmer application which starts
486     * managed provisioning to pass data to the management application instance after provisioning.
487     * <p>
488     * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
489     * sends the intent to pass data to itself on the newly created profile.
490     * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
491     * instance of the app on the primary user.
492     * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
493     * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
494     * message should contain a stringified {@link java.util.Properties} instance, whose string
495     * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
496     * management application after provisioning.
497     *
498     * <p>
499     * In both cases the application receives the data in
500     * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
501     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
502     * during the managed provisioning.
503     */
504    public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
505            "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
506
507    /**
508     * A String extra holding the package name of the mobile device management application that
509     * will be set as the profile owner or device owner.
510     *
511     * <p>If an application starts provisioning directly via an intent with action
512     * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
513     * application that started provisioning. The package will be set as profile owner in that case.
514     *
515     * <p>This package is set as device owner when device owner provisioning is started by an NFC
516     * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
517     *
518     * <p> When this extra is set, the application must have exactly one device admin receiver.
519     * This receiver will be set as the profile or device owner and active admin.
520     *
521     * @see DeviceAdminReceiver
522     * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
523     * supported, but only if there is only one device admin receiver in the package that requires
524     * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
525     */
526    @Deprecated
527    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
528        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
529
530    /**
531     * A ComponentName extra indicating the device admin receiver of the mobile device management
532     * application that will be set as the profile owner or device owner and active admin.
533     *
534     * <p>If an application starts provisioning directly via an intent with action
535     * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
536     * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
537     * component has to match the package name of the application that started provisioning.
538     *
539     * <p>This component is set as device owner and active admin when device owner provisioning is
540     * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
541     * message containing an NFC record with MIME type
542     * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
543     * flattened to a string, via {@link ComponentName#flattenToShortString()}.
544     *
545     * @see DeviceAdminReceiver
546     */
547    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
548        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
549
550    /**
551     * An {@link android.accounts.Account} extra holding the account to migrate during managed
552     * profile provisioning. If the account supplied is present in the primary user, it will be
553     * copied, along with its credentials to the managed profile and removed from the primary user.
554     *
555     * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}.
556     */
557
558    public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
559        = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
560
561    /**
562     * Boolean extra to indicate that the migrated account should be kept. This is used in
563     * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
564     * the account will not be removed from the primary user after it is migrated to the newly
565     * created user or profile.
566     *
567     * <p> Defaults to {@code false}
568     *
569     * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
570     * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}
571     */
572    public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
573            = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
574
575    /**
576     * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
577     * device.
578     */
579    @Deprecated
580    public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
581        = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
582
583    /**
584     * A integer extra indicating the predominant color to show during the provisioning.
585     * Refer to {@link android.graphics.Color} for how the color is represented.
586     *
587     * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
588     * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
589     */
590    public static final String EXTRA_PROVISIONING_MAIN_COLOR =
591             "android.app.extra.PROVISIONING_MAIN_COLOR";
592
593    /**
594     * A Boolean extra that can be used by the mobile device management application to skip the
595     * disabling of system apps during provisioning when set to {@code true}.
596     *
597     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
598     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
599     */
600    public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
601            "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
602
603    /**
604     * A String extra holding the time zone {@link android.app.AlarmManager} that the device
605     * will be set to.
606     *
607     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
608     * provisioning via an NFC bump.
609     */
610    public static final String EXTRA_PROVISIONING_TIME_ZONE
611        = "android.app.extra.PROVISIONING_TIME_ZONE";
612
613    /**
614     * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
615     * {@link android.app.AlarmManager}.
616     *
617     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
618     * provisioning via an NFC bump.
619     */
620    public static final String EXTRA_PROVISIONING_LOCAL_TIME
621        = "android.app.extra.PROVISIONING_LOCAL_TIME";
622
623    /**
624     * A String extra holding the {@link java.util.Locale} that the device will be set to.
625     * Format: xx_yy, where xx is the language code, and yy the country code.
626     *
627     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
628     * provisioning via an NFC bump.
629     */
630    public static final String EXTRA_PROVISIONING_LOCALE
631        = "android.app.extra.PROVISIONING_LOCALE";
632
633    /**
634     * A String extra holding the ssid of the wifi network that should be used during nfc device
635     * owner provisioning for downloading the mobile device management application.
636     *
637     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
638     * provisioning via an NFC bump.
639     */
640    public static final String EXTRA_PROVISIONING_WIFI_SSID
641        = "android.app.extra.PROVISIONING_WIFI_SSID";
642
643    /**
644     * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
645     * is hidden or not.
646     *
647     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
648     * provisioning via an NFC bump.
649     */
650    public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
651        = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
652
653    /**
654     * A String extra indicating the security type of the wifi network in
655     * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA} or
656     * {@code WEP}.
657     *
658     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
659     * provisioning via an NFC bump.
660     */
661    public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
662        = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
663
664    /**
665     * A String extra holding the password of the wifi network in
666     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
667     *
668     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
669     * provisioning via an NFC bump.
670     */
671    public static final String EXTRA_PROVISIONING_WIFI_PASSWORD
672        = "android.app.extra.PROVISIONING_WIFI_PASSWORD";
673
674    /**
675     * A String extra holding the proxy host for the wifi network in
676     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
677     *
678     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
679     * provisioning via an NFC bump.
680     */
681    public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
682        = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
683
684    /**
685     * An int extra holding the proxy port for the wifi network in
686     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
687     *
688     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
689     * provisioning via an NFC bump.
690     */
691    public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
692        = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
693
694    /**
695     * A String extra holding the proxy bypass for the wifi network in
696     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
697     *
698     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
699     * provisioning via an NFC bump.
700     */
701    public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
702        = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
703
704    /**
705     * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
706     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
707     *
708     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
709     * provisioning via an NFC bump.
710     */
711    public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
712        = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
713
714    /**
715     * A String extra holding a url that specifies the download location of the device admin
716     * package. When not provided it is assumed that the device admin package is already installed.
717     *
718     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
719     * provisioning via an NFC bump.
720     */
721    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
722        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
723
724    /**
725     * A String extra holding the localized name of the organization under management.
726     *
727     * The name is displayed only during provisioning.
728     *
729     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
730     *
731     * @hide
732     */
733    @SystemApi
734    public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
735            "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
736
737    /**
738     * A String extra holding a url to the website of the device provider so the user can open it
739     * during provisioning. If the url is not HTTPS, an error will be shown.
740     *
741     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
742     *
743     * @hide
744     */
745    @SystemApi
746    public static final String EXTRA_PROVISIONING_SUPPORT_URL =
747            "android.app.extra.PROVISIONING_SUPPORT_URL";
748
749    /**
750     * A String extra holding the localized name of the device admin package. It should be the same
751     * as the app label of the package.
752     *
753     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
754     *
755     * @hide
756     */
757    @SystemApi
758    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
759            "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
760
761    /**
762     * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
763     * shown during the provisioning.
764     * <h5>The following URI schemes are accepted:</h5>
765     * <ul>
766     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
767     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
768     * </ul>
769     *
770     * <p> It is the responsibility of the caller to provide an image with a reasonable
771     * pixel density for the device.
772     *
773     * <p> If a content: URI is passed, the intent should have the flag
774     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
775     * {@link android.content.ClipData} of the intent too.
776     *
777     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
778     *
779     * @hide
780     */
781    @SystemApi
782    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
783            "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
784
785    /**
786     * An int extra holding a minimum required version code for the device admin package. If the
787     * device admin is already installed on the device, it will only be re-downloaded from
788     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
789     * installed package is less than this version code.
790     *
791     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
792     * provisioning via an NFC bump.
793     */
794    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
795        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
796
797    /**
798     * A String extra holding a http cookie header which should be used in the http request to the
799     * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
800     *
801     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
802     * provisioning via an NFC bump.
803     */
804    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
805        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
806
807    /**
808     * A String extra holding the URL-safe base64 encoded SHA-256 or SHA-1 hash (see notes below) of
809     * the file at download location specified in
810     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
811     *
812     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
813     * present. The provided checksum must match the checksum of the file at the download
814     * location. If the checksum doesn't match an error will be shown to the user and the user will
815     * be asked to factory reset the device.
816     *
817     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
818     * provisioning via an NFC bump.
819     *
820     * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
821     * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
822     * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
823     * addition to SHA-1. Support for SHA-1 is likely to be removed in future OS releases.
824     */
825    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
826        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
827
828    /**
829     * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
830     * android package archive at the download location specified in {@link
831     * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
832     *
833     * <p>The signatures of an android package archive can be obtained using
834     * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
835     * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
836     *
837     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
838     * present. The provided checksum must match the checksum of any signature of the file at
839     * the download location. If the checksum does not match an error will be shown to the user and
840     * the user will be asked to factory reset the device.
841     *
842     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
843     * provisioning via an NFC bump.
844     */
845    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
846        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
847
848    /**
849     * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
850     * has completed successfully.
851     *
852     * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
853     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
854     *
855     * <p>This intent will contain the following extras
856     * <ul>
857     * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
858     * profile.</li>
859     * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
860     * be migrated at provisioning time, if any.</li>
861     * </ul>
862     */
863    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
864    public static final String ACTION_MANAGED_PROFILE_PROVISIONED
865        = "android.app.action.MANAGED_PROFILE_PROVISIONED";
866
867    /**
868     * Activity action: This activity action is sent to indicate that provisioning of a managed
869     * profile or managed device has completed successfully. It'll be sent at the same time as
870     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
871     * delivered faster as it's an activity intent.
872     *
873     * <p>The intent is only sent to the new device or profile owner.
874     *
875     * @see #ACTION_PROVISION_MANAGED_PROFILE
876     * @see #ACTION_PROVISION_MANAGED_DEVICE
877     */
878    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
879    public static final String ACTION_PROVISIONING_SUCCESSFUL =
880            "android.app.action.PROVISIONING_SUCCESSFUL";
881
882    /**
883     * A boolean extra indicating whether device encryption can be skipped as part of device owner
884     * or managed profile provisioning.
885     *
886     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
887     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
888     *
889     * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
890     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
891     */
892    public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
893             "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
894
895    /**
896     * A {@link Uri} extra pointing to a logo image. This image will be shown during the
897     * provisioning. If this extra is not passed, a default image will be shown.
898     * <h5>The following URI schemes are accepted:</h5>
899     * <ul>
900     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
901     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
902     * </ul>
903     *
904     * <p> It is the responsibility of the caller to provide an image with a reasonable
905     * pixel density for the device.
906     *
907     * <p> If a content: URI is passed, the intent should have the flag
908     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
909     * {@link android.content.ClipData} of the intent too.
910     *
911     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
912     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
913     */
914    public static final String EXTRA_PROVISIONING_LOGO_URI =
915            "android.app.extra.PROVISIONING_LOGO_URI";
916
917    /**
918     * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
919     * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
920     * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
921     * content.
922     *
923     * <p> The extra typically contains one disclaimer from the company of mobile device
924     * management application (MDM), and one disclaimer from the organization.
925     *
926     * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
927     *
928     * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
929     *
930     * <p> Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
931     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
932     */
933    public static final String EXTRA_PROVISIONING_DISCLAIMERS =
934            "android.app.extra.PROVISIONING_DISCLAIMERS";
935
936    /**
937     * A String extra of localized disclaimer header.
938     *
939     * <p> The extra is typically the company name of mobile device management application (MDM)
940     * or the organization name.
941     *
942     * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
943     *
944     * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
945     * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
946     * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
947     *
948     * <pre>
949     *  &lt;meta-data
950     *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
951     *      android:resource="@string/disclaimer_header"
952     * /&gt;</pre>
953     */
954    public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
955            "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
956
957    /**
958     * A {@link Uri} extra pointing to disclaimer content.
959     *
960     * <h5>The following URI schemes are accepted:</h5>
961     * <ul>
962     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
963     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
964     * </ul>
965     *
966     * <p> Styled text is supported in the disclaimer content. The content is parsed by
967     * {@link android.text.Html#fromHtml(String)} and displayed in a
968     * {@link android.widget.TextView}.
969     *
970     * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
971     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
972     * {@link android.content.ClipData} of the intent too.
973     *
974     * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
975     *
976     * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
977     * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
978     * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
979     *
980     * <pre>
981     *  &lt;meta-data
982     *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
983     *      android:resource="@string/disclaimer_content"
984     * /&gt;</pre>
985     */
986    public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
987            "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
988
989    /**
990     * A boolean extra indicating if user setup should be skipped, for when provisioning is started
991     * during setup-wizard.
992     *
993     * <p>If unspecified, defaults to {@code true} to match the behavior in
994     * {@link android.os.Build.VERSION_CODES#M} and earlier.
995     *
996     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or
997     * {@link #ACTION_PROVISION_MANAGED_USER}.
998     *
999     * @hide
1000     */
1001    public static final String EXTRA_PROVISIONING_SKIP_USER_SETUP =
1002            "android.app.extra.PROVISIONING_SKIP_USER_SETUP";
1003
1004    /**
1005     * A boolean extra indicating if the user consent steps from the provisioning flow should be
1006     * skipped. If unspecified, defaults to {@code false}.
1007     *
1008     * It can only be used by an existing device owner trying to create a managed profile via
1009     * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1010     */
1011    public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1012            "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1013
1014    /**
1015     * This MIME type is used for starting the device owner provisioning.
1016     *
1017     * <p>During device owner provisioning a device admin app is set as the owner of the device.
1018     * A device owner has full control over the device. The device owner can not be modified by the
1019     * user and the only way of resetting the device is if the device owner app calls a factory
1020     * reset.
1021     *
1022     * <p> A typical use case would be a device that is owned by a company, but used by either an
1023     * employee or client.
1024     *
1025     * <p> The NFC message must be sent to an unprovisioned device.
1026     *
1027     * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1028     * contains the following properties:
1029     * <ul>
1030     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1031     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1032     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1033     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1034     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1035     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1036     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1037     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1038     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1039     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1040     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1041     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1042     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1043     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1044     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1045     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from
1046     * {@link android.os.Build.VERSION_CODES#M} </li></ul>
1047     *
1048     * <p>
1049     * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1050     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1051     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1052     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1053     */
1054    public static final String MIME_TYPE_PROVISIONING_NFC
1055        = "application/com.android.managedprovisioning";
1056
1057    /**
1058     * Activity action: ask the user to add a new device administrator to the system.
1059     * The desired policy is the ComponentName of the policy in the
1060     * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
1061     * bring the user through adding the device administrator to the system (or
1062     * allowing them to reject it).
1063     *
1064     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1065     * field to provide the user with additional explanation (in addition
1066     * to your component's description) about what is being added.
1067     *
1068     * <p>If your administrator is already active, this will ordinarily return immediately (without
1069     * user intervention).  However, if your administrator has been updated and is requesting
1070     * additional uses-policy flags, the user will be presented with the new list.  New policies
1071     * will not be available to the updated administrator until the user has accepted the new list.
1072     */
1073    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1074    public static final String ACTION_ADD_DEVICE_ADMIN
1075            = "android.app.action.ADD_DEVICE_ADMIN";
1076
1077    /**
1078     * @hide
1079     * Activity action: ask the user to add a new device administrator as the profile owner
1080     * for this user. Only system apps can launch this intent.
1081     *
1082     * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
1083     * extra field. This will invoke a UI to bring the user through adding the profile owner admin
1084     * to remotely control restrictions on the user.
1085     *
1086     * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
1087     * result of whether or not the user approved the action. If approved, the result will
1088     * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
1089     * as a profile owner.
1090     *
1091     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1092     * field to provide the user with additional explanation (in addition
1093     * to your component's description) about what is being added.
1094     *
1095     * <p>If there is already a profile owner active or the caller is not a system app, the
1096     * operation will return a failure result.
1097     */
1098    @SystemApi
1099    public static final String ACTION_SET_PROFILE_OWNER
1100            = "android.app.action.SET_PROFILE_OWNER";
1101
1102    /**
1103     * @hide
1104     * Name of the profile owner admin that controls the user.
1105     */
1106    @SystemApi
1107    public static final String EXTRA_PROFILE_OWNER_NAME
1108            = "android.app.extra.PROFILE_OWNER_NAME";
1109
1110    /**
1111     * Broadcast action: send when any policy admin changes a policy.
1112     * This is generally used to find out when a new policy is in effect.
1113     *
1114     * @hide
1115     */
1116    public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1117            = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
1118
1119    /**
1120     * Broadcast action: sent when the device owner is set, changed or cleared.
1121     *
1122     * This broadcast is sent only to the primary user.
1123     * @see #ACTION_PROVISION_MANAGED_DEVICE
1124     * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1125     */
1126    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1127    public static final String ACTION_DEVICE_OWNER_CHANGED
1128            = "android.app.action.DEVICE_OWNER_CHANGED";
1129
1130    /**
1131     * The ComponentName of the administrator component.
1132     *
1133     * @see #ACTION_ADD_DEVICE_ADMIN
1134     */
1135    public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
1136
1137    /**
1138     * An optional CharSequence providing additional explanation for why the
1139     * admin is being added.
1140     *
1141     * @see #ACTION_ADD_DEVICE_ADMIN
1142     */
1143    public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
1144
1145    /**
1146     * Constant to indicate the feature of disabling the camera. Used as argument to
1147     * {@link #createAdminSupportIntent(String)}.
1148     * @see #setCameraDisabled(ComponentName, boolean)
1149     */
1150    public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
1151
1152    /**
1153     * Constant to indicate the feature of disabling screen captures. Used as argument to
1154     * {@link #createAdminSupportIntent(String)}.
1155     * @see #setScreenCaptureDisabled(ComponentName, boolean)
1156     */
1157    public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
1158
1159    /**
1160     * Constant to indicate the feature of mandatory backups. Used as argument to
1161     * {@link #createAdminSupportIntent(String)}.
1162     * @see #setMandatoryBackupTransport(ComponentName, ComponentName)
1163     */
1164    public static final String POLICY_MANDATORY_BACKUPS = "policy_mandatory_backups";
1165
1166    /**
1167     * A String indicating a specific restricted feature. Can be a user restriction from the
1168     * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1169     * {@link #POLICY_DISABLE_CAMERA}, {@link #POLICY_DISABLE_SCREEN_CAPTURE} or
1170     * {@link #POLICY_MANDATORY_BACKUPS}.
1171     * @see #createAdminSupportIntent(String)
1172     * @hide
1173     */
1174    @TestApi
1175    public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1176
1177    /**
1178     * Activity action: have the user enter a new password. This activity should
1179     * be launched after using {@link #setPasswordQuality(ComponentName, int)},
1180     * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
1181     * enter a new password that meets the current requirements. You can use
1182     * {@link #isActivePasswordSufficient()} to determine whether you need to
1183     * have the user select a new password in order to meet the current
1184     * constraints. Upon being resumed from this activity, you can check the new
1185     * password characteristics to see if they are sufficient.
1186     *
1187     * If the intent is launched from within a managed profile with a profile
1188     * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1189     * this will trigger entering a new password for the parent of the profile.
1190     * For all other cases it will trigger entering a new password for the user
1191     * or profile it is launched from.
1192     *
1193     * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1194     */
1195    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1196    public static final String ACTION_SET_NEW_PASSWORD
1197            = "android.app.action.SET_NEW_PASSWORD";
1198
1199    /**
1200     * Activity action: have the user enter a new password for the parent profile.
1201     * If the intent is launched from within a managed profile, this will trigger
1202     * entering a new password for the parent of the profile. In all other cases
1203     * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
1204     */
1205    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1206    public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1207            = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1208
1209    /**
1210     * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1211     * Network logging was enabled and the user tapped the notification.
1212     * <p class="note">This is a protected intent that can only be sent by the system.</p>
1213     * @hide
1214     */
1215    public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1216            = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1217
1218    /**
1219     * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1220     * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1221     * {@link #EXTRA_DELEGATION_SCOPES} key.
1222     *
1223     * <p class=”note”> Note: This is a protected intent that can only be sent by the system.</p>
1224     */
1225    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1226    public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1227            "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1228
1229    /**
1230     * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1231     * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1232     */
1233    public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1234
1235    /**
1236     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1237     * the parent profile to access intents sent from the managed profile.
1238     * That is, when an app in the managed profile calls
1239     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1240     * matching activity in the parent profile.
1241     */
1242    public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1243
1244    /**
1245     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1246     * the managed profile to access intents sent from the parent profile.
1247     * That is, when an app in the parent profile calls
1248     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1249     * matching activity in the managed profile.
1250     */
1251    public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1252
1253    /**
1254     * Broadcast action: notify that a new local system update policy has been set by the device
1255     * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1256     */
1257    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1258    public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1259            = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1260
1261    /**
1262     * Broadcast action to notify ManagedProvisioning that
1263     * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has changed.
1264     * @hide
1265     */
1266    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1267    public static final String ACTION_DATA_SHARING_RESTRICTION_CHANGED =
1268            "android.app.action.DATA_SHARING_RESTRICTION_CHANGED";
1269
1270    /**
1271     * Broadcast action from ManagedProvisioning to notify that the latest change to
1272     * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
1273     * applied (cross profile intent filters updated). Only usesd for CTS tests.
1274     * @hide
1275     */
1276    @TestApi
1277    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1278    public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
1279            "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
1280
1281    /**
1282     * Permission policy to prompt user for new permission requests for runtime permissions.
1283     * Already granted or denied permissions are not affected by this.
1284     */
1285    public static final int PERMISSION_POLICY_PROMPT = 0;
1286
1287    /**
1288     * Permission policy to always grant new permission requests for runtime permissions.
1289     * Already granted or denied permissions are not affected by this.
1290     */
1291    public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1292
1293    /**
1294     * Permission policy to always deny new permission requests for runtime permissions.
1295     * Already granted or denied permissions are not affected by this.
1296     */
1297    public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1298
1299    /**
1300     * Runtime permission state: The user can manage the permission
1301     * through the UI.
1302     */
1303    public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1304
1305    /**
1306     * Runtime permission state: The permission is granted to the app
1307     * and the user cannot manage the permission through the UI.
1308     */
1309    public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1310
1311    /**
1312     * Runtime permission state: The permission is denied to the app
1313     * and the user cannot manage the permission through the UI.
1314     */
1315    public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1316
1317    /**
1318     * Delegation of certificate installation and management. This scope grants access to the
1319     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1320     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1321     */
1322    public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1323
1324    /**
1325     * Delegation of application restrictions management. This scope grants access to the
1326     * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1327     */
1328    public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1329
1330    /**
1331     * Delegation of application uninstall block. This scope grants access to the
1332     * {@link #setUninstallBlocked} API.
1333     */
1334    public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1335
1336    /**
1337     * Delegation of permission policy and permission grant state. This scope grants access to the
1338     * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1339     * and {@link #setPermissionGrantState} APIs.
1340     */
1341    public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1342
1343    /**
1344     * Delegation of package access state. This scope grants access to the
1345     * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1346     * {@link #setPackagesSuspended} APIs.
1347     */
1348    public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1349
1350    /**
1351     * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1352     * API.
1353     */
1354    public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1355
1356    /**
1357     * Delegation for installing existing packages. This scope grants access to the
1358     * {@link #installExistingPackage} API.
1359     */
1360    public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
1361            "delegation-install-existing-package";
1362
1363    /**
1364     * Delegation of management of uninstalled packages. This scope grants access to the
1365     * {@code #setKeepUninstalledPackages} and {@code #getKeepUninstalledPackages} APIs.
1366     */
1367    public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1368            "delegation-keep-uninstalled-packages";
1369
1370    /**
1371     * No management for current user in-effect. This is the default.
1372     * @hide
1373     */
1374    @SystemApi
1375    public static final int STATE_USER_UNMANAGED = 0;
1376
1377    /**
1378     * Management partially setup, user setup needs to be completed.
1379     * @hide
1380     */
1381    @SystemApi
1382    public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1383
1384    /**
1385     * Management partially setup, user setup completed.
1386     * @hide
1387     */
1388    @SystemApi
1389    public static final int STATE_USER_SETUP_COMPLETE = 2;
1390
1391    /**
1392     * Management setup and active on current user.
1393     * @hide
1394     */
1395    @SystemApi
1396    public static final int STATE_USER_SETUP_FINALIZED = 3;
1397
1398    /**
1399     * Management partially setup on a managed profile.
1400     * @hide
1401     */
1402    @SystemApi
1403    public static final int STATE_USER_PROFILE_COMPLETE = 4;
1404
1405    /**
1406     * @hide
1407     */
1408    @IntDef(prefix = { "STATE_USER_" }, value = {
1409            STATE_USER_UNMANAGED,
1410            STATE_USER_SETUP_INCOMPLETE,
1411            STATE_USER_SETUP_COMPLETE,
1412            STATE_USER_SETUP_FINALIZED,
1413            STATE_USER_PROFILE_COMPLETE
1414    })
1415    @Retention(RetentionPolicy.SOURCE)
1416    public @interface UserProvisioningState {}
1417
1418    /**
1419     * Result code for {@link #checkProvisioningPreCondition}.
1420     *
1421     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1422     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1423     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when provisioning is allowed.
1424     *
1425     * @hide
1426     */
1427    public static final int CODE_OK = 0;
1428
1429    /**
1430     * Result code for {@link #checkProvisioningPreCondition}.
1431     *
1432     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1433     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the device already has a device
1434     * owner.
1435     *
1436     * @hide
1437     */
1438    public static final int CODE_HAS_DEVICE_OWNER = 1;
1439
1440    /**
1441     * Result code for {@link #checkProvisioningPreCondition}.
1442     *
1443     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1444     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user has a profile owner and for
1445     * {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
1446     *
1447     * @hide
1448     */
1449    public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
1450
1451    /**
1452     * Result code for {@link #checkProvisioningPreCondition}.
1453     *
1454     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1455     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user isn't running.
1456     *
1457     * @hide
1458     */
1459    public static final int CODE_USER_NOT_RUNNING = 3;
1460
1461    /**
1462     * Result code for {@link #checkProvisioningPreCondition}.
1463     *
1464     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1465     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the device has already been setup and
1466     * for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
1467     *
1468     * @hide
1469     */
1470    public static final int CODE_USER_SETUP_COMPLETED = 4;
1471
1472    /**
1473     * Code used to indicate that the device also has a user other than the system user.
1474     *
1475     * @hide
1476     */
1477    public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
1478
1479    /**
1480     * Code used to indicate that device has an account that prevents provisioning.
1481     *
1482     * @hide
1483     */
1484    public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
1485
1486    /**
1487     * Result code for {@link #checkProvisioningPreCondition}.
1488     *
1489     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1490     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the user is not a system user.
1491     *
1492     * @hide
1493     */
1494    public static final int CODE_NOT_SYSTEM_USER = 7;
1495
1496    /**
1497     * Result code for {@link #checkProvisioningPreCondition}.
1498     *
1499     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1500     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} and {@link #ACTION_PROVISION_MANAGED_USER}
1501     * when the device is a watch and is already paired.
1502     *
1503     * @hide
1504     */
1505    public static final int CODE_HAS_PAIRED = 8;
1506
1507    /**
1508     * Result code for {@link #checkProvisioningPreCondition}.
1509     *
1510     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
1511     * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
1512     *
1513     * @see {@link PackageManager#FEATURE_MANAGED_USERS}
1514     * @hide
1515     */
1516    public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
1517
1518    /**
1519     * Result code for {@link #checkProvisioningPreCondition}.
1520     *
1521     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user.
1522     *
1523     * @hide
1524     */
1525    public static final int CODE_SYSTEM_USER = 10;
1526
1527    /**
1528     * Result code for {@link #checkProvisioningPreCondition}.
1529     *
1530     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
1531     * managed profiles.
1532     *
1533     * @hide
1534     */
1535    public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
1536
1537    /**
1538     * Result code for {@link #checkProvisioningPreCondition}.
1539     *
1540     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} and
1541     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices not running with split system
1542     * user.
1543     *
1544     * @hide
1545     */
1546    public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
1547
1548    /**
1549     * Result code for {@link #checkProvisioningPreCondition}.
1550     *
1551     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1552     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1553     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices which do no support device
1554     * admins.
1555     *
1556     * @hide
1557     */
1558    public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
1559
1560    /**
1561     * Result code for {@link #checkProvisioningPreCondition}.
1562     *
1563     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the device the user is a
1564     * system user on a split system user device.
1565     *
1566     * @hide
1567     */
1568    public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
1569
1570    /**
1571     * Result code for {@link #checkProvisioningPreCondition}.
1572     *
1573     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when adding a managed profile is
1574     * disallowed by {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
1575     *
1576     * @hide
1577     */
1578    public static final int CODE_ADD_MANAGED_PROFILE_DISALLOWED = 15;
1579
1580    /**
1581     * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
1582     * conditions.
1583     *
1584     * @hide
1585     */
1586    @Retention(RetentionPolicy.SOURCE)
1587    @IntDef(prefix = { "CODE_" }, value = {
1588            CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
1589            CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
1590            CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
1591            CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
1592            CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER, CODE_ADD_MANAGED_PROFILE_DISALLOWED
1593    })
1594    public @interface ProvisioningPreCondition {}
1595
1596    /**
1597     * Disable all configurable SystemUI features during LockTask mode. This includes,
1598     * <ul>
1599     *     <li>system info area in the status bar (connectivity icons, clock, etc.)
1600     *     <li>notifications (including alerts, icons, and the notification shade)
1601     *     <li>Home button
1602     *     <li>Recents button and UI
1603     *     <li>global actions menu (i.e. power button menu)
1604     *     <li>keyguard
1605     * </ul>
1606     *
1607     * This is the default configuration for LockTask.
1608     *
1609     * @see #setLockTaskFeatures(ComponentName, int)
1610     */
1611    public static final int LOCK_TASK_FEATURE_NONE = 0;
1612
1613    /**
1614     * Enable the system info area in the status bar during LockTask mode. The system info area
1615     * usually occupies the right side of the status bar (although this can differ across OEMs). It
1616     * includes all system information indicators, such as date and time, connectivity, battery,
1617     * vibration mode, etc.
1618     *
1619     * @see #setLockTaskFeatures(ComponentName, int)
1620     */
1621    public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
1622
1623    /**
1624     * Enable notifications during LockTask mode. This includes notification icons on the status
1625     * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
1626     * Settings panel will still be disabled.
1627     *
1628     * @see #setLockTaskFeatures(ComponentName, int)
1629     */
1630    public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
1631
1632    /**
1633     * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
1634     * to be registered as the default launcher with
1635     * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
1636     * package needs to be whitelisted for LockTask with
1637     * {@link #setLockTaskPackages(ComponentName, String[])}.
1638     *
1639     * @see #setLockTaskFeatures(ComponentName, int)
1640     */
1641    public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
1642
1643    /**
1644     * Enable the Recents button and the Recents screen during LockTask mode.
1645     *
1646     * @see #setLockTaskFeatures(ComponentName, int)
1647     */
1648    public static final int LOCK_TASK_FEATURE_RECENTS = 1 << 3;
1649
1650    /**
1651     * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
1652     * the user long-presses the power button, for example. Note that the user may not be able to
1653     * power off the device if this flag is not set.
1654     *
1655     * @see #setLockTaskFeatures(ComponentName, int)
1656     */
1657    public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
1658
1659    /**
1660     * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
1661     * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
1662     * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
1663     * credential.
1664     *
1665     * @see #setLockTaskFeatures(ComponentName, int)
1666     */
1667    public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
1668
1669    /**
1670     * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
1671     *
1672     * @hide
1673     */
1674    @Retention(RetentionPolicy.SOURCE)
1675    @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
1676            LOCK_TASK_FEATURE_NONE,
1677            LOCK_TASK_FEATURE_SYSTEM_INFO,
1678            LOCK_TASK_FEATURE_NOTIFICATIONS,
1679            LOCK_TASK_FEATURE_HOME,
1680            LOCK_TASK_FEATURE_RECENTS,
1681            LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
1682            LOCK_TASK_FEATURE_KEYGUARD
1683    })
1684    public @interface LockTaskFeature {}
1685
1686    /**
1687     * Service action: Action for a service that device owner and profile owner can optionally
1688     * own.  If a device owner or a profile owner has such a service, the system tries to keep
1689     * a bound connection to it, in order to keep their process always running.
1690     * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
1691     * permission.
1692     */
1693    @SdkConstant(SdkConstantType.SERVICE_ACTION)
1694    public static final String ACTION_DEVICE_ADMIN_SERVICE
1695            = "android.app.action.DEVICE_ADMIN_SERVICE";
1696
1697    /** @hide */
1698    @Retention(RetentionPolicy.SOURCE)
1699    @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
1700        ID_TYPE_BASE_INFO,
1701        ID_TYPE_SERIAL,
1702        ID_TYPE_IMEI,
1703        ID_TYPE_MEID
1704    })
1705    public @interface AttestationIdType {}
1706
1707    /**
1708     * Specifies that the device should attest its manufacturer details. For use with
1709     * {@link #generateKeyPair}.
1710     *
1711     * @see #generateKeyPair
1712     */
1713    public static final int ID_TYPE_BASE_INFO = 1;
1714
1715    /**
1716     * Specifies that the device should attest its serial number. For use with
1717     * {@link #generateKeyPair}.
1718     *
1719     * @see #generateKeyPair
1720     */
1721    public static final int ID_TYPE_SERIAL = 2;
1722
1723    /**
1724     * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
1725     *
1726     * @see #generateKeyPair
1727     */
1728    public static final int ID_TYPE_IMEI = 4;
1729
1730    /**
1731     * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
1732     *
1733     * @see #generateKeyPair
1734     */
1735    public static final int ID_TYPE_MEID = 8;
1736
1737    /**
1738     * Broadcast action: sent when the profile owner is set, changed or cleared.
1739     *
1740     * This broadcast is sent only to the user managed by the new profile owner.
1741     * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1742     */
1743    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1744    public static final String ACTION_PROFILE_OWNER_CHANGED =
1745            "android.app.action.PROFILE_OWNER_CHANGED";
1746
1747    /**
1748     * Return true if the given administrator component is currently active (enabled) in the system.
1749     *
1750     * @param admin The administrator component to check for.
1751     * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
1752     *         otherwise
1753     */
1754    public boolean isAdminActive(@NonNull ComponentName admin) {
1755        throwIfParentInstance("isAdminActive");
1756        return isAdminActiveAsUser(admin, myUserId());
1757    }
1758
1759    /**
1760     * @see #isAdminActive(ComponentName)
1761     * @hide
1762     */
1763    public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
1764        if (mService != null) {
1765            try {
1766                return mService.isAdminActive(admin, userId);
1767            } catch (RemoteException e) {
1768                throw e.rethrowFromSystemServer();
1769            }
1770        }
1771        return false;
1772    }
1773
1774    /**
1775     * Return true if the given administrator component is currently being removed
1776     * for the user.
1777     * @hide
1778     */
1779    public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
1780        if (mService != null) {
1781            try {
1782                return mService.isRemovingAdmin(admin, userId);
1783            } catch (RemoteException e) {
1784                throw e.rethrowFromSystemServer();
1785            }
1786        }
1787        return false;
1788    }
1789
1790    /**
1791     * Return a list of all currently active device administrators' component
1792     * names.  If there are no administrators {@code null} may be
1793     * returned.
1794     */
1795    public @Nullable List<ComponentName> getActiveAdmins() {
1796        throwIfParentInstance("getActiveAdmins");
1797        return getActiveAdminsAsUser(myUserId());
1798    }
1799
1800    /**
1801     * @see #getActiveAdmins()
1802     * @hide
1803     */
1804    public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
1805        if (mService != null) {
1806            try {
1807                return mService.getActiveAdmins(userId);
1808            } catch (RemoteException e) {
1809                throw e.rethrowFromSystemServer();
1810            }
1811        }
1812        return null;
1813    }
1814
1815    /**
1816     * Used by package administration code to determine if a package can be stopped
1817     * or uninstalled.
1818     * @hide
1819     */
1820    @SystemApi
1821    @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1822    public boolean packageHasActiveAdmins(String packageName) {
1823        return packageHasActiveAdmins(packageName, myUserId());
1824    }
1825
1826    /**
1827     * Used by package administration code to determine if a package can be stopped
1828     * or uninstalled.
1829     * @hide
1830     */
1831    public boolean packageHasActiveAdmins(String packageName, int userId) {
1832        if (mService != null) {
1833            try {
1834                return mService.packageHasActiveAdmins(packageName, userId);
1835            } catch (RemoteException e) {
1836                throw e.rethrowFromSystemServer();
1837            }
1838        }
1839        return false;
1840    }
1841
1842    /**
1843     * Remove a current administration component.  This can only be called
1844     * by the application that owns the administration component; if you
1845     * try to remove someone else's component, a security exception will be
1846     * thrown.
1847     *
1848     * <p>Note that the operation is not synchronous and the admin might still be active (as
1849     * indicated by {@link #getActiveAdmins()}) by the time this method returns.
1850     *
1851     * @param admin The administration compononent to remove.
1852     * @throws SecurityException if the caller is not in the owner application of {@code admin}.
1853     */
1854    public void removeActiveAdmin(@NonNull ComponentName admin) {
1855        throwIfParentInstance("removeActiveAdmin");
1856        if (mService != null) {
1857            try {
1858                mService.removeActiveAdmin(admin, myUserId());
1859            } catch (RemoteException e) {
1860                throw e.rethrowFromSystemServer();
1861            }
1862        }
1863    }
1864
1865    /**
1866     * Returns true if an administrator has been granted a particular device policy. This can be
1867     * used to check whether the administrator was activated under an earlier set of policies, but
1868     * requires additional policies after an upgrade.
1869     *
1870     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
1871     *            active administrator, or an exception will be thrown.
1872     * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
1873     * @throws SecurityException if {@code admin} is not an active administrator.
1874     */
1875    public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
1876        throwIfParentInstance("hasGrantedPolicy");
1877        if (mService != null) {
1878            try {
1879                return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
1880            } catch (RemoteException e) {
1881                throw e.rethrowFromSystemServer();
1882            }
1883        }
1884        return false;
1885    }
1886
1887    /**
1888     * Returns true if the Profile Challenge is available to use for the given profile user.
1889     *
1890     * @hide
1891     */
1892    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
1893        if (mService != null) {
1894            try {
1895                return mService.isSeparateProfileChallengeAllowed(userHandle);
1896            } catch (RemoteException e) {
1897                throw e.rethrowFromSystemServer();
1898            }
1899        }
1900        return false;
1901    }
1902
1903    /**
1904     * Constant for {@link #setPasswordQuality}: the policy has no requirements
1905     * for the password.  Note that quality constants are ordered so that higher
1906     * values are more restrictive.
1907     */
1908    public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
1909
1910    /**
1911     * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
1912     * recognition technology.  This implies technologies that can recognize the identity of
1913     * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
1914     * Note that quality constants are ordered so that higher values are more restrictive.
1915     */
1916    public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
1917
1918    /**
1919     * Constant for {@link #setPasswordQuality}: the policy requires some kind
1920     * of password or pattern, but doesn't care what it is. Note that quality constants
1921     * are ordered so that higher values are more restrictive.
1922     */
1923    public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
1924
1925    /**
1926     * Constant for {@link #setPasswordQuality}: the user must have entered a
1927     * password containing at least numeric characters.  Note that quality
1928     * constants are ordered so that higher values are more restrictive.
1929     */
1930    public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
1931
1932    /**
1933     * Constant for {@link #setPasswordQuality}: the user must have entered a
1934     * password containing at least numeric characters with no repeating (4444)
1935     * or ordered (1234, 4321, 2468) sequences.  Note that quality
1936     * constants are ordered so that higher values are more restrictive.
1937     */
1938    public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
1939
1940    /**
1941     * Constant for {@link #setPasswordQuality}: the user must have entered a
1942     * password containing at least alphabetic (or other symbol) characters.
1943     * Note that quality constants are ordered so that higher values are more
1944     * restrictive.
1945     */
1946    public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
1947
1948    /**
1949     * Constant for {@link #setPasswordQuality}: the user must have entered a
1950     * password containing at least <em>both></em> numeric <em>and</em>
1951     * alphabetic (or other symbol) characters.  Note that quality constants are
1952     * ordered so that higher values are more restrictive.
1953     */
1954    public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
1955
1956    /**
1957     * Constant for {@link #setPasswordQuality}: the user must have entered a
1958     * password containing at least a letter, a numerical digit and a special
1959     * symbol, by default. With this password quality, passwords can be
1960     * restricted to contain various sets of characters, like at least an
1961     * uppercase letter, etc. These are specified using various methods,
1962     * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
1963     * that quality constants are ordered so that higher values are more
1964     * restrictive.
1965     */
1966    public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
1967
1968    /**
1969     * Constant for {@link #setPasswordQuality}: the user is not allowed to
1970     * modify password. In case this password quality is set, the password is
1971     * managed by a profile owner. The profile owner can set any password,
1972     * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
1973     * that quality constants are ordered so that higher values are more
1974     * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
1975     * the highest.
1976     * @hide
1977     */
1978    public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
1979
1980    /**
1981     * @hide
1982     *
1983     * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
1984     * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
1985     * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
1986     * used by authenticator to exempt their accounts from this:
1987     *
1988     * <ul>
1989     *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
1990     *     <p>In order to make an apk test-only, add android:testOnly="true" to the
1991     *     &lt;application&gt; tag in the manifest.
1992     *
1993     *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
1994     *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
1995     *     Some authenticators claim to have any features, so to detect it, we also check
1996     *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
1997     *     if any of the accounts have it.
1998     * </ul>
1999     */
2000    @SystemApi
2001    @TestApi
2002    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
2003            "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
2004
2005    /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
2006    @SystemApi
2007    @TestApi
2008    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
2009            "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
2010
2011    /**
2012     * Called by an application that is administering the device to set the password restrictions it
2013     * is imposing. After setting this, the user will not be able to enter a new password that is
2014     * not at least as restrictive as what has been set. Note that the current password will remain
2015     * until the user has set a new one, so the change does not take place immediately. To prompt
2016     * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2017     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
2018     * <p>
2019     * Quality constants are ordered so that higher values are more restrictive; thus the highest
2020     * requested quality constant (between the policy set here, the user's preference, and any other
2021     * considerations) is the one that is in effect.
2022     * <p>
2023     * The calling device admin must have requested
2024     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2025     * not, a security exception will be thrown.
2026     * <p>
2027     * This method can be called on the {@link DevicePolicyManager} instance returned by
2028     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2029     * profile.
2030     *
2031     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2032     * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
2033     *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
2034     *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2035     *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
2036     * @throws SecurityException if {@code admin} is not an active administrator or if {@code admin}
2037     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2038     */
2039    public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
2040        if (mService != null) {
2041            try {
2042                mService.setPasswordQuality(admin, quality, mParentInstance);
2043            } catch (RemoteException e) {
2044                throw e.rethrowFromSystemServer();
2045            }
2046        }
2047    }
2048
2049    /**
2050     * Retrieve the current minimum password quality for a particular admin or all admins that set
2051     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2052     * a separate challenge are not taken into account.
2053     *
2054     * <p>This method can be called on the {@link DevicePolicyManager} instance
2055     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2056     * restrictions on the parent profile.
2057     *
2058     * @param admin The name of the admin component to check, or {@code null} to aggregate
2059     * all admins.
2060     */
2061    public int getPasswordQuality(@Nullable ComponentName admin) {
2062        return getPasswordQuality(admin, myUserId());
2063    }
2064
2065    /** @hide per-user version */
2066    public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
2067        if (mService != null) {
2068            try {
2069                return mService.getPasswordQuality(admin, userHandle, mParentInstance);
2070            } catch (RemoteException e) {
2071                throw e.rethrowFromSystemServer();
2072            }
2073        }
2074        return PASSWORD_QUALITY_UNSPECIFIED;
2075    }
2076
2077    /**
2078     * Called by an application that is administering the device to set the minimum allowed password
2079     * length. After setting this, the user will not be able to enter a new password that is not at
2080     * least as restrictive as what has been set. Note that the current password will remain until
2081     * the user has set a new one, so the change does not take place immediately. To prompt the user
2082     * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2083     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2084     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2085     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2086     * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
2087     * {@link #setPasswordQuality}.
2088     * <p>
2089     * The calling device admin must have requested
2090     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2091     * not, a security exception will be thrown.
2092     * <p>
2093     * This method can be called on the {@link DevicePolicyManager} instance returned by
2094     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2095     * profile.
2096     *
2097     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2098     * @param length The new desired minimum password length. A value of 0 means there is no
2099     *            restriction.
2100     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2101     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2102     */
2103    public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
2104        if (mService != null) {
2105            try {
2106                mService.setPasswordMinimumLength(admin, length, mParentInstance);
2107            } catch (RemoteException e) {
2108                throw e.rethrowFromSystemServer();
2109            }
2110        }
2111    }
2112
2113    /**
2114     * Retrieve the current minimum password length for a particular admin or all admins that set
2115     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2116     * a separate challenge are not taken into account.
2117     *
2118     * <p>This method can be called on the {@link DevicePolicyManager} instance
2119     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2120     * restrictions on the parent profile.
2121     *
2122     * user and its profiles or a particular one.
2123     * @param admin The name of the admin component to check, or {@code null} to aggregate
2124     * all admins.
2125     */
2126    public int getPasswordMinimumLength(@Nullable ComponentName admin) {
2127        return getPasswordMinimumLength(admin, myUserId());
2128    }
2129
2130    /** @hide per-user version */
2131    public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
2132        if (mService != null) {
2133            try {
2134                return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
2135            } catch (RemoteException e) {
2136                throw e.rethrowFromSystemServer();
2137            }
2138        }
2139        return 0;
2140    }
2141
2142    /**
2143     * Called by an application that is administering the device to set the minimum number of upper
2144     * case letters required in the password. After setting this, the user will not be able to enter
2145     * a new password that is not at least as restrictive as what has been set. Note that the
2146     * current password will remain until the user has set a new one, so the change does not take
2147     * place immediately. To prompt the user for a new password, use
2148     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2149     * setting this value. This constraint is only imposed if the administrator has also requested
2150     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2151     * <p>
2152     * The calling device admin must have requested
2153     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2154     * not, a security exception will be thrown.
2155     * <p>
2156     * This method can be called on the {@link DevicePolicyManager} instance returned by
2157     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2158     * profile.
2159     *
2160     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2161     * @param length The new desired minimum number of upper case letters required in the password.
2162     *            A value of 0 means there is no restriction.
2163     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2164     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2165     */
2166    public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
2167        if (mService != null) {
2168            try {
2169                mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
2170            } catch (RemoteException e) {
2171                throw e.rethrowFromSystemServer();
2172            }
2173        }
2174    }
2175
2176    /**
2177     * Retrieve the current number of upper case letters required in the password
2178     * for a particular admin or all admins that set restrictions on this user and
2179     * its participating profiles. Restrictions on profiles that have a separate challenge
2180     * are not taken into account.
2181     * This is the same value as set by
2182     * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
2183     * and only applies when the password quality is
2184     * {@link #PASSWORD_QUALITY_COMPLEX}.
2185     *
2186     * <p>This method can be called on the {@link DevicePolicyManager} instance
2187     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2188     * restrictions on the parent profile.
2189     *
2190     * @param admin The name of the admin component to check, or {@code null} to
2191     *            aggregate all admins.
2192     * @return The minimum number of upper case letters required in the
2193     *         password.
2194     */
2195    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
2196        return getPasswordMinimumUpperCase(admin, myUserId());
2197    }
2198
2199    /** @hide per-user version */
2200    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
2201        if (mService != null) {
2202            try {
2203                return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
2204            } catch (RemoteException e) {
2205                throw e.rethrowFromSystemServer();
2206            }
2207        }
2208        return 0;
2209    }
2210
2211    /**
2212     * Called by an application that is administering the device to set the minimum number of lower
2213     * case letters required in the password. After setting this, the user will not be able to enter
2214     * a new password that is not at least as restrictive as what has been set. Note that the
2215     * current password will remain until the user has set a new one, so the change does not take
2216     * place immediately. To prompt the user for a new password, use
2217     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2218     * setting this value. This constraint is only imposed if the administrator has also requested
2219     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2220     * <p>
2221     * The calling device admin must have requested
2222     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2223     * not, a security exception will be thrown.
2224     * <p>
2225     * This method can be called on the {@link DevicePolicyManager} instance returned by
2226     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2227     * profile.
2228     *
2229     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2230     * @param length The new desired minimum number of lower case letters required in the password.
2231     *            A value of 0 means there is no restriction.
2232     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2233     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2234     */
2235    public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
2236        if (mService != null) {
2237            try {
2238                mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
2239            } catch (RemoteException e) {
2240                throw e.rethrowFromSystemServer();
2241            }
2242        }
2243    }
2244
2245    /**
2246     * Retrieve the current number of lower case letters required in the password
2247     * for a particular admin or all admins that set restrictions on this user
2248     * and its participating profiles. Restrictions on profiles that have
2249     * a separate challenge are not taken into account.
2250     * This is the same value as set by
2251     * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
2252     * and only applies when the password quality is
2253     * {@link #PASSWORD_QUALITY_COMPLEX}.
2254     *
2255     * <p>This method can be called on the {@link DevicePolicyManager} instance
2256     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2257     * restrictions on the parent profile.
2258     *
2259     * @param admin The name of the admin component to check, or {@code null} to
2260     *            aggregate all admins.
2261     * @return The minimum number of lower case letters required in the
2262     *         password.
2263     */
2264    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
2265        return getPasswordMinimumLowerCase(admin, myUserId());
2266    }
2267
2268    /** @hide per-user version */
2269    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
2270        if (mService != null) {
2271            try {
2272                return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
2273            } catch (RemoteException e) {
2274                throw e.rethrowFromSystemServer();
2275            }
2276        }
2277        return 0;
2278    }
2279
2280    /**
2281     * Called by an application that is administering the device to set the minimum number of
2282     * letters required in the password. After setting this, the user will not be able to enter a
2283     * new password that is not at least as restrictive as what has been set. Note that the current
2284     * password will remain until the user has set a new one, so the change does not take place
2285     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2286     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2287     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2288     * {@link #setPasswordQuality}. The default value is 1.
2289     * <p>
2290     * The calling device admin must have requested
2291     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2292     * not, a security exception will be thrown.
2293     * <p>
2294     * This method can be called on the {@link DevicePolicyManager} instance returned by
2295     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2296     * profile.
2297     *
2298     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2299     * @param length The new desired minimum number of letters required in the password. A value of
2300     *            0 means there is no restriction.
2301     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2302     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2303     */
2304    public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
2305        if (mService != null) {
2306            try {
2307                mService.setPasswordMinimumLetters(admin, length, mParentInstance);
2308            } catch (RemoteException e) {
2309                throw e.rethrowFromSystemServer();
2310            }
2311        }
2312    }
2313
2314    /**
2315     * Retrieve the current number of letters required in the password
2316     * for a particular admin or all admins that set restrictions on this user
2317     * and its participating profiles. Restrictions on profiles that have
2318     * a separate challenge are not taken into account.
2319     * This is the same value as set by
2320     * {@link #setPasswordMinimumLetters(ComponentName, int)}
2321     * and only applies when the password quality is
2322     * {@link #PASSWORD_QUALITY_COMPLEX}.
2323     *
2324     * <p>This method can be called on the {@link DevicePolicyManager} instance
2325     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2326     * restrictions on the parent profile.
2327     *
2328     * @param admin The name of the admin component to check, or {@code null} to
2329     *            aggregate all admins.
2330     * @return The minimum number of letters required in the password.
2331     */
2332    public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
2333        return getPasswordMinimumLetters(admin, myUserId());
2334    }
2335
2336    /** @hide per-user version */
2337    public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
2338        if (mService != null) {
2339            try {
2340                return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
2341            } catch (RemoteException e) {
2342                throw e.rethrowFromSystemServer();
2343            }
2344        }
2345        return 0;
2346    }
2347
2348    /**
2349     * Called by an application that is administering the device to set the minimum number of
2350     * numerical digits required in the password. After setting this, the user will not be able to
2351     * enter a new password that is not at least as restrictive as what has been set. Note that the
2352     * current password will remain until the user has set a new one, so the change does not take
2353     * place immediately. To prompt the user for a new password, use
2354     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2355     * setting this value. This constraint is only imposed if the administrator has also requested
2356     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 1.
2357     * <p>
2358     * The calling device admin must have requested
2359     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2360     * not, a security exception will be thrown.
2361     * <p>
2362     * This method can be called on the {@link DevicePolicyManager} instance returned by
2363     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2364     * profile.
2365     *
2366     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2367     * @param length The new desired minimum number of numerical digits required in the password. A
2368     *            value of 0 means there is no restriction.
2369     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2370     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2371     */
2372    public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
2373        if (mService != null) {
2374            try {
2375                mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
2376            } catch (RemoteException e) {
2377                throw e.rethrowFromSystemServer();
2378            }
2379        }
2380    }
2381
2382    /**
2383     * Retrieve the current number of numerical digits required in the password
2384     * for a particular admin or all admins that set restrictions on this user
2385     * and its participating profiles. Restrictions on profiles that have
2386     * a separate challenge are not taken into account.
2387     * This is the same value as set by
2388     * {@link #setPasswordMinimumNumeric(ComponentName, int)}
2389     * and only applies when the password quality is
2390     * {@link #PASSWORD_QUALITY_COMPLEX}.
2391     *
2392     * <p>This method can be called on the {@link DevicePolicyManager} instance
2393     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2394     * restrictions on the parent profile.
2395     *
2396     * @param admin The name of the admin component to check, or {@code null} to
2397     *            aggregate all admins.
2398     * @return The minimum number of numerical digits required in the password.
2399     */
2400    public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
2401        return getPasswordMinimumNumeric(admin, myUserId());
2402    }
2403
2404    /** @hide per-user version */
2405    public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
2406        if (mService != null) {
2407            try {
2408                return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
2409            } catch (RemoteException e) {
2410                throw e.rethrowFromSystemServer();
2411            }
2412        }
2413        return 0;
2414    }
2415
2416    /**
2417     * Called by an application that is administering the device to set the minimum number of
2418     * symbols required in the password. After setting this, the user will not be able to enter a
2419     * new password that is not at least as restrictive as what has been set. Note that the current
2420     * password will remain until the user has set a new one, so the change does not take place
2421     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2422     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2423     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2424     * {@link #setPasswordQuality}. The default value is 1.
2425     * <p>
2426     * The calling device admin must have requested
2427     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2428     * not, a security exception will be thrown.
2429     * <p>
2430     * This method can be called on the {@link DevicePolicyManager} instance returned by
2431     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2432     * profile.
2433     *
2434     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2435     * @param length The new desired minimum number of symbols required in the password. A value of
2436     *            0 means there is no restriction.
2437     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2438     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2439     */
2440    public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
2441        if (mService != null) {
2442            try {
2443                mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
2444            } catch (RemoteException e) {
2445                throw e.rethrowFromSystemServer();
2446            }
2447        }
2448    }
2449
2450    /**
2451     * Retrieve the current number of symbols required in the password
2452     * for a particular admin or all admins that set restrictions on this user
2453     * and its participating profiles. Restrictions on profiles that have
2454     * a separate challenge are not taken into account. This is the same value as
2455     * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
2456     * and only applies when the password quality is
2457     * {@link #PASSWORD_QUALITY_COMPLEX}.
2458     *
2459     * <p>This method can be called on the {@link DevicePolicyManager} instance
2460     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2461     * restrictions on the parent profile.
2462     *
2463     * @param admin The name of the admin component to check, or {@code null} to
2464     *            aggregate all admins.
2465     * @return The minimum number of symbols required in the password.
2466     */
2467    public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
2468        return getPasswordMinimumSymbols(admin, myUserId());
2469    }
2470
2471    /** @hide per-user version */
2472    public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
2473        if (mService != null) {
2474            try {
2475                return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
2476            } catch (RemoteException e) {
2477                throw e.rethrowFromSystemServer();
2478            }
2479        }
2480        return 0;
2481    }
2482
2483    /**
2484     * Called by an application that is administering the device to set the minimum number of
2485     * non-letter characters (numerical digits or symbols) required in the password. After setting
2486     * this, the user will not be able to enter a new password that is not at least as restrictive
2487     * as what has been set. Note that the current password will remain until the user has set a new
2488     * one, so the change does not take place immediately. To prompt the user for a new password,
2489     * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2490     * setting this value. This constraint is only imposed if the administrator has also requested
2491     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2492     * <p>
2493     * The calling device admin must have requested
2494     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2495     * not, a security exception will be thrown.
2496     * <p>
2497     * This method can be called on the {@link DevicePolicyManager} instance returned by
2498     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2499     * profile.
2500     *
2501     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2502     * @param length The new desired minimum number of letters required in the password. A value of
2503     *            0 means there is no restriction.
2504     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2505     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2506     */
2507    public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
2508        if (mService != null) {
2509            try {
2510                mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
2511            } catch (RemoteException e) {
2512                throw e.rethrowFromSystemServer();
2513            }
2514        }
2515    }
2516
2517    /**
2518     * Retrieve the current number of non-letter characters required in the password
2519     * for a particular admin or all admins that set restrictions on this user
2520     * and its participating profiles. Restrictions on profiles that have
2521     * a separate challenge are not taken into account.
2522     * This is the same value as set by
2523     * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
2524     * and only applies when the password quality is
2525     * {@link #PASSWORD_QUALITY_COMPLEX}.
2526     *
2527     * <p>This method can be called on the {@link DevicePolicyManager} instance
2528     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2529     * restrictions on the parent profile.
2530     *
2531     * @param admin The name of the admin component to check, or {@code null} to
2532     *            aggregate all admins.
2533     * @return The minimum number of letters required in the password.
2534     */
2535    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
2536        return getPasswordMinimumNonLetter(admin, myUserId());
2537    }
2538
2539    /** @hide per-user version */
2540    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
2541        if (mService != null) {
2542            try {
2543                return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
2544            } catch (RemoteException e) {
2545                throw e.rethrowFromSystemServer();
2546            }
2547        }
2548        return 0;
2549    }
2550
2551    /**
2552     * Called by an application that is administering the device to set the length of the password
2553     * history. After setting this, the user will not be able to enter a new password that is the
2554     * same as any password in the history. Note that the current password will remain until the
2555     * user has set a new one, so the change does not take place immediately. To prompt the user for
2556     * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2557     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2558     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2559     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX} {@link #PASSWORD_QUALITY_ALPHABETIC}, or
2560     * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
2561     * <p>
2562     * The calling device admin must have requested
2563     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2564     * not, a security exception will be thrown.
2565     * <p>
2566     * This method can be called on the {@link DevicePolicyManager} instance returned by
2567     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2568     * profile.
2569     *
2570     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2571     * @param length The new desired length of password history. A value of 0 means there is no
2572     *            restriction.
2573     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2574     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2575     */
2576    public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
2577        if (mService != null) {
2578            try {
2579                mService.setPasswordHistoryLength(admin, length, mParentInstance);
2580            } catch (RemoteException e) {
2581                throw e.rethrowFromSystemServer();
2582            }
2583        }
2584    }
2585
2586    /**
2587     * Called by a device admin to set the password expiration timeout. Calling this method will
2588     * restart the countdown for password expiration for the given admin, as will changing the
2589     * device password (for all admins).
2590     * <p>
2591     * The provided timeout is the time delta in ms and will be added to the current time. For
2592     * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
2593     * 432000000 ms for timeout.
2594     * <p>
2595     * To disable password expiration, a value of 0 may be used for timeout.
2596     * <p>
2597     * The calling device admin must have requested
2598     * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
2599     * not, a security exception will be thrown.
2600     * <p>
2601     * Note that setting the password will automatically reset the expiration time for all active
2602     * admins. Active admins do not need to explicitly call this method in that case.
2603     * <p>
2604     * This method can be called on the {@link DevicePolicyManager} instance returned by
2605     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2606     * profile.
2607     *
2608     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2609     * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
2610     *            there is no restriction (unlimited).
2611     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2612     *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
2613     */
2614    public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
2615        if (mService != null) {
2616            try {
2617                mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
2618            } catch (RemoteException e) {
2619                throw e.rethrowFromSystemServer();
2620            }
2621        }
2622    }
2623
2624    /**
2625     * Get the password expiration timeout for the given admin. The expiration timeout is the
2626     * recurring expiration timeout provided in the call to
2627     * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
2628     * aggregate of all participating policy administrators if {@code admin} is null. Admins that
2629     * have set restrictions on profiles that have a separate challenge are not taken into account.
2630     *
2631     * <p>This method can be called on the {@link DevicePolicyManager} instance
2632     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2633     * restrictions on the parent profile.
2634     *
2635     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2636     * @return The timeout for the given admin or the minimum of all timeouts
2637     */
2638    public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
2639        if (mService != null) {
2640            try {
2641                return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
2642            } catch (RemoteException e) {
2643                throw e.rethrowFromSystemServer();
2644            }
2645        }
2646        return 0;
2647    }
2648
2649    /**
2650     * Get the current password expiration time for a particular admin or all admins that set
2651     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2652     * a separate challenge are not taken into account. If admin is {@code null}, then a composite
2653     * of all expiration times is returned - which will be the minimum of all of them.
2654     *
2655     * <p>This method can be called on the {@link DevicePolicyManager} instance
2656     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2657     * the password expiration for the parent profile.
2658     *
2659     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2660     * @return The password expiration time, in milliseconds since epoch.
2661     */
2662    public long getPasswordExpiration(@Nullable ComponentName admin) {
2663        if (mService != null) {
2664            try {
2665                return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
2666            } catch (RemoteException e) {
2667                throw e.rethrowFromSystemServer();
2668            }
2669        }
2670        return 0;
2671    }
2672
2673    /**
2674     * Retrieve the current password history length for a particular admin or all admins that
2675     * set restrictions on this user and its participating profiles. Restrictions on profiles that
2676     * have a separate challenge are not taken into account.
2677     *
2678     * <p>This method can be called on the {@link DevicePolicyManager} instance
2679     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2680     * restrictions on the parent profile.
2681     *
2682     * @param admin The name of the admin component to check, or {@code null} to aggregate
2683     * all admins.
2684     * @return The length of the password history
2685     */
2686    public int getPasswordHistoryLength(@Nullable ComponentName admin) {
2687        return getPasswordHistoryLength(admin, myUserId());
2688    }
2689
2690    /** @hide per-user version */
2691    public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
2692        if (mService != null) {
2693            try {
2694                return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
2695            } catch (RemoteException e) {
2696                throw e.rethrowFromSystemServer();
2697            }
2698        }
2699        return 0;
2700    }
2701
2702    /**
2703     * Return the maximum password length that the device supports for a
2704     * particular password quality.
2705     * @param quality The quality being interrogated.
2706     * @return Returns the maximum length that the user can enter.
2707     */
2708    public int getPasswordMaximumLength(int quality) {
2709        // Kind-of arbitrary.
2710        return 16;
2711    }
2712
2713    /**
2714     * The maximum number of characters allowed in the password blacklist.
2715     */
2716    private static final int PASSWORD_BLACKLIST_CHARACTER_LIMIT = 128 * 1000;
2717
2718    /**
2719     * Throws an exception if the password blacklist is too large.
2720     *
2721     * @hide
2722     */
2723    public static void enforcePasswordBlacklistSize(List<String> blacklist) {
2724        if (blacklist == null) {
2725            return;
2726        }
2727        long characterCount = 0;
2728        for (final String item : blacklist) {
2729            characterCount += item.length();
2730        }
2731        if (characterCount > PASSWORD_BLACKLIST_CHARACTER_LIMIT) {
2732            throw new IllegalArgumentException("128 thousand blacklist character limit exceeded by "
2733                      + (characterCount - PASSWORD_BLACKLIST_CHARACTER_LIMIT) + " characters");
2734        }
2735    }
2736
2737    /**
2738     * Called by an application that is administering the device to blacklist passwords.
2739     * <p>
2740     * Any blacklisted password or PIN is prevented from being enrolled by the user or the admin.
2741     * Note that the match against the blacklist is case insensitive. The blacklist applies for all
2742     * password qualities requested by {@link #setPasswordQuality} however it is not taken into
2743     * consideration by {@link #isActivePasswordSufficient}.
2744     * <p>
2745     * The blacklist can be cleared by passing {@code null} or an empty list. The blacklist is
2746     * given a name that is used to track which blacklist is currently set by calling {@link
2747     * #getPasswordBlacklistName}. If the blacklist is being cleared, the name is ignored and {@link
2748     * #getPasswordBlacklistName} will return {@code null}. The name can only be {@code null} when
2749     * the blacklist is being cleared.
2750     * <p>
2751     * The blacklist is limited to a total of 128 thousand characters rather than limiting to a
2752     * number of entries.
2753     * <p>
2754     * This method can be called on the {@link DevicePolicyManager} instance returned by
2755     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2756     * profile.
2757     *
2758     * @param admin the {@link DeviceAdminReceiver} this request is associated with
2759     * @param name name to associate with the blacklist
2760     * @param blacklist list of passwords to blacklist or {@code null} to clear the blacklist
2761     * @return whether the new blacklist was successfully installed
2762     * @throws SecurityException if {@code admin} is not a device or profile owner
2763     * @throws IllegalArgumentException if the blacklist surpasses the character limit
2764     * @throws NullPointerException if {@code name} is {@code null} when setting a non-empty list
2765     *
2766     * @see #getPasswordBlacklistName
2767     * @see #isActivePasswordSufficient
2768     * @see #resetPasswordWithToken
2769     */
2770    public boolean setPasswordBlacklist(@NonNull ComponentName admin, @Nullable String name,
2771            @Nullable List<String> blacklist) {
2772        enforcePasswordBlacklistSize(blacklist);
2773
2774        try {
2775            return mService.setPasswordBlacklist(admin, name, blacklist, mParentInstance);
2776        } catch (RemoteException re) {
2777            throw re.rethrowFromSystemServer();
2778        }
2779    }
2780
2781    /**
2782     * Get the name of the password blacklist set by the given admin.
2783     *
2784     * @param admin the {@link DeviceAdminReceiver} this request is associated with
2785     * @return the name of the blacklist or {@code null} if no blacklist is set
2786     *
2787     * @see #setPasswordBlacklist
2788     */
2789    public @Nullable String getPasswordBlacklistName(@NonNull ComponentName admin) {
2790        try {
2791            return mService.getPasswordBlacklistName(admin, myUserId(), mParentInstance);
2792        } catch (RemoteException re) {
2793            throw re.rethrowFromSystemServer();
2794        }
2795    }
2796
2797    /**
2798     * Test if a given password is blacklisted.
2799     *
2800     * @param userId the user to valiate for
2801     * @param password the password to check against the blacklist
2802     * @return whether the password is blacklisted
2803     *
2804     * @see #setPasswordBlacklist
2805     *
2806     * @hide
2807     */
2808    @RequiresPermission(android.Manifest.permission.TEST_BLACKLISTED_PASSWORD)
2809    public boolean isPasswordBlacklisted(@UserIdInt int userId, @NonNull String password) {
2810        try {
2811            return mService.isPasswordBlacklisted(userId, password);
2812        } catch (RemoteException re) {
2813            throw re.rethrowFromSystemServer();
2814        }
2815    }
2816
2817    /**
2818     * Determine whether the current password the user has set is sufficient to meet the policy
2819     * requirements (e.g. quality, minimum length) that have been requested by the admins of this
2820     * user and its participating profiles. Restrictions on profiles that have a separate challenge
2821     * are not taken into account. The user must be unlocked in order to perform the check. The
2822     * password blacklist is not considered when checking sufficiency.
2823     * <p>
2824     * The calling device admin must have requested
2825     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2826     * not, a security exception will be thrown.
2827     * <p>
2828     * This method can be called on the {@link DevicePolicyManager} instance returned by
2829     * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
2830     * the parent profile is sufficient.
2831     *
2832     * @return Returns true if the password meets the current requirements, else false.
2833     * @throws SecurityException if the calling application does not own an active administrator
2834     *             that uses {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2835     * @throws IllegalStateException if the user is not unlocked.
2836     */
2837    public boolean isActivePasswordSufficient() {
2838        if (mService != null) {
2839            try {
2840                return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
2841            } catch (RemoteException e) {
2842                throw e.rethrowFromSystemServer();
2843            }
2844        }
2845        return false;
2846    }
2847
2848    /**
2849     * When called by a profile owner of a managed profile returns true if the profile uses unified
2850     * challenge with its parent user.
2851     *
2852     * <strong>Note: This method is not concerned with password quality and will return false if
2853     * the profile has empty password as a separate challenge.
2854     *
2855     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2856     * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
2857     * @see UserManager#DISALLOW_UNIFIED_PASSWORD
2858     */
2859    public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
2860        throwIfParentInstance("isUsingUnifiedPassword");
2861        if (mService != null) {
2862            try {
2863                return mService.isUsingUnifiedPassword(admin);
2864            } catch (RemoteException e) {
2865                throw e.rethrowFromSystemServer();
2866            }
2867        }
2868        return true;
2869    }
2870
2871    /**
2872     * Determine whether the current profile password the user has set is sufficient
2873     * to meet the policy requirements (e.g. quality, minimum length) that have been
2874     * requested by the admins of the parent user and its profiles.
2875     *
2876     * @param userHandle the userId of the profile to check the password for.
2877     * @return Returns true if the password would meet the current requirements, else false.
2878     * @throws SecurityException if {@code userHandle} is not a managed profile.
2879     * @hide
2880     */
2881    public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
2882        if (mService != null) {
2883            try {
2884                return mService.isProfileActivePasswordSufficientForParent(userHandle);
2885            } catch (RemoteException e) {
2886                throw e.rethrowFromSystemServer();
2887            }
2888        }
2889        return false;
2890    }
2891
2892    /**
2893     * Retrieve the number of times the user has failed at entering a password since that last
2894     * successful password entry.
2895     * <p>
2896     * This method can be called on the {@link DevicePolicyManager} instance returned by
2897     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
2898     * password attemts for the parent user.
2899     * <p>
2900     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2901     * to be able to call this method; if it has not, a security exception will be thrown.
2902     *
2903     * @return The number of times user has entered an incorrect password since the last correct
2904     *         password entry.
2905     * @throws SecurityException if the calling application does not own an active administrator
2906     *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2907     */
2908    public int getCurrentFailedPasswordAttempts() {
2909        return getCurrentFailedPasswordAttempts(myUserId());
2910    }
2911
2912    /**
2913     * Retrieve the number of times the given user has failed at entering a
2914     * password since that last successful password entry.
2915     *
2916     * <p>The calling device admin must have requested
2917     * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
2918     * not and it is not the system uid, a security exception will be thrown.
2919     *
2920     * @hide
2921     */
2922    public int getCurrentFailedPasswordAttempts(int userHandle) {
2923        if (mService != null) {
2924            try {
2925                return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
2926            } catch (RemoteException e) {
2927                throw e.rethrowFromSystemServer();
2928            }
2929        }
2930        return -1;
2931    }
2932
2933    /**
2934     * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
2935     *
2936     * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
2937     * @hide
2938     */
2939    public boolean getDoNotAskCredentialsOnBoot() {
2940        if (mService != null) {
2941            try {
2942                return mService.getDoNotAskCredentialsOnBoot();
2943            } catch (RemoteException e) {
2944                throw e.rethrowFromSystemServer();
2945            }
2946        }
2947        return false;
2948    }
2949
2950    /**
2951     * Setting this to a value greater than zero enables a built-in policy that will perform a
2952     * device or profile wipe after too many incorrect device-unlock passwords have been entered.
2953     * This built-in policy combines watching for failed passwords and wiping the device, and
2954     * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2955     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
2956     * <p>
2957     * To implement any other policy (e.g. wiping data for a particular application only, erasing or
2958     * revoking credentials, or reporting the failure to a server), you should implement
2959     * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
2960     * use this API, because if the maximum count is reached, the device or profile will be wiped
2961     * immediately, and your callback will not be invoked.
2962     * <p>
2963     * This method can be called on the {@link DevicePolicyManager} instance returned by
2964     * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
2965     * profile.
2966     *
2967     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2968     * @param num The number of failed password attempts at which point the device or profile will
2969     *            be wiped.
2970     * @throws SecurityException if {@code admin} is not an active administrator or does not use
2971     *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2972     *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
2973     */
2974    public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
2975        if (mService != null) {
2976            try {
2977                mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
2978            } catch (RemoteException e) {
2979                throw e.rethrowFromSystemServer();
2980            }
2981        }
2982    }
2983
2984    /**
2985     * Retrieve the current maximum number of login attempts that are allowed before the device
2986     * or profile is wiped, for a particular admin or all admins that set restrictions on this user
2987     * and its participating profiles. Restrictions on profiles that have a separate challenge are
2988     * not taken into account.
2989     *
2990     * <p>This method can be called on the {@link DevicePolicyManager} instance
2991     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2992     * the value for the parent profile.
2993     *
2994     * @param admin The name of the admin component to check, or {@code null} to aggregate
2995     * all admins.
2996     */
2997    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
2998        return getMaximumFailedPasswordsForWipe(admin, myUserId());
2999    }
3000
3001    /** @hide per-user version */
3002    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
3003        if (mService != null) {
3004            try {
3005                return mService.getMaximumFailedPasswordsForWipe(
3006                        admin, userHandle, mParentInstance);
3007            } catch (RemoteException e) {
3008                throw e.rethrowFromSystemServer();
3009            }
3010        }
3011        return 0;
3012    }
3013
3014    /**
3015     * Returns the profile with the smallest maximum failed passwords for wipe,
3016     * for the given user. So for primary user, it might return the primary or
3017     * a managed profile. For a secondary user, it would be the same as the
3018     * user passed in.
3019     * @hide Used only by Keyguard
3020     */
3021    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
3022        if (mService != null) {
3023            try {
3024                return mService.getProfileWithMinimumFailedPasswordsForWipe(
3025                        userHandle, mParentInstance);
3026            } catch (RemoteException e) {
3027                throw e.rethrowFromSystemServer();
3028            }
3029        }
3030        return UserHandle.USER_NULL;
3031    }
3032
3033    /**
3034     * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
3035     * to change the password again until the user has entered it.
3036     */
3037    public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
3038
3039    /**
3040     * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
3041     * credentials on device boot.
3042     * If the flag is set, the device can be booted without asking for user password.
3043     * The absence of this flag does not change the current boot requirements. This flag
3044     * can be set by the device owner only. If the app is not the device owner, the flag
3045     * is ignored. Once the flag is set, it cannot be reverted back without resetting the
3046     * device to factory defaults.
3047     */
3048    public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
3049
3050    /**
3051     * Force a new password for device unlock (the password needed to access the entire device) or
3052     * the work profile challenge on the current user. This takes effect immediately.
3053     * <p>
3054     * <em>For device owner and profile owners targeting SDK level
3055     * {@link android.os.Build.VERSION_CODES#O} or above, this API is no longer available and will
3056     * throw {@link SecurityException}. Please use the new API {@link #resetPasswordWithToken}
3057     * instead. </em>
3058     * <p>
3059     * <em>Note: This API has been limited as of {@link android.os.Build.VERSION_CODES#N} for
3060     * device admins that are not device owner and not profile owner.
3061     * The password can now only be changed if there is currently no password set.  Device owner
3062     * and profile owner can still do this when user is unlocked and does not have a managed
3063     * profile.</em>
3064     * <p>
3065     * The given password must be sufficient for the current password quality and length constraints
3066     * as returned by {@link #getPasswordQuality(ComponentName)} and
3067     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3068     * it will be rejected and false returned. Note that the password may be a stronger quality
3069     * (containing alphanumeric characters when the requested quality is only numeric), in which
3070     * case the currently active quality will be increased to match.
3071     * <p>
3072     * Calling with a null or empty password will clear any existing PIN, pattern or password if the
3073     * current password constraints allow it. <em>Note: This will not work in
3074     * {@link android.os.Build.VERSION_CODES#N} and later for managed profiles, or for device admins
3075     * that are not device owner or profile owner.  Once set, the password cannot be changed to null
3076     * or empty except by these admins.</em>
3077     * <p>
3078     * The calling device admin must have requested
3079     * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
3080     * not, a security exception will be thrown.
3081     *
3082     * @param password The new password for the user. Null or empty clears the password.
3083     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3084     *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3085     * @return Returns true if the password was applied, or false if it is not acceptable for the
3086     *         current constraints or if the user has not been decrypted yet.
3087     * @throws SecurityException if the calling application does not own an active administrator
3088     *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
3089     * @throws IllegalStateException if the calling user is locked or has a managed profile.
3090     */
3091    public boolean resetPassword(String password, int flags) {
3092        throwIfParentInstance("resetPassword");
3093        if (mService != null) {
3094            try {
3095                return mService.resetPassword(password, flags);
3096            } catch (RemoteException e) {
3097                throw e.rethrowFromSystemServer();
3098            }
3099        }
3100        return false;
3101    }
3102
3103    /**
3104     * Called by a profile or device owner to provision a token which can later be used to reset the
3105     * device lockscreen password (if called by device owner), or managed profile challenge (if
3106     * called by profile owner), via {@link #resetPasswordWithToken}.
3107     * <p>
3108     * If the user currently has a lockscreen password, the provisioned token will not be
3109     * immediately usable; it only becomes active after the user performs a confirm credential
3110     * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
3111     * If the user has no lockscreen password, the token is activated immediately. In all cases,
3112     * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
3113     * For security reasons, un-activated tokens are only stored in memory and will be lost once
3114     * the device reboots. In this case a new token needs to be provisioned again.
3115     * <p>
3116     * Once provisioned and activated, the token will remain effective even if the user changes
3117     * or clears the lockscreen password.
3118     * <p>
3119     * <em>This token is highly sensitive and should be treated at the same level as user
3120     * credentials. In particular, NEVER store this token on device in plaintext. Do not store
3121     * the plaintext token in device-encrypted storage if it will be needed to reset password on
3122     * file-based encryption devices before user unlocks. Consider carefully how any password token
3123     * will be stored on your server and who will need access to them. Tokens may be the subject of
3124     * legal access requests.
3125     * </em>
3126     *
3127     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3128     * @param token a secure token a least 32-byte long, which must be generated by a
3129     *        cryptographically strong random number generator.
3130     * @return true if the operation is successful, false otherwise.
3131     * @throws SecurityException if admin is not a device or profile owner.
3132     * @throws IllegalArgumentException if the supplied token is invalid.
3133     */
3134    public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
3135        throwIfParentInstance("setResetPasswordToken");
3136        if (mService != null) {
3137            try {
3138                return mService.setResetPasswordToken(admin, token);
3139            } catch (RemoteException e) {
3140                throw e.rethrowFromSystemServer();
3141            }
3142        }
3143        return false;
3144    }
3145
3146    /**
3147     * Called by a profile or device owner to revoke the current password reset token.
3148     *
3149     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3150     * @return true if the operation is successful, false otherwise.
3151     * @throws SecurityException if admin is not a device or profile owner.
3152     */
3153    public boolean clearResetPasswordToken(ComponentName admin) {
3154        throwIfParentInstance("clearResetPasswordToken");
3155        if (mService != null) {
3156            try {
3157                return mService.clearResetPasswordToken(admin);
3158            } catch (RemoteException e) {
3159                throw e.rethrowFromSystemServer();
3160            }
3161        }
3162        return false;
3163    }
3164
3165    /**
3166     * Called by a profile or device owner to check if the current reset password token is active.
3167     *
3168     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3169     * @return true if the token is active, false otherwise.
3170     * @throws SecurityException if admin is not a device or profile owner.
3171     * @throws IllegalStateException if no token has been set.
3172     */
3173    public boolean isResetPasswordTokenActive(ComponentName admin) {
3174        throwIfParentInstance("isResetPasswordTokenActive");
3175        if (mService != null) {
3176            try {
3177                return mService.isResetPasswordTokenActive(admin);
3178            } catch (RemoteException e) {
3179                throw e.rethrowFromSystemServer();
3180            }
3181        }
3182        return false;
3183    }
3184
3185    /**
3186     * Called by device or profile owner to force set a new device unlock password or a managed
3187     * profile challenge on current user. This takes effect immediately.
3188     * <p>
3189     * Unlike {@link #resetPassword}, this API can change the password even before the user or
3190     * device is unlocked or decrypted. The supplied token must have been previously provisioned via
3191     * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
3192     * <p>
3193     * The given password must be sufficient for the current password quality and length constraints
3194     * as returned by {@link #getPasswordQuality(ComponentName)} and
3195     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3196     * it will be rejected and false returned. Note that the password may be a stronger quality, for
3197     * example, a password containing alphanumeric characters when the requested quality is only
3198     * numeric.
3199     * <p>
3200     * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
3201     * password if the current password constraints allow it.
3202     *
3203     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3204     * @param password The new password for the user. {@code null} or empty clears the password.
3205     * @param token the password reset token previously provisioned by
3206     *        {@link #setResetPasswordToken}.
3207     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3208     *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3209     * @return Returns true if the password was applied, or false if it is not acceptable for the
3210     *         current constraints.
3211     * @throws SecurityException if admin is not a device or profile owner.
3212     * @throws IllegalStateException if the provided token is not valid.
3213     */
3214    public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
3215            byte[] token, int flags) {
3216        throwIfParentInstance("resetPassword");
3217        if (mService != null) {
3218            try {
3219                return mService.resetPasswordWithToken(admin, password, token, flags);
3220            } catch (RemoteException e) {
3221                throw e.rethrowFromSystemServer();
3222            }
3223        }
3224        return false;
3225    }
3226
3227    /**
3228     * Called by an application that is administering the device to set the maximum time for user
3229     * activity until the device will lock. This limits the length that the user can set. It takes
3230     * effect immediately.
3231     * <p>
3232     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3233     * to be able to call this method; if it has not, a security exception will be thrown.
3234     * <p>
3235     * This method can be called on the {@link DevicePolicyManager} instance returned by
3236     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3237     * profile.
3238     *
3239     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3240     * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
3241     *            is no restriction.
3242     * @throws SecurityException if {@code admin} is not an active administrator or it does not use
3243     *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3244     */
3245    public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
3246        if (mService != null) {
3247            try {
3248                mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
3249            } catch (RemoteException e) {
3250                throw e.rethrowFromSystemServer();
3251            }
3252        }
3253    }
3254
3255    /**
3256     * Retrieve the current maximum time to unlock for a particular admin or all admins that set
3257     * restrictions on this user and its participating profiles. Restrictions on profiles that have
3258     * a separate challenge are not taken into account.
3259     *
3260     * <p>This method can be called on the {@link DevicePolicyManager} instance
3261     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3262     * restrictions on the parent profile.
3263     *
3264     * @param admin The name of the admin component to check, or {@code null} to aggregate
3265     * all admins.
3266     * @return time in milliseconds for the given admin or the minimum value (strictest) of
3267     * all admins if admin is null. Returns 0 if there are no restrictions.
3268     */
3269    public long getMaximumTimeToLock(@Nullable ComponentName admin) {
3270        return getMaximumTimeToLock(admin, myUserId());
3271    }
3272
3273    /** @hide per-user version */
3274    public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
3275        if (mService != null) {
3276            try {
3277                return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
3278            } catch (RemoteException e) {
3279                throw e.rethrowFromSystemServer();
3280            }
3281        }
3282        return 0;
3283    }
3284
3285    /**
3286     * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
3287     * strong auth (e.g. fingerprint, trust agents) times out, i.e. the user has to use a strong
3288     * authentication method like password, pin or pattern.
3289     *
3290     * <p>This timeout is used internally to reset the timer to require strong auth again after
3291     * specified timeout each time it has been successfully used.
3292     *
3293     * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
3294     *
3295     * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3296     *
3297     * <p>The calling device admin must be a device or profile owner. If it is not,
3298     * a {@link SecurityException} will be thrown.
3299     *
3300     * <p>The calling device admin can verify the value it has set by calling
3301     * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
3302     *
3303     * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
3304     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3305     * profile.
3306     *
3307     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3308     * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
3309     *         with strong authentication method. A value of 0 means the admin is not participating
3310     *         in controlling the timeout.
3311     *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
3312     *         72 hours, respectively. Though discouraged, the admin may choose to require strong
3313     *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
3314     *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3315     *
3316     * @throws SecurityException if {@code admin} is not a device or profile owner.
3317     */
3318    public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
3319            long timeoutMs) {
3320        if (mService != null) {
3321            try {
3322                mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
3323            } catch (RemoteException e) {
3324                throw e.rethrowFromSystemServer();
3325            }
3326        }
3327    }
3328
3329    /**
3330     * Determine for how long the user will be able to use secondary, non strong auth for
3331     * authentication, since last strong method authentication (password, pin or pattern) was used.
3332     * After the returned timeout the user is required to use strong authentication method.
3333     *
3334     * <p>This method can be called on the {@link DevicePolicyManager} instance
3335     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3336     * restrictions on the parent profile.
3337     *
3338     * @param admin The name of the admin component to check, or {@code null} to aggregate
3339     *         accross all participating admins.
3340     * @return The timeout in milliseconds or 0 if not configured for the provided admin.
3341     */
3342    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
3343        return getRequiredStrongAuthTimeout(admin, myUserId());
3344    }
3345
3346    /** @hide per-user version */
3347    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
3348        if (mService != null) {
3349            try {
3350                return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
3351            } catch (RemoteException e) {
3352                throw e.rethrowFromSystemServer();
3353            }
3354        }
3355        return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
3356    }
3357
3358    /**
3359     * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
3360     * keyring. The user's credential will need to be entered again in order to derive the
3361     * credential encryption key that will be stored back in the keyring for future use.
3362     * <p>
3363     * This flag can only be used by a profile owner when locking a managed profile when
3364     * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3365     * <p>
3366     * In order to secure user data, the user will be stopped and restarted so apps should wait
3367     * until they are next run to perform further actions.
3368     */
3369    public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
3370
3371    /** @hide */
3372    @Retention(RetentionPolicy.SOURCE)
3373    @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
3374            FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
3375    })
3376    public @interface LockNowFlag {}
3377
3378    /**
3379     * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3380     * this call.
3381     * <p>
3382     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3383     * to be able to call this method; if it has not, a security exception will be thrown.
3384     * <p>
3385     * This method can be called on the {@link DevicePolicyManager} instance returned by
3386     * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3387     * <p>
3388     * Equivalent to calling {@link #lockNow(int)} with no flags.
3389     *
3390     * @throws SecurityException if the calling application does not own an active administrator
3391     *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3392     */
3393    public void lockNow() {
3394        lockNow(0);
3395    }
3396
3397    /**
3398     * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3399     * this call.
3400     * <p>
3401     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3402     * to be able to call this method; if it has not, a security exception will be thrown.
3403     * <p>
3404     * This method can be called on the {@link DevicePolicyManager} instance returned by
3405     * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3406     *
3407     * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
3408     * @throws SecurityException if the calling application does not own an active administrator
3409     *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
3410     *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
3411     *             that is not a profile
3412     *             owner of a managed profile.
3413     * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
3414     *             passed when locking the parent profile.
3415     * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
3416     *             flag is passed when {@link #getStorageEncryptionStatus} does not return
3417     *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3418     */
3419    public void lockNow(@LockNowFlag int flags) {
3420        if (mService != null) {
3421            try {
3422                mService.lockNow(flags, mParentInstance);
3423            } catch (RemoteException e) {
3424                throw e.rethrowFromSystemServer();
3425            }
3426        }
3427    }
3428
3429    /**
3430     * Flag for {@link #wipeData(int)}: also erase the device's external
3431     * storage (such as SD cards).
3432     */
3433    public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
3434
3435    /**
3436     * Flag for {@link #wipeData(int)}: also erase the factory reset protection
3437     * data.
3438     *
3439     * <p>This flag may only be set by device owner admins; if it is set by
3440     * other admins a {@link SecurityException} will be thrown.
3441     */
3442    public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
3443
3444    /**
3445     * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
3446     *
3447     * TODO(b/35851809): make this public.
3448     * @hide
3449     */
3450    public static final int WIPE_EUICC = 0x0004;
3451
3452
3453    /**
3454     * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
3455     * other users will remain unaffected. Calling from the primary user will cause the device to
3456     * reboot, erasing all device data - including all the secondary users and their data - while
3457     * booting up.
3458     * <p>
3459     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
3460     * be able to call this method; if it has not, a security exception will be thrown.
3461     *
3462     * @param flags Bit mask of additional options: currently supported flags are
3463     *            {@link #WIPE_EXTERNAL_STORAGE} and {@link #WIPE_RESET_PROTECTION_DATA}.
3464     * @throws SecurityException if the calling application does not own an active administrator
3465     *             that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
3466     */
3467    public void wipeData(int flags) {
3468        throwIfParentInstance("wipeData");
3469        final String wipeReasonForUser = mContext.getString(
3470                R.string.work_profile_deleted_description_dpm_wipe);
3471        wipeDataInternal(flags, wipeReasonForUser);
3472    }
3473
3474    /**
3475     * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
3476     * other users will remain unaffected, the provided reason for wiping data can be shown to
3477     * user. Calling from the primary user will cause the device to reboot, erasing all device data
3478     * - including all the secondary users and their data - while booting up. In this case, we don't
3479     * show the reason to the user since the device would be factory reset.
3480     * <p>
3481     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
3482     * be able to call this method; if it has not, a security exception will be thrown.
3483     *
3484     * @param flags Bit mask of additional options: currently supported flags are
3485     *            {@link #WIPE_EXTERNAL_STORAGE} and {@link #WIPE_RESET_PROTECTION_DATA}.
3486     * @param reason a string that contains the reason for wiping data, which can be
3487     *                          presented to the user.
3488     * @throws SecurityException if the calling application does not own an active administrator
3489     *             that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
3490     * @throws IllegalArgumentException if the input reason string is null or empty.
3491     */
3492    public void wipeDataWithReason(int flags, @NonNull CharSequence reason) {
3493        throwIfParentInstance("wipeDataWithReason");
3494        Preconditions.checkNotNull(reason, "CharSequence is null");
3495        wipeDataInternal(flags, reason.toString());
3496    }
3497
3498    /**
3499     * Internal function for both {@link #wipeData(int)} and
3500     * {@link #wipeDataWithReason(int, CharSequence)} to call.
3501     *
3502     * @see #wipeData(int)
3503     * @see #wipeDataWithReason(int, CharSequence)
3504     * @hide
3505     */
3506    private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
3507        if (mService != null) {
3508            try {
3509                mService.wipeDataWithReason(flags, wipeReasonForUser);
3510            } catch (RemoteException e) {
3511                throw e.rethrowFromSystemServer();
3512            }
3513        }
3514    }
3515
3516    /**
3517     * Called by an application that is administering the device to set the
3518     * global proxy and exclusion list.
3519     * <p>
3520     * The calling device admin must have requested
3521     * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
3522     * this method; if it has not, a security exception will be thrown.
3523     * Only the first device admin can set the proxy. If a second admin attempts
3524     * to set the proxy, the {@link ComponentName} of the admin originally setting the
3525     * proxy will be returned. If successful in setting the proxy, {@code null} will
3526     * be returned.
3527     * The method can be called repeatedly by the device admin alrady setting the
3528     * proxy to update the proxy and exclusion list.
3529     *
3530     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3531     * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
3532     *            Pass Proxy.NO_PROXY to reset the proxy.
3533     * @param exclusionList a list of domains to be excluded from the global proxy.
3534     * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
3535     *            of the device admin that sets the proxy.
3536     * @hide
3537     */
3538    public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
3539            List<String> exclusionList ) {
3540        throwIfParentInstance("setGlobalProxy");
3541        if (proxySpec == null) {
3542            throw new NullPointerException();
3543        }
3544        if (mService != null) {
3545            try {
3546                String hostSpec;
3547                String exclSpec;
3548                if (proxySpec.equals(Proxy.NO_PROXY)) {
3549                    hostSpec = null;
3550                    exclSpec = null;
3551                } else {
3552                    if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
3553                        throw new IllegalArgumentException();
3554                    }
3555                    InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
3556                    String hostName = sa.getHostName();
3557                    int port = sa.getPort();
3558                    StringBuilder hostBuilder = new StringBuilder();
3559                    hostSpec = hostBuilder.append(hostName)
3560                        .append(":").append(Integer.toString(port)).toString();
3561                    if (exclusionList == null) {
3562                        exclSpec = "";
3563                    } else {
3564                        StringBuilder listBuilder = new StringBuilder();
3565                        boolean firstDomain = true;
3566                        for (String exclDomain : exclusionList) {
3567                            if (!firstDomain) {
3568                                listBuilder = listBuilder.append(",");
3569                            } else {
3570                                firstDomain = false;
3571                            }
3572                            listBuilder = listBuilder.append(exclDomain.trim());
3573                        }
3574                        exclSpec = listBuilder.toString();
3575                    }
3576                    if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
3577                            != android.net.Proxy.PROXY_VALID)
3578                        throw new IllegalArgumentException();
3579                }
3580                return mService.setGlobalProxy(admin, hostSpec, exclSpec);
3581            } catch (RemoteException e) {
3582                throw e.rethrowFromSystemServer();
3583            }
3584        }
3585        return null;
3586    }
3587
3588    /**
3589     * Set a network-independent global HTTP proxy. This is not normally what you want for typical
3590     * HTTP proxies - they are generally network dependent. However if you're doing something
3591     * unusual like general internal filtering this may be useful. On a private network where the
3592     * proxy is not accessible, you may break HTTP using this.
3593     * <p>
3594     * This method requires the caller to be the device owner.
3595     * <p>
3596     * This proxy is only a recommendation and it is possible that some apps will ignore it.
3597     *
3598     * @see ProxyInfo
3599     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3600     * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
3601     *            {@code null} value will clear the global HTTP proxy.
3602     * @throws SecurityException if {@code admin} is not the device owner.
3603     */
3604    public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
3605            proxyInfo) {
3606        throwIfParentInstance("setRecommendedGlobalProxy");
3607        if (mService != null) {
3608            try {
3609                mService.setRecommendedGlobalProxy(admin, proxyInfo);
3610            } catch (RemoteException e) {
3611                throw e.rethrowFromSystemServer();
3612            }
3613        }
3614    }
3615
3616    /**
3617     * Returns the component name setting the global proxy.
3618     * @return ComponentName object of the device admin that set the global proxy, or {@code null}
3619     *         if no admin has set the proxy.
3620     * @hide
3621     */
3622    public @Nullable ComponentName getGlobalProxyAdmin() {
3623        if (mService != null) {
3624            try {
3625                return mService.getGlobalProxyAdmin(myUserId());
3626            } catch (RemoteException e) {
3627                throw e.rethrowFromSystemServer();
3628            }
3629        }
3630        return null;
3631    }
3632
3633    /**
3634     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3635     * indicating that encryption is not supported.
3636     */
3637    public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
3638
3639    /**
3640     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3641     * indicating that encryption is supported, but is not currently active.
3642     */
3643    public static final int ENCRYPTION_STATUS_INACTIVE = 1;
3644
3645    /**
3646     * Result code for {@link #getStorageEncryptionStatus}:
3647     * indicating that encryption is not currently active, but is currently
3648     * being activated.  This is only reported by devices that support
3649     * encryption of data and only when the storage is currently
3650     * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
3651     * to become encrypted will never return this value.
3652     */
3653    public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
3654
3655    /**
3656     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3657     * indicating that encryption is active.
3658     * <p>
3659     * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3660     */
3661    public static final int ENCRYPTION_STATUS_ACTIVE = 3;
3662
3663    /**
3664     * Result code for {@link #getStorageEncryptionStatus}:
3665     * indicating that encryption is active, but an encryption key has not
3666     * been set by the user.
3667     */
3668    public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
3669
3670    /**
3671     * Result code for {@link #getStorageEncryptionStatus}:
3672     * indicating that encryption is active and the encryption key is tied to the user or profile.
3673     * <p>
3674     * This value is only returned to apps targeting API level 24 and above. For apps targeting
3675     * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
3676     * encryption key is specific to the user or profile.
3677     */
3678    public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
3679
3680    /**
3681     * Activity action: begin the process of encrypting data on the device.  This activity should
3682     * be launched after using {@link #setStorageEncryption} to request encryption be activated.
3683     * After resuming from this activity, use {@link #getStorageEncryption}
3684     * to check encryption status.  However, on some devices this activity may never return, as
3685     * it may trigger a reboot and in some cases a complete data wipe of the device.
3686     */
3687    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3688    public static final String ACTION_START_ENCRYPTION
3689            = "android.app.action.START_ENCRYPTION";
3690
3691    /**
3692     * Broadcast action: notify managed provisioning that new managed user is created.
3693     *
3694     * @hide
3695     */
3696    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3697    public static final String ACTION_MANAGED_USER_CREATED =
3698            "android.app.action.MANAGED_USER_CREATED";
3699
3700    /**
3701     * Widgets are enabled in keyguard
3702     */
3703    public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
3704
3705    /**
3706     * Disable all keyguard widgets. Has no effect.
3707     */
3708    public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
3709
3710    /**
3711     * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
3712     */
3713    public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
3714
3715    /**
3716     * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3717     */
3718    public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
3719
3720    /**
3721     * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3722     */
3723    public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
3724
3725    /**
3726     * Ignore trust agent state on secure keyguard screens
3727     * (e.g. PIN/Pattern/Password).
3728     */
3729    public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
3730
3731    /**
3732     * Disable fingerprint sensor on keyguard secure screens (e.g. PIN/Pattern/Password).
3733     */
3734    public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
3735
3736    /**
3737     * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
3738     */
3739    public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
3740
3741    /**
3742     * Disable all current and future keyguard customizations.
3743     */
3744    public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
3745
3746    /**
3747     * Keyguard features that when set on a managed profile that doesn't have its own challenge will
3748     * affect the profile's parent user. These can also be set on the managed profile's parent
3749     * {@link DevicePolicyManager} instance.
3750     *
3751     * @hide
3752     */
3753    public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
3754            DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
3755            | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
3756
3757    /**
3758     * Called by an application that is administering the device to request that the storage system
3759     * be encrypted.
3760     * <p>
3761     * When multiple device administrators attempt to control device encryption, the most secure,
3762     * supported setting will always be used. If any device administrator requests device
3763     * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
3764     * device encryption while another device administrator has enabled it, the call to disable will
3765     * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
3766     * <p>
3767     * This policy controls encryption of the secure (application data) storage area. Data written
3768     * to other storage areas may or may not be encrypted, and this policy does not require or
3769     * control the encryption of any other storage areas. There is one exception: If
3770     * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
3771     * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
3772     * written to disk within the encrypted storage area.
3773     * <p>
3774     * Important Note: On some devices, it is possible to encrypt storage without requiring the user
3775     * to create a device PIN or Password. In this case, the storage is encrypted, but the
3776     * encryption key may not be fully secured. For maximum security, the administrator should also
3777     * require (and check for) a pattern, PIN, or password.
3778     *
3779     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3780     * @param encrypt true to request encryption, false to release any previous request
3781     * @return the new request status (for all active admins) - will be one of
3782     *         {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, or
3783     *         {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value of the requests; Use
3784     *         {@link #getStorageEncryptionStatus()} to query the actual device state.
3785     * @throws SecurityException if {@code admin} is not an active administrator or does not use
3786     *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
3787     */
3788    public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
3789        throwIfParentInstance("setStorageEncryption");
3790        if (mService != null) {
3791            try {
3792                return mService.setStorageEncryption(admin, encrypt);
3793            } catch (RemoteException e) {
3794                throw e.rethrowFromSystemServer();
3795            }
3796        }
3797        return ENCRYPTION_STATUS_UNSUPPORTED;
3798    }
3799
3800    /**
3801     * Called by an application that is administering the device to
3802     * determine the requested setting for secure storage.
3803     *
3804     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
3805     * this will return the requested encryption setting as an aggregate of all active
3806     * administrators.
3807     * @return true if the admin(s) are requesting encryption, false if not.
3808     */
3809    public boolean getStorageEncryption(@Nullable ComponentName admin) {
3810        throwIfParentInstance("getStorageEncryption");
3811        if (mService != null) {
3812            try {
3813                return mService.getStorageEncryption(admin, myUserId());
3814            } catch (RemoteException e) {
3815                throw e.rethrowFromSystemServer();
3816            }
3817        }
3818        return false;
3819    }
3820
3821    /**
3822     * Called by an application that is administering the device to
3823     * determine the current encryption status of the device.
3824     * <p>
3825     * Depending on the returned status code, the caller may proceed in different
3826     * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
3827     * storage system does not support encryption.  If the
3828     * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
3829     * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
3830     * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
3831     * storage system has enabled encryption but no password is set so further action
3832     * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
3833     * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
3834     * no further action is required.
3835     *
3836     * @return current status of encryption. The value will be one of
3837     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
3838     * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
3839     * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3840     */
3841    public int getStorageEncryptionStatus() {
3842        throwIfParentInstance("getStorageEncryptionStatus");
3843        return getStorageEncryptionStatus(myUserId());
3844    }
3845
3846    /** @hide per-user version */
3847    public int getStorageEncryptionStatus(int userHandle) {
3848        if (mService != null) {
3849            try {
3850                return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
3851            } catch (RemoteException e) {
3852                throw e.rethrowFromSystemServer();
3853            }
3854        }
3855        return ENCRYPTION_STATUS_UNSUPPORTED;
3856    }
3857
3858    /**
3859     * Mark a CA certificate as approved by the device user. This means that they have been notified
3860     * of the installation, were made aware of the risks, viewed the certificate and still wanted to
3861     * keep the certificate on the device.
3862     *
3863     * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
3864     * this certificate.
3865     *
3866     * @hide
3867     */
3868    public boolean approveCaCert(String alias, int userHandle, boolean approval) {
3869        if (mService != null) {
3870            try {
3871                return mService.approveCaCert(alias, userHandle, approval);
3872            } catch (RemoteException e) {
3873                throw e.rethrowFromSystemServer();
3874            }
3875        }
3876        return false;
3877    }
3878
3879    /**
3880     * Check whether a CA certificate has been approved by the device user.
3881     *
3882     * @hide
3883     */
3884    public boolean isCaCertApproved(String alias, int userHandle) {
3885        if (mService != null) {
3886            try {
3887                return mService.isCaCertApproved(alias, userHandle);
3888            } catch (RemoteException e) {
3889                throw e.rethrowFromSystemServer();
3890            }
3891        }
3892        return false;
3893    }
3894
3895    /**
3896     * Installs the given certificate as a user CA.
3897     *
3898     * The caller must be a profile or device owner on that user, or a delegate package given the
3899     * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3900     * security exception will be thrown.
3901     *
3902     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3903     *              {@code null} if calling from a delegated certificate installer.
3904     * @param certBuffer encoded form of the certificate to install.
3905     *
3906     * @return false if the certBuffer cannot be parsed or installation is
3907     *         interrupted, true otherwise.
3908     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3909     *         owner.
3910     * @see #setDelegatedScopes
3911     * @see #DELEGATION_CERT_INSTALL
3912     */
3913    public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3914        throwIfParentInstance("installCaCert");
3915        if (mService != null) {
3916            try {
3917                return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
3918            } catch (RemoteException e) {
3919                throw e.rethrowFromSystemServer();
3920            }
3921        }
3922        return false;
3923    }
3924
3925    /**
3926     * Uninstalls the given certificate from trusted user CAs, if present.
3927     *
3928     * The caller must be a profile or device owner on that user, or a delegate package given the
3929     * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3930     * security exception will be thrown.
3931     *
3932     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3933     *              {@code null} if calling from a delegated certificate installer.
3934     * @param certBuffer encoded form of the certificate to remove.
3935     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3936     *         owner.
3937     * @see #setDelegatedScopes
3938     * @see #DELEGATION_CERT_INSTALL
3939     */
3940    public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3941        throwIfParentInstance("uninstallCaCert");
3942        if (mService != null) {
3943            try {
3944                final String alias = getCaCertAlias(certBuffer);
3945                mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
3946            } catch (CertificateException e) {
3947                Log.w(TAG, "Unable to parse certificate", e);
3948            } catch (RemoteException e) {
3949                throw e.rethrowFromSystemServer();
3950            }
3951        }
3952    }
3953
3954    /**
3955     * Returns all CA certificates that are currently trusted, excluding system CA certificates.
3956     * If a user has installed any certificates by other means than device policy these will be
3957     * included too.
3958     *
3959     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3960     *              {@code null} if calling from a delegated certificate installer.
3961     * @return a List of byte[] arrays, each encoding one user CA certificate.
3962     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3963     *         owner.
3964     */
3965    public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
3966        final List<byte[]> certs = new ArrayList<byte[]>();
3967        throwIfParentInstance("getInstalledCaCerts");
3968        if (mService != null) {
3969            try {
3970                mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
3971                final TrustedCertificateStore certStore = new TrustedCertificateStore();
3972                for (String alias : certStore.userAliases()) {
3973                    try {
3974                        certs.add(certStore.getCertificate(alias).getEncoded());
3975                    } catch (CertificateException ce) {
3976                        Log.w(TAG, "Could not encode certificate: " + alias, ce);
3977                    }
3978                }
3979            } catch (RemoteException re) {
3980                throw re.rethrowFromSystemServer();
3981            }
3982        }
3983        return certs;
3984    }
3985
3986    /**
3987     * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
3988     * means other than device policy will also be removed, except for system CA certificates.
3989     *
3990     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3991     *              {@code null} if calling from a delegated certificate installer.
3992     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3993     *         owner.
3994     */
3995    public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
3996        throwIfParentInstance("uninstallAllUserCaCerts");
3997        if (mService != null) {
3998            try {
3999                mService.uninstallCaCerts(admin, mContext.getPackageName(),
4000                        new TrustedCertificateStore().userAliases() .toArray(new String[0]));
4001            } catch (RemoteException re) {
4002                throw re.rethrowFromSystemServer();
4003            }
4004        }
4005    }
4006
4007    /**
4008     * Returns whether this certificate is installed as a trusted CA.
4009     *
4010     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4011     *              {@code null} if calling from a delegated certificate installer.
4012     * @param certBuffer encoded form of the certificate to look up.
4013     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4014     *         owner.
4015     */
4016    public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
4017        throwIfParentInstance("hasCaCertInstalled");
4018        if (mService != null) {
4019            try {
4020                mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
4021                return getCaCertAlias(certBuffer) != null;
4022            } catch (RemoteException re) {
4023                throw re.rethrowFromSystemServer();
4024            } catch (CertificateException ce) {
4025                Log.w(TAG, "Could not parse certificate", ce);
4026            }
4027        }
4028        return false;
4029    }
4030
4031    /**
4032     * Called by a device or profile owner, or delegated certificate installer, to install a
4033     * certificate and corresponding private key. All apps within the profile will be able to access
4034     * the certificate and use the private key, given direct user approval.
4035     *
4036     * <p>Access to the installed credentials will not be granted to the caller of this API without
4037     * direct user approval. This is for security - should a certificate installer become
4038     * compromised, certificates it had already installed will be protected.
4039     *
4040     * <p>If the installer must have access to the credentials, call
4041     * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
4042     *
4043     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4044     *            {@code null} if calling from a delegated certificate installer.
4045     * @param privKey The private key to install.
4046     * @param cert The certificate to install.
4047     * @param alias The private key alias under which to install the certificate. If a certificate
4048     * with that alias already exists, it will be overwritten.
4049     * @return {@code true} if the keys were installed, {@code false} otherwise.
4050     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4051     *         owner.
4052     * @see #setDelegatedScopes
4053     * @see #DELEGATION_CERT_INSTALL
4054     */
4055    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4056            @NonNull Certificate cert, @NonNull String alias) {
4057        return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
4058    }
4059
4060    /**
4061     * Called by a device or profile owner, or delegated certificate installer, to install a
4062     * certificate chain and corresponding private key for the leaf certificate. All apps within the
4063     * profile will be able to access the certificate chain and use the private key, given direct
4064     * user approval.
4065     *
4066     * <p>The caller of this API may grant itself access to the certificate and private key
4067     * immediately, without user approval. It is a best practice not to request this unless strictly
4068     * necessary since it opens up additional security vulnerabilities.
4069     *
4070     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4071     *        {@code null} if calling from a delegated certificate installer.
4072     * @param privKey The private key to install.
4073     * @param certs The certificate chain to install. The chain should start with the leaf
4074     *        certificate and include the chain of trust in order. This will be returned by
4075     *        {@link android.security.KeyChain#getCertificateChain}.
4076     * @param alias The private key alias under which to install the certificate. If a certificate
4077     *        with that alias already exists, it will be overwritten.
4078     * @param requestAccess {@code true} to request that the calling app be granted access to the
4079     *        credentials immediately. Otherwise, access to the credentials will be gated by user
4080     *        approval.
4081     * @return {@code true} if the keys were installed, {@code false} otherwise.
4082     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4083     *         owner.
4084     * @see android.security.KeyChain#getCertificateChain
4085     * @see #setDelegatedScopes
4086     * @see #DELEGATION_CERT_INSTALL
4087     */
4088    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4089            @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
4090        return installKeyPair(admin, privKey, certs, alias, requestAccess, true);
4091    }
4092
4093    /**
4094     * Called by a device or profile owner, or delegated certificate installer, to install a
4095     * certificate chain and corresponding private key for the leaf certificate. All apps within the
4096     * profile will be able to access the certificate chain and use the private key, given direct
4097     * user approval (if the user is allowed to select the private key).
4098     *
4099     * <p>The caller of this API may grant itself access to the certificate and private key
4100     * immediately, without user approval. It is a best practice not to request this unless strictly
4101     * necessary since it opens up additional security vulnerabilities.
4102     *
4103     * <p>Whether this key is offered to the user for approval at all or not depends on the
4104     * {@code isUserSelectable} parameter.
4105     *
4106     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4107     *        {@code null} if calling from a delegated certificate installer.
4108     * @param privKey The private key to install.
4109     * @param certs The certificate chain to install. The chain should start with the leaf
4110     *        certificate and include the chain of trust in order. This will be returned by
4111     *        {@link android.security.KeyChain#getCertificateChain}.
4112     * @param alias The private key alias under which to install the certificate. If a certificate
4113     *        with that alias already exists, it will be overwritten.
4114     * @param requestAccess {@code true} to request that the calling app be granted access to the
4115     *        credentials immediately. Otherwise, access to the credentials will be gated by user
4116     *        approval.
4117     * @param isUserSelectable {@code true} to indicate that a user can select this key via the
4118     *        Certificate Selection prompt, false to indicate that this key can only be granted
4119     *        access by implementing
4120     *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
4121     * @return {@code true} if the keys were installed, {@code false} otherwise.
4122     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4123     *         owner.
4124     * @see android.security.KeyChain#getCertificateChain
4125     * @see #setDelegatedScopes
4126     * @see #DELEGATION_CERT_INSTALL
4127     */
4128    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4129            @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess,
4130            boolean isUserSelectable) {
4131        throwIfParentInstance("installKeyPair");
4132        try {
4133            final byte[] pemCert = Credentials.convertToPem(certs[0]);
4134            byte[] pemChain = null;
4135            if (certs.length > 1) {
4136                pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
4137            }
4138            final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
4139                    .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
4140            return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
4141                    pemChain, alias, requestAccess, isUserSelectable);
4142        } catch (RemoteException e) {
4143            throw e.rethrowFromSystemServer();
4144        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
4145            Log.w(TAG, "Failed to obtain private key material", e);
4146        } catch (CertificateException | IOException e) {
4147            Log.w(TAG, "Could not pem-encode certificate", e);
4148        }
4149        return false;
4150    }
4151
4152    /**
4153     * Called by a device or profile owner, or delegated certificate installer, to remove a
4154     * certificate and private key pair installed under a given alias.
4155     *
4156     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4157     *        {@code null} if calling from a delegated certificate installer.
4158     * @param alias The private key alias under which the certificate is installed.
4159     * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
4160     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4161     *         owner.
4162     * @see #setDelegatedScopes
4163     * @see #DELEGATION_CERT_INSTALL
4164     */
4165    public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
4166        throwIfParentInstance("removeKeyPair");
4167        try {
4168            return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4169        } catch (RemoteException e) {
4170            throw e.rethrowFromSystemServer();
4171        }
4172    }
4173
4174    /**
4175     * Called by a device or profile owner, or delegated certificate installer, to generate a
4176     * new private/public key pair. If the device supports key generation via secure hardware,
4177     * this method is useful for creating a key in KeyChain that never left the secure hardware.
4178     *
4179     * Access to the key is controlled the same way as in {@link #installKeyPair}.
4180     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4181     *            {@code null} if calling from a delegated certificate installer.
4182     * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
4183     * @param keySpec Specification of the key to generate, see
4184     * {@link java.security.KeyPairGenerator}.
4185     * @param idAttestationFlags A bitmask of all the identifiers that should be included in the
4186     *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
4187     *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), or {@code 0} if no device
4188     *        identification is required in the attestation record.
4189     *        Device owner, profile owner and their delegated certificate installer can use
4190     *        {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device information
4191     *        including manufacturer, model, brand, device and product in the attestation record.
4192     *        Only device owner and their delegated certificate installer can use
4193     *        {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID} to request
4194     *        unique device identifiers to be attested.
4195     *        <p>
4196     *        If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
4197     *        is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
4198     *        <p>
4199     *        If any flag is specified, then an attestation challenge must be included in the
4200     *        {@code keySpec}.
4201     * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
4202     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4203     *         owner. If Device ID attestation is requested (using {@link #ID_TYPE_SERIAL},
4204     *         {@link #ID_TYPE_IMEI} or {@link #ID_TYPE_MEID}), the caller must be the Device Owner
4205     *         or the Certificate Installer delegate.
4206     * @throws IllegalArgumentException if the alias in {@code keySpec} is empty, if the
4207     *         algorithm specification in {@code keySpec} is not {@code RSAKeyGenParameterSpec}
4208     *         or {@code ECGenParameterSpec}, or if Device ID attestation was requested but the
4209     *         {@code keySpec} does not contain an attestation challenge.
4210     * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
4211     */
4212    public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
4213            @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
4214            @AttestationIdType int idAttestationFlags) {
4215        throwIfParentInstance("generateKeyPair");
4216        try {
4217            final ParcelableKeyGenParameterSpec parcelableSpec =
4218                    new ParcelableKeyGenParameterSpec(keySpec);
4219            KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
4220
4221            // Translate ID attestation flags to values used by AttestationUtils
4222            final boolean success = mService.generateKeyPair(
4223                    admin, mContext.getPackageName(), algorithm, parcelableSpec,
4224                    idAttestationFlags, attestationChain);
4225            if (!success) {
4226                Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
4227                return null;
4228            }
4229
4230            final String alias = keySpec.getKeystoreAlias();
4231            final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
4232            Certificate[] outputChain = null;
4233            try {
4234                if (AttestationUtils.isChainValid(attestationChain)) {
4235                    outputChain = AttestationUtils.parseCertificateChain(attestationChain);
4236                }
4237            } catch (KeyAttestationException e) {
4238                Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
4239                mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4240                return null;
4241            }
4242            return new AttestedKeyPair(keyPair, outputChain);
4243        } catch (RemoteException e) {
4244            throw e.rethrowFromSystemServer();
4245        } catch (KeyChainException e) {
4246            Log.w(TAG, "Failed to generate key", e);
4247        } catch (InterruptedException e) {
4248            Log.w(TAG, "Interrupted while generating key", e);
4249            Thread.currentThread().interrupt();
4250        }
4251        return null;
4252    }
4253
4254
4255    /**
4256     * Called by a device or profile owner, or delegated certificate installer, to associate
4257     * certificates with a key pair that was generated using {@link #generateKeyPair}, and
4258     * set whether the key is available for the user to choose in the certificate selection
4259     * prompt.
4260     *
4261     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4262     *            {@code null} if calling from a delegated certificate installer.
4263     * @param alias The private key alias under which to install the certificate. The {@code alias}
4264     *        should denote an existing private key. If a certificate with that alias already
4265     *        exists, it will be overwritten.
4266     * @param certs The certificate chain to install. The chain should start with the leaf
4267     *        certificate and include the chain of trust in order. This will be returned by
4268     *        {@link android.security.KeyChain#getCertificateChain}.
4269     * @param isUserSelectable {@code true} to indicate that a user can select this key via the
4270     *        certificate selection prompt, {@code false} to indicate that this key can only be
4271     *        granted access by implementing
4272     *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
4273     * @return {@code true} if the provided {@code alias} exists and the certificates has been
4274     *        successfully associated with it, {@code false} otherwise.
4275     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4276     *         owner, or {@code admin} is null but the calling application is not a delegated
4277     *         certificate installer.
4278     */
4279    public boolean setKeyPairCertificate(@Nullable ComponentName admin,
4280            @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
4281        throwIfParentInstance("setKeyPairCertificate");
4282        try {
4283            final byte[] pemCert = Credentials.convertToPem(certs.get(0));
4284            byte[] pemChain = null;
4285            if (certs.size() > 1) {
4286                pemChain = Credentials.convertToPem(
4287                        certs.subList(1, certs.size()).toArray(new Certificate[0]));
4288            }
4289            return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
4290                    pemChain, isUserSelectable);
4291        } catch (RemoteException e) {
4292            throw e.rethrowFromSystemServer();
4293        } catch (CertificateException | IOException e) {
4294            Log.w(TAG, "Could not pem-encode certificate", e);
4295        }
4296        return false;
4297    }
4298
4299
4300    /**
4301     * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
4302     * doesn't exist.
4303     */
4304    private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
4305        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4306        final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
4307                              new ByteArrayInputStream(certBuffer));
4308        return new TrustedCertificateStore().getCertificateAlias(cert);
4309    }
4310
4311    /**
4312     * Called by a profile owner or device owner to grant access to privileged certificate
4313     * manipulation APIs to a third-party certificate installer app. Granted APIs include
4314     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
4315     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
4316     * <p>
4317     * Delegated certificate installer is a per-user state. The delegated access is persistent until
4318     * it is later cleared by calling this method with a null value or uninstallling the certificate
4319     * installer.
4320     * <p>
4321     * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
4322     * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
4323     * supplied certificate installer package must be installed when calling this API, otherwise an
4324     * {@link IllegalArgumentException} will be thrown.
4325     *
4326     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4327     * @param installerPackage The package name of the certificate installer which will be given
4328     *            access. If {@code null} is given the current package will be cleared.
4329     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4330     *
4331     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
4332     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
4333     */
4334    @Deprecated
4335    public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
4336            installerPackage) throws SecurityException {
4337        throwIfParentInstance("setCertInstallerPackage");
4338        if (mService != null) {
4339            try {
4340                mService.setCertInstallerPackage(admin, installerPackage);
4341            } catch (RemoteException e) {
4342                throw e.rethrowFromSystemServer();
4343            }
4344        }
4345    }
4346
4347    /**
4348     * Called by a profile owner or device owner to retrieve the certificate installer for the user,
4349     * or {@code null} if none is set. If there are multiple delegates this function will return one
4350     * of them.
4351     *
4352     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4353     * @return The package name of the current delegated certificate installer, or {@code null} if
4354     *         none is set.
4355     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4356     *
4357     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
4358     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
4359     */
4360    @Deprecated
4361    public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
4362            throws SecurityException {
4363        throwIfParentInstance("getCertInstallerPackage");
4364        if (mService != null) {
4365            try {
4366                return mService.getCertInstallerPackage(admin);
4367            } catch (RemoteException e) {
4368                throw e.rethrowFromSystemServer();
4369            }
4370        }
4371        return null;
4372    }
4373
4374    /**
4375     * Called by a profile owner or device owner to grant access to privileged APIs to another app.
4376     * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
4377     * constants.
4378     * <p>
4379     * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
4380     * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
4381     * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
4382     * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
4383     * <p>
4384     * Delegated scopes are a per-user state. The delegated access is persistent until it is later
4385     * cleared by calling this method with an empty {@code scopes} list or uninstalling the
4386     * {@code delegatePackage}.
4387     *
4388     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4389     * @param delegatePackage The package name of the app which will be given access.
4390     * @param scopes The groups of privileged APIs whose access should be granted to
4391     *            {@code delegatedPackage}.
4392     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4393     */
4394     public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
4395            @NonNull List<String> scopes) {
4396        throwIfParentInstance("setDelegatedScopes");
4397        if (mService != null) {
4398            try {
4399                mService.setDelegatedScopes(admin, delegatePackage, scopes);
4400            } catch (RemoteException e) {
4401                throw e.rethrowFromSystemServer();
4402            }
4403        }
4404    }
4405
4406    /**
4407     * Called by a profile owner or device owner to retrieve a list of the scopes given to a
4408     * delegate package. Other apps can use this method to retrieve their own delegated scopes by
4409     * passing {@code null} for {@code admin} and their own package name as
4410     * {@code delegatedPackage}.
4411     *
4412     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4413     *            {@code null} if the caller is {@code delegatedPackage}.
4414     * @param delegatedPackage The package name of the app whose scopes should be retrieved.
4415     * @return A list containing the scopes given to {@code delegatedPackage}.
4416     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4417     */
4418     @NonNull
4419     public List<String> getDelegatedScopes(@Nullable ComponentName admin,
4420             @NonNull String delegatedPackage) {
4421         throwIfParentInstance("getDelegatedScopes");
4422         if (mService != null) {
4423             try {
4424                 return mService.getDelegatedScopes(admin, delegatedPackage);
4425             } catch (RemoteException e) {
4426                 throw e.rethrowFromSystemServer();
4427             }
4428         }
4429         return null;
4430    }
4431
4432    /**
4433     * Called by a profile owner or device owner to retrieve a list of delegate packages that were
4434     * granted a delegation scope.
4435     *
4436     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4437     * @param delegationScope The scope whose delegates should be retrieved.
4438     * @return A list of package names of the current delegated packages for
4439               {@code delegationScope}.
4440     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4441     */
4442     @Nullable
4443     public List<String> getDelegatePackages(@NonNull ComponentName admin,
4444             @NonNull String delegationScope) {
4445        throwIfParentInstance("getDelegatePackages");
4446        if (mService != null) {
4447            try {
4448                return mService.getDelegatePackages(admin, delegationScope);
4449            } catch (RemoteException e) {
4450                throw e.rethrowFromSystemServer();
4451            }
4452        }
4453        return null;
4454    }
4455
4456    /**
4457     * Called by a device or profile owner to configure an always-on VPN connection through a
4458     * specific application for the current user. This connection is automatically granted and
4459     * persisted after a reboot.
4460     * <p>
4461     * To support the always-on feature, an app must
4462     * <ul>
4463     *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
4464     *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
4465     *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
4466     *     <li><i>not</i> explicitly opt out of the feature through
4467     *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
4468     * </ul>
4469     * The call will fail if called with the package name of an unsupported VPN app.
4470     *
4471     * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
4472     *        remove an existing always-on VPN configuration.
4473     * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
4474     *        {@code false} otherwise. This carries the risk that any failure of the VPN provider
4475     *        could break networking for all apps. This has no effect when clearing.
4476     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4477     * @throws NameNotFoundException if {@code vpnPackage} is not installed.
4478     * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
4479     *         set as always-on, or if always-on VPN is not available.
4480     */
4481    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
4482            boolean lockdownEnabled)
4483            throws NameNotFoundException, UnsupportedOperationException {
4484        throwIfParentInstance("setAlwaysOnVpnPackage");
4485        if (mService != null) {
4486            try {
4487                if (!mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled)) {
4488                    throw new NameNotFoundException(vpnPackage);
4489                }
4490            } catch (RemoteException e) {
4491                throw e.rethrowFromSystemServer();
4492            }
4493        }
4494    }
4495
4496    /**
4497     * Called by a device or profile owner to read the name of the package administering an
4498     * always-on VPN connection for the current user. If there is no such package, or the always-on
4499     * VPN is provided by the system instead of by an application, {@code null} will be returned.
4500     *
4501     * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
4502     *         is set.
4503     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4504     */
4505    public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
4506        throwIfParentInstance("getAlwaysOnVpnPackage");
4507        if (mService != null) {
4508            try {
4509                return mService.getAlwaysOnVpnPackage(admin);
4510            } catch (RemoteException e) {
4511                throw e.rethrowFromSystemServer();
4512            }
4513        }
4514        return null;
4515    }
4516
4517    /**
4518     * Called by an application that is administering the device to disable all cameras on the
4519     * device, for this user. After setting this, no applications running as this user will be able
4520     * to access any cameras on the device.
4521     * <p>
4522     * If the caller is device owner, then the restriction will be applied to all users.
4523     * <p>
4524     * The calling device admin must have requested
4525     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
4526     * not, a security exception will be thrown.
4527     *
4528     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4529     * @param disabled Whether or not the camera should be disabled.
4530     * @throws SecurityException if {@code admin} is not an active administrator or does not use
4531     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
4532     */
4533    public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
4534        throwIfParentInstance("setCameraDisabled");
4535        if (mService != null) {
4536            try {
4537                mService.setCameraDisabled(admin, disabled);
4538            } catch (RemoteException e) {
4539                throw e.rethrowFromSystemServer();
4540            }
4541        }
4542    }
4543
4544    /**
4545     * Determine whether or not the device's cameras have been disabled for this user,
4546     * either by the calling admin, if specified, or all admins.
4547     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4548     * have disabled the camera
4549     */
4550    public boolean getCameraDisabled(@Nullable ComponentName admin) {
4551        throwIfParentInstance("getCameraDisabled");
4552        return getCameraDisabled(admin, myUserId());
4553    }
4554
4555    /** @hide per-user version */
4556    public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
4557        if (mService != null) {
4558            try {
4559                return mService.getCameraDisabled(admin, userHandle);
4560            } catch (RemoteException e) {
4561                throw e.rethrowFromSystemServer();
4562            }
4563        }
4564        return false;
4565    }
4566
4567    /**
4568     * Called by a device owner to request a bugreport.
4569     * <p>
4570     * If the device contains secondary users or profiles, they must be affiliated with the device.
4571     * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
4572     *
4573     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4574     * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
4575     *         wasn't triggered because a previous bugreport operation is still active (either the
4576     *         bugreport is still running or waiting for the user to share or decline)
4577     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
4578     *         profile or secondary user that is not affiliated with the device.
4579     * @see #isAffiliatedUser
4580     */
4581    public boolean requestBugreport(@NonNull ComponentName admin) {
4582        throwIfParentInstance("requestBugreport");
4583        if (mService != null) {
4584            try {
4585                return mService.requestBugreport(admin);
4586            } catch (RemoteException e) {
4587                throw e.rethrowFromSystemServer();
4588            }
4589        }
4590        return false;
4591    }
4592
4593    /**
4594     * Determine whether or not creating a guest user has been disabled for the device
4595     *
4596     * @hide
4597     */
4598    public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
4599        // Currently guest users can always be created if multi-user is enabled
4600        // TODO introduce a policy for guest user creation
4601        return false;
4602    }
4603
4604    /**
4605     * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
4606     * screen capture also prevents the content from being shown on display devices that do not have
4607     * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
4608     * secure surfaces and secure displays.
4609     * <p>
4610     * The calling device admin must be a device or profile owner. If it is not, a security
4611     * exception will be thrown.
4612     * <p>
4613     * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
4614     * assist requests for all activities of the relevant user.
4615     *
4616     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4617     * @param disabled Whether screen capture is disabled or not.
4618     * @throws SecurityException if {@code admin} is not a device or profile owner.
4619     */
4620    public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
4621        throwIfParentInstance("setScreenCaptureDisabled");
4622        if (mService != null) {
4623            try {
4624                mService.setScreenCaptureDisabled(admin, disabled);
4625            } catch (RemoteException e) {
4626                throw e.rethrowFromSystemServer();
4627            }
4628        }
4629    }
4630
4631    /**
4632     * Determine whether or not screen capture has been disabled by the calling
4633     * admin, if specified, or all admins.
4634     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4635     * have disabled screen capture.
4636     */
4637    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
4638        throwIfParentInstance("getScreenCaptureDisabled");
4639        return getScreenCaptureDisabled(admin, myUserId());
4640    }
4641
4642    /** @hide per-user version */
4643    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
4644        if (mService != null) {
4645            try {
4646                return mService.getScreenCaptureDisabled(admin, userHandle);
4647            } catch (RemoteException e) {
4648                throw e.rethrowFromSystemServer();
4649            }
4650        }
4651        return false;
4652    }
4653
4654    /**
4655     * Called by a device or profile owner to set whether auto time is required. If auto time is
4656     * required, no user will be able set the date and time and network date and time will be used.
4657     * <p>
4658     * Note: if auto time is required the user can still manually set the time zone.
4659     * <p>
4660     * The calling device admin must be a device or profile owner. If it is not, a security
4661     * exception will be thrown.
4662     *
4663     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4664     * @param required Whether auto time is set required or not.
4665     * @throws SecurityException if {@code admin} is not a device owner.
4666     */
4667    public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
4668        throwIfParentInstance("setAutoTimeRequired");
4669        if (mService != null) {
4670            try {
4671                mService.setAutoTimeRequired(admin, required);
4672            } catch (RemoteException e) {
4673                throw e.rethrowFromSystemServer();
4674            }
4675        }
4676    }
4677
4678    /**
4679     * @return true if auto time is required.
4680     */
4681    public boolean getAutoTimeRequired() {
4682        throwIfParentInstance("getAutoTimeRequired");
4683        if (mService != null) {
4684            try {
4685                return mService.getAutoTimeRequired();
4686            } catch (RemoteException e) {
4687                throw e.rethrowFromSystemServer();
4688            }
4689        }
4690        return false;
4691    }
4692
4693    /**
4694     * Called by a device owner to set whether all users created on the device should be ephemeral.
4695     * <p>
4696     * The system user is exempt from this policy - it is never ephemeral.
4697     * <p>
4698     * The calling device admin must be the device owner. If it is not, a security exception will be
4699     * thrown.
4700     *
4701     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4702     * @param forceEphemeralUsers If true, all the existing users will be deleted and all
4703     *            subsequently created users will be ephemeral.
4704     * @throws SecurityException if {@code admin} is not a device owner.
4705     * @hide
4706     */
4707    public void setForceEphemeralUsers(
4708            @NonNull ComponentName admin, boolean forceEphemeralUsers) {
4709        throwIfParentInstance("setForceEphemeralUsers");
4710        if (mService != null) {
4711            try {
4712                mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
4713            } catch (RemoteException e) {
4714                throw e.rethrowFromSystemServer();
4715            }
4716        }
4717    }
4718
4719    /**
4720     * @return true if all users are created ephemeral.
4721     * @throws SecurityException if {@code admin} is not a device owner.
4722     * @hide
4723     */
4724    public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
4725        throwIfParentInstance("getForceEphemeralUsers");
4726        if (mService != null) {
4727            try {
4728                return mService.getForceEphemeralUsers(admin);
4729            } catch (RemoteException e) {
4730                throw e.rethrowFromSystemServer();
4731            }
4732        }
4733        return false;
4734    }
4735
4736    /**
4737     * Called by an application that is administering the device to disable keyguard customizations,
4738     * such as widgets. After setting this, keyguard features will be disabled according to the
4739     * provided feature list.
4740     * <p>
4741     * The calling device admin must have requested
4742     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
4743     * if it has not, a security exception will be thrown.
4744     * <p>
4745     * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
4746     * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
4747     * profile owner of a managed profile can set:
4748     * <ul>
4749     * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
4750     * is no separate challenge set on the managed profile.
4751     * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT} which affects the managed profile challenge if
4752     * there is one, or the parent user otherwise.
4753     * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
4754     * by applications in the managed profile.
4755     * </ul>
4756     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and {@link #KEYGUARD_DISABLE_FINGERPRINT} can also be
4757     * set on the {@link DevicePolicyManager} instance returned by
4758     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4759     * profile.
4760     * <p>
4761     * Requests to disable other features on a managed profile will be ignored.
4762     * <p>
4763     * The admin can check which features have been disabled by calling
4764     * {@link #getKeyguardDisabledFeatures(ComponentName)}
4765     *
4766     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4767     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
4768     *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
4769     *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
4770     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
4771     *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
4772     *            {@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
4773     * @throws SecurityException if {@code admin} is not an active administrator or does not user
4774     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
4775     */
4776    public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
4777        if (mService != null) {
4778            try {
4779                mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
4780            } catch (RemoteException e) {
4781                throw e.rethrowFromSystemServer();
4782            }
4783        }
4784    }
4785
4786    /**
4787     * Determine whether or not features have been disabled in keyguard either by the calling
4788     * admin, if specified, or all admins that set restrictions on this user and its participating
4789     * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
4790     *
4791     * <p>This method can be called on the {@link DevicePolicyManager} instance
4792     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4793     * restrictions on the parent profile.
4794     *
4795     * @param admin The name of the admin component to check, or {@code null} to check whether any
4796     * admins have disabled features in keyguard.
4797     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
4798     * for a list.
4799     */
4800    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
4801        return getKeyguardDisabledFeatures(admin, myUserId());
4802    }
4803
4804    /** @hide per-user version */
4805    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
4806        if (mService != null) {
4807            try {
4808                return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
4809            } catch (RemoteException e) {
4810                throw e.rethrowFromSystemServer();
4811            }
4812        }
4813        return KEYGUARD_DISABLE_FEATURES_NONE;
4814    }
4815
4816    /**
4817     * @hide
4818     */
4819    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
4820            int userHandle) {
4821        if (mService != null) {
4822            try {
4823                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
4824            } catch (RemoteException e) {
4825                throw e.rethrowFromSystemServer();
4826            }
4827        }
4828    }
4829
4830    /**
4831     * @hide
4832     */
4833    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
4834        setActiveAdmin(policyReceiver, refreshing, myUserId());
4835    }
4836
4837    /**
4838     * @hide
4839     */
4840    public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
4841        if (mService != null) {
4842            try {
4843                mService.getRemoveWarning(admin, result, myUserId());
4844            } catch (RemoteException e) {
4845                throw e.rethrowFromSystemServer();
4846            }
4847        }
4848    }
4849
4850    /**
4851     * @hide
4852     */
4853    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
4854        if (mService != null) {
4855            try {
4856                mService.setActivePasswordState(metrics, userHandle);
4857            } catch (RemoteException e) {
4858                throw e.rethrowFromSystemServer();
4859            }
4860        }
4861    }
4862
4863    /**
4864     * @hide
4865     */
4866    public void reportPasswordChanged(@UserIdInt int userId) {
4867        if (mService != null) {
4868            try {
4869                mService.reportPasswordChanged(userId);
4870            } catch (RemoteException e) {
4871                throw e.rethrowFromSystemServer();
4872            }
4873        }
4874    }
4875
4876    /**
4877     * @hide
4878     */
4879    public void reportFailedPasswordAttempt(int userHandle) {
4880        if (mService != null) {
4881            try {
4882                mService.reportFailedPasswordAttempt(userHandle);
4883            } catch (RemoteException e) {
4884                throw e.rethrowFromSystemServer();
4885            }
4886        }
4887    }
4888
4889    /**
4890     * @hide
4891     */
4892    public void reportSuccessfulPasswordAttempt(int userHandle) {
4893        if (mService != null) {
4894            try {
4895                mService.reportSuccessfulPasswordAttempt(userHandle);
4896            } catch (RemoteException e) {
4897                throw e.rethrowFromSystemServer();
4898            }
4899        }
4900    }
4901
4902    /**
4903     * @hide
4904     */
4905    public void reportFailedFingerprintAttempt(int userHandle) {
4906        if (mService != null) {
4907            try {
4908                mService.reportFailedFingerprintAttempt(userHandle);
4909            } catch (RemoteException e) {
4910                throw e.rethrowFromSystemServer();
4911            }
4912        }
4913    }
4914
4915    /**
4916     * @hide
4917     */
4918    public void reportSuccessfulFingerprintAttempt(int userHandle) {
4919        if (mService != null) {
4920            try {
4921                mService.reportSuccessfulFingerprintAttempt(userHandle);
4922            } catch (RemoteException e) {
4923                throw e.rethrowFromSystemServer();
4924            }
4925        }
4926    }
4927
4928    /**
4929     * Should be called when keyguard has been dismissed.
4930     * @hide
4931     */
4932    public void reportKeyguardDismissed(int userHandle) {
4933        if (mService != null) {
4934            try {
4935                mService.reportKeyguardDismissed(userHandle);
4936            } catch (RemoteException e) {
4937                throw e.rethrowFromSystemServer();
4938            }
4939        }
4940    }
4941
4942    /**
4943     * Should be called when keyguard view has been shown to the user.
4944     * @hide
4945     */
4946    public void reportKeyguardSecured(int userHandle) {
4947        if (mService != null) {
4948            try {
4949                mService.reportKeyguardSecured(userHandle);
4950            } catch (RemoteException e) {
4951                throw e.rethrowFromSystemServer();
4952            }
4953        }
4954    }
4955
4956    /**
4957     * @hide
4958     * Sets the given package as the device owner.
4959     * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
4960     * @param who the component name to be registered as device owner.
4961     * @return whether the package was successfully registered as the device owner.
4962     * @throws IllegalArgumentException if the package name is null or invalid
4963     * @throws IllegalStateException If the preconditions mentioned are not met.
4964     */
4965    public boolean setDeviceOwner(ComponentName who) {
4966        return setDeviceOwner(who, null);
4967    }
4968
4969    /**
4970     * @hide
4971     */
4972    public boolean setDeviceOwner(ComponentName who, int userId)  {
4973        return setDeviceOwner(who, null, userId);
4974    }
4975
4976    /**
4977     * @hide
4978     */
4979    public boolean setDeviceOwner(ComponentName who, String ownerName) {
4980        return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
4981    }
4982
4983    /**
4984     * @hide
4985     * Sets the given package as the device owner. The package must already be installed. There
4986     * must not already be a device owner.
4987     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
4988     * this method.
4989     * Calling this after the setup phase of the primary user has completed is allowed only if
4990     * the caller is the shell uid, and there are no additional users and no accounts.
4991     * @param who the component name to be registered as device owner.
4992     * @param ownerName the human readable name of the institution that owns this device.
4993     * @param userId ID of the user on which the device owner runs.
4994     * @return whether the package was successfully registered as the device owner.
4995     * @throws IllegalArgumentException if the package name is null or invalid
4996     * @throws IllegalStateException If the preconditions mentioned are not met.
4997     */
4998    public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
4999            throws IllegalArgumentException, IllegalStateException {
5000        if (mService != null) {
5001            try {
5002                return mService.setDeviceOwner(who, ownerName, userId);
5003            } catch (RemoteException re) {
5004                throw re.rethrowFromSystemServer();
5005            }
5006        }
5007        return false;
5008    }
5009
5010    /**
5011     * Used to determine if a particular package has been registered as a Device Owner app.
5012     * A device owner app is a special device admin that cannot be deactivated by the user, once
5013     * activated as a device admin. It also cannot be uninstalled. To check whether a particular
5014     * package is currently registered as the device owner app, pass in the package name from
5015     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
5016     * admin apps that want to check whether they are also registered as the device owner app. The
5017     * exact mechanism by which a device admin app is registered as a device owner app is defined by
5018     * the setup process.
5019     * @param packageName the package name of the app, to compare with the registered device owner
5020     * app, if any.
5021     * @return whether or not the package is registered as the device owner app.
5022     */
5023    public boolean isDeviceOwnerApp(String packageName) {
5024        throwIfParentInstance("isDeviceOwnerApp");
5025        return isDeviceOwnerAppOnCallingUser(packageName);
5026    }
5027
5028    /**
5029     * @return true if a package is registered as device owner, only when it's running on the
5030     * calling user.
5031     *
5032     * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
5033     * @hide
5034     */
5035    public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
5036        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
5037    }
5038
5039    /**
5040     * @return true if a package is registered as device owner, even if it's running on a different
5041     * user.
5042     *
5043     * <p>Requires the MANAGE_USERS permission.
5044     *
5045     * @hide
5046     */
5047    public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
5048        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
5049    }
5050
5051    /**
5052     * @return device owner component name, only when it's running on the calling user.
5053     *
5054     * @hide
5055     */
5056    public ComponentName getDeviceOwnerComponentOnCallingUser() {
5057        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
5058    }
5059
5060    /**
5061     * @return device owner component name, even if it's running on a different user.
5062     *
5063     * @hide
5064     */
5065    @SystemApi
5066    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5067    public ComponentName getDeviceOwnerComponentOnAnyUser() {
5068        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
5069    }
5070
5071    private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
5072        if (packageName == null) {
5073            return false;
5074        }
5075        final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
5076        if (deviceOwner == null) {
5077            return false;
5078        }
5079        return packageName.equals(deviceOwner.getPackageName());
5080    }
5081
5082    private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
5083        if (mService != null) {
5084            try {
5085                return mService.getDeviceOwnerComponent(callingUserOnly);
5086            } catch (RemoteException re) {
5087                throw re.rethrowFromSystemServer();
5088            }
5089        }
5090        return null;
5091    }
5092
5093    /**
5094     * @return ID of the user who runs device owner, or {@link UserHandle#USER_NULL} if there's
5095     * no device owner.
5096     *
5097     * <p>Requires the MANAGE_USERS permission.
5098     *
5099     * @hide
5100     */
5101    public int getDeviceOwnerUserId() {
5102        if (mService != null) {
5103            try {
5104                return mService.getDeviceOwnerUserId();
5105            } catch (RemoteException re) {
5106                throw re.rethrowFromSystemServer();
5107            }
5108        }
5109        return UserHandle.USER_NULL;
5110    }
5111
5112    /**
5113     * Clears the current device owner. The caller must be the device owner. This function should be
5114     * used cautiously as once it is called it cannot be undone. The device owner can only be set as
5115     * a part of device setup, before it completes.
5116     * <p>
5117     * While some policies previously set by the device owner will be cleared by this method, it is
5118     * a best-effort process and some other policies will still remain in place after the device
5119     * owner is cleared.
5120     *
5121     * @param packageName The package name of the device owner.
5122     * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
5123     *             does not own the current device owner component.
5124     *
5125     * @deprecated This method is expected to be used for testing purposes only. The device owner
5126     * will lose control of the device and its data after calling it. In order to protect any
5127     * sensitive data that remains on the device, it is advised that the device owner factory resets
5128     * the device instead of calling this method. See {@link #wipeData(int)}.
5129     */
5130    @Deprecated
5131    public void clearDeviceOwnerApp(String packageName) {
5132        throwIfParentInstance("clearDeviceOwnerApp");
5133        if (mService != null) {
5134            try {
5135                mService.clearDeviceOwner(packageName);
5136            } catch (RemoteException re) {
5137                throw re.rethrowFromSystemServer();
5138            }
5139        }
5140    }
5141
5142    /**
5143     * Returns the device owner package name, only if it's running on the calling user.
5144     *
5145     * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
5146     *
5147     * @hide
5148     */
5149    @SystemApi
5150    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5151    public @Nullable String getDeviceOwner() {
5152        throwIfParentInstance("getDeviceOwner");
5153        final ComponentName name = getDeviceOwnerComponentOnCallingUser();
5154        return name != null ? name.getPackageName() : null;
5155    }
5156
5157    /**
5158     * Called by the system to find out whether the device is managed by a Device Owner.
5159     *
5160     * @return whether the device is managed by a Device Owner.
5161     * @throws SecurityException if the caller is not the device owner, does not hold the
5162     *         MANAGE_USERS permission and is not the system.
5163     *
5164     * @hide
5165     */
5166    @SystemApi
5167    @TestApi
5168    @SuppressLint("Doclava125")
5169    public boolean isDeviceManaged() {
5170        try {
5171            return mService.hasDeviceOwner();
5172        } catch (RemoteException re) {
5173            throw re.rethrowFromSystemServer();
5174        }
5175    }
5176
5177    /**
5178     * Returns the device owner name.  Note this method *will* return the device owner
5179     * name when it's running on a different user.
5180     *
5181     * @hide
5182     */
5183    @SystemApi
5184    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5185    public String getDeviceOwnerNameOnAnyUser() {
5186        throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
5187        if (mService != null) {
5188            try {
5189                return mService.getDeviceOwnerName();
5190            } catch (RemoteException re) {
5191                throw re.rethrowFromSystemServer();
5192            }
5193        }
5194        return null;
5195    }
5196
5197    /**
5198     * @hide
5199     * @deprecated Do not use
5200     * @removed
5201     */
5202    @Deprecated
5203    @SystemApi
5204    @SuppressLint("Doclava125")
5205    public @Nullable String getDeviceInitializerApp() {
5206        return null;
5207    }
5208
5209    /**
5210     * @hide
5211     * @deprecated Do not use
5212     * @removed
5213     */
5214    @Deprecated
5215    @SystemApi
5216    @SuppressLint("Doclava125")
5217    public @Nullable ComponentName getDeviceInitializerComponent() {
5218        return null;
5219    }
5220
5221    /**
5222     * @hide
5223     * @deprecated Use #ACTION_SET_PROFILE_OWNER
5224     * Sets the given component as an active admin and registers the package as the profile
5225     * owner for this user. The package must already be installed and there shouldn't be
5226     * an existing profile owner registered for this user. Also, this method must be called
5227     * before the user setup has been completed.
5228     * <p>
5229     * This method can only be called by system apps that hold MANAGE_USERS permission and
5230     * MANAGE_DEVICE_ADMINS permission.
5231     * @param admin The component to register as an active admin and profile owner.
5232     * @param ownerName The user-visible name of the entity that is managing this user.
5233     * @return whether the admin was successfully registered as the profile owner.
5234     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
5235     *         the user has already been set up.
5236     */
5237    @Deprecated
5238    @SystemApi
5239    @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
5240    public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
5241            throws IllegalArgumentException {
5242        throwIfParentInstance("setActiveProfileOwner");
5243        if (mService != null) {
5244            try {
5245                final int myUserId = myUserId();
5246                mService.setActiveAdmin(admin, false, myUserId);
5247                return mService.setProfileOwner(admin, ownerName, myUserId);
5248            } catch (RemoteException re) {
5249                throw re.rethrowFromSystemServer();
5250            }
5251        }
5252        return false;
5253    }
5254
5255    /**
5256     * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
5257     * a SecurityException will be thrown. This method is not available to managed profile owners.
5258     * <p>
5259     * While some policies previously set by the profile owner will be cleared by this method, it is
5260     * a best-effort process and some other policies will still remain in place after the profile
5261     * owner is cleared.
5262     *
5263     * @param admin The component to remove as the profile owner.
5264     * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
5265     * being called from a managed profile.
5266     *
5267     * @deprecated This method is expected to be used for testing purposes only. The profile owner
5268     * will lose control of the user and its data after calling it. In order to protect any
5269     * sensitive data that remains on this user, it is advised that the profile owner deletes it
5270     * instead of calling this method. See {@link #wipeData(int)}.
5271     */
5272    @Deprecated
5273    public void clearProfileOwner(@NonNull ComponentName admin) {
5274        throwIfParentInstance("clearProfileOwner");
5275        if (mService != null) {
5276            try {
5277                mService.clearProfileOwner(admin);
5278            } catch (RemoteException re) {
5279                throw re.rethrowFromSystemServer();
5280            }
5281        }
5282    }
5283
5284    /**
5285     * @hide
5286     * Checks whether the user was already setup.
5287     */
5288    public boolean hasUserSetupCompleted() {
5289        if (mService != null) {
5290            try {
5291                return mService.hasUserSetupCompleted();
5292            } catch (RemoteException re) {
5293                throw re.rethrowFromSystemServer();
5294            }
5295        }
5296        return true;
5297    }
5298
5299    /**
5300     * @hide
5301     * Sets the given component as the profile owner of the given user profile. The package must
5302     * already be installed. There must not already be a profile owner for this user.
5303     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
5304     * this method.
5305     * Calling this after the setup phase of the specified user has completed is allowed only if:
5306     * - the caller is SYSTEM_UID.
5307     * - or the caller is the shell uid, and there are no accounts on the specified user.
5308     * @param admin the component name to be registered as profile owner.
5309     * @param ownerName the human readable name of the organisation associated with this DPM.
5310     * @param userHandle the userId to set the profile owner for.
5311     * @return whether the component was successfully registered as the profile owner.
5312     * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
5313     * preconditions mentioned are not met.
5314     */
5315    public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
5316            int userHandle) throws IllegalArgumentException {
5317        if (mService != null) {
5318            try {
5319                if (ownerName == null) {
5320                    ownerName = "";
5321                }
5322                return mService.setProfileOwner(admin, ownerName, userHandle);
5323            } catch (RemoteException re) {
5324                throw re.rethrowFromSystemServer();
5325            }
5326        }
5327        return false;
5328    }
5329
5330    /**
5331     * Sets the device owner information to be shown on the lock screen.
5332     * <p>
5333     * If the device owner information is {@code null} or empty then the device owner info is
5334     * cleared and the user owner info is shown on the lock screen if it is set.
5335     * <p>
5336     * If the device owner information contains only whitespaces then the message on the lock screen
5337     * will be blank and the user will not be allowed to change it.
5338     * <p>
5339     * If the device owner information needs to be localized, it is the responsibility of the
5340     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
5341     * and set a new version of this string accordingly.
5342     *
5343     * @param admin The name of the admin component to check.
5344     * @param info Device owner information which will be displayed instead of the user owner info.
5345     * @throws SecurityException if {@code admin} is not a device owner.
5346     */
5347    public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
5348        throwIfParentInstance("setDeviceOwnerLockScreenInfo");
5349        if (mService != null) {
5350            try {
5351                mService.setDeviceOwnerLockScreenInfo(admin, info);
5352            } catch (RemoteException re) {
5353                throw re.rethrowFromSystemServer();
5354            }
5355        }
5356    }
5357
5358    /**
5359     * @return The device owner information. If it is not set returns {@code null}.
5360     */
5361    public CharSequence getDeviceOwnerLockScreenInfo() {
5362        throwIfParentInstance("getDeviceOwnerLockScreenInfo");
5363        if (mService != null) {
5364            try {
5365                return mService.getDeviceOwnerLockScreenInfo();
5366            } catch (RemoteException re) {
5367                throw re.rethrowFromSystemServer();
5368            }
5369        }
5370        return null;
5371    }
5372
5373    /**
5374     * Called by device or profile owners to suspend packages for this user. This function can be
5375     * called by a device owner, profile owner, or by a delegate given the
5376     * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
5377     * <p>
5378     * A suspended package will not be able to start activities. Its notifications will be hidden,
5379     * it will not show up in recents, will not be able to show toasts or dialogs or ring the
5380     * device.
5381     * <p>
5382     * The package must already be installed. If the package is uninstalled while suspended the
5383     * package will no longer be suspended. The admin can block this by using
5384     * {@link #setUninstallBlocked}.
5385     *
5386     * @param admin The name of the admin component to check, or {@code null} if the caller is a
5387     *            package access delegate.
5388     * @param packageNames The package names to suspend or unsuspend.
5389     * @param suspended If set to {@code true} than the packages will be suspended, if set to
5390     *            {@code false} the packages will be unsuspended.
5391     * @return an array of package names for which the suspended status is not set as requested in
5392     *         this method.
5393     * @throws SecurityException if {@code admin} is not a device or profile owner.
5394     * @see #setDelegatedScopes
5395     * @see #DELEGATION_PACKAGE_ACCESS
5396     */
5397    public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
5398            @NonNull String[] packageNames, boolean suspended) {
5399        throwIfParentInstance("setPackagesSuspended");
5400        if (mService != null) {
5401            try {
5402                return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
5403                        suspended);
5404            } catch (RemoteException re) {
5405                throw re.rethrowFromSystemServer();
5406            }
5407        }
5408        return packageNames;
5409    }
5410
5411    /**
5412     * Determine if a package is suspended. This function can be called by a device owner, profile
5413     * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
5414     * {@link #setDelegatedScopes}.
5415     *
5416     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5417     *            {@code null} if the caller is a package access delegate.
5418     * @param packageName The name of the package to retrieve the suspended status of.
5419     * @return {@code true} if the package is suspended or {@code false} if the package is not
5420     *         suspended, could not be found or an error occurred.
5421     * @throws SecurityException if {@code admin} is not a device or profile owner.
5422     * @throws NameNotFoundException if the package could not be found.
5423     * @see #setDelegatedScopes
5424     * @see #DELEGATION_PACKAGE_ACCESS
5425     */
5426    public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
5427            throws NameNotFoundException {
5428        throwIfParentInstance("isPackageSuspended");
5429        if (mService != null) {
5430            try {
5431                return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
5432            } catch (RemoteException e) {
5433                throw e.rethrowFromSystemServer();
5434            } catch (IllegalArgumentException ex) {
5435                throw new NameNotFoundException(packageName);
5436            }
5437        }
5438        return false;
5439    }
5440
5441    /**
5442     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
5443     * be used. Only the profile owner can call this.
5444     *
5445     * @see #isProfileOwnerApp
5446     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5447     * @throws SecurityException if {@code admin} is not a profile owner.
5448     */
5449    public void setProfileEnabled(@NonNull ComponentName admin) {
5450        throwIfParentInstance("setProfileEnabled");
5451        if (mService != null) {
5452            try {
5453                mService.setProfileEnabled(admin);
5454            } catch (RemoteException e) {
5455                throw e.rethrowFromSystemServer();
5456            }
5457        }
5458    }
5459
5460    /**
5461     * Sets the name of the profile. In the device owner case it sets the name of the user which it
5462     * is called from. Only a profile owner or device owner can call this. If this is never called
5463     * by the profile or device owner, the name will be set to default values.
5464     *
5465     * @see #isProfileOwnerApp
5466     * @see #isDeviceOwnerApp
5467     * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
5468     * @param profileName The name of the profile.
5469     * @throws SecurityException if {@code admin} is not a device or profile owner.
5470     */
5471    public void setProfileName(@NonNull ComponentName admin, String profileName) {
5472        throwIfParentInstance("setProfileName");
5473        if (mService != null) {
5474            try {
5475                mService.setProfileName(admin, profileName);
5476            } catch (RemoteException e) {
5477                throw e.rethrowFromSystemServer();
5478            }
5479        }
5480    }
5481
5482    /**
5483     * Used to determine if a particular package is registered as the profile owner for the
5484     * user. A profile owner is a special device admin that has additional privileges
5485     * within the profile.
5486     *
5487     * @param packageName The package name of the app to compare with the registered profile owner.
5488     * @return Whether or not the package is registered as the profile owner.
5489     */
5490    public boolean isProfileOwnerApp(String packageName) {
5491        throwIfParentInstance("isProfileOwnerApp");
5492        if (mService != null) {
5493            try {
5494                ComponentName profileOwner = mService.getProfileOwner(myUserId());
5495                return profileOwner != null
5496                        && profileOwner.getPackageName().equals(packageName);
5497            } catch (RemoteException re) {
5498                throw re.rethrowFromSystemServer();
5499            }
5500        }
5501        return false;
5502    }
5503
5504    /**
5505     * @hide
5506     * @return the packageName of the owner of the given user profile or {@code null} if no profile
5507     * owner has been set for that user.
5508     * @throws IllegalArgumentException if the userId is invalid.
5509     */
5510    @SystemApi
5511    public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
5512        throwIfParentInstance("getProfileOwner");
5513        return getProfileOwnerAsUser(Process.myUserHandle().getIdentifier());
5514    }
5515
5516    /**
5517     * @see #getProfileOwner()
5518     * @hide
5519     */
5520    public @Nullable ComponentName getProfileOwnerAsUser(final int userId)
5521            throws IllegalArgumentException {
5522        if (mService != null) {
5523            try {
5524                return mService.getProfileOwner(userId);
5525            } catch (RemoteException re) {
5526                throw re.rethrowFromSystemServer();
5527            }
5528        }
5529        return null;
5530    }
5531
5532    /**
5533     * @hide
5534     * @return the human readable name of the organisation associated with this DPM or {@code null}
5535     *         if one is not set.
5536     * @throws IllegalArgumentException if the userId is invalid.
5537     */
5538    public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
5539        if (mService != null) {
5540            try {
5541                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
5542            } catch (RemoteException re) {
5543                throw re.rethrowFromSystemServer();
5544            }
5545        }
5546        return null;
5547    }
5548
5549    /**
5550     * @hide
5551     * @param userId The user for whom to fetch the profile owner name, if any.
5552     * @return the human readable name of the organisation associated with this profile owner or
5553     *         null if one is not set.
5554     * @throws IllegalArgumentException if the userId is invalid.
5555     */
5556    @SystemApi
5557    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5558    public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
5559        throwIfParentInstance("getProfileOwnerNameAsUser");
5560        if (mService != null) {
5561            try {
5562                return mService.getProfileOwnerName(userId);
5563            } catch (RemoteException re) {
5564                throw re.rethrowFromSystemServer();
5565            }
5566        }
5567        return null;
5568    }
5569
5570    /**
5571     * Called by a profile owner or device owner to add a default intent handler activity for
5572     * intents that match a certain intent filter. This activity will remain the default intent
5573     * handler even if the set of potential event handlers for the intent filter changes and if the
5574     * intent preferences are reset.
5575     * <p>
5576     * The default disambiguation mechanism takes over if the activity is not installed (anymore).
5577     * When the activity is (re)installed, it is automatically reset as default intent handler for
5578     * the filter.
5579     * <p>
5580     * The calling device admin must be a profile owner or device owner. If it is not, a security
5581     * exception will be thrown.
5582     *
5583     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5584     * @param filter The IntentFilter for which a default handler is added.
5585     * @param activity The Activity that is added as default intent handler.
5586     * @throws SecurityException if {@code admin} is not a device or profile owner.
5587     */
5588    public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
5589            @NonNull ComponentName activity) {
5590        throwIfParentInstance("addPersistentPreferredActivity");
5591        if (mService != null) {
5592            try {
5593                mService.addPersistentPreferredActivity(admin, filter, activity);
5594            } catch (RemoteException e) {
5595                throw e.rethrowFromSystemServer();
5596            }
5597        }
5598    }
5599
5600    /**
5601     * Called by a profile owner or device owner to remove all persistent intent handler preferences
5602     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
5603     * <p>
5604     * The calling device admin must be a profile owner. If it is not, a security exception will be
5605     * thrown.
5606     *
5607     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5608     * @param packageName The name of the package for which preferences are removed.
5609     * @throws SecurityException if {@code admin} is not a device or profile owner.
5610     */
5611    public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
5612            String packageName) {
5613        throwIfParentInstance("clearPackagePersistentPreferredActivities");
5614        if (mService != null) {
5615            try {
5616                mService.clearPackagePersistentPreferredActivities(admin, packageName);
5617            } catch (RemoteException e) {
5618                throw e.rethrowFromSystemServer();
5619            }
5620        }
5621    }
5622
5623    /**
5624     * Called by a profile owner or device owner to grant permission to a package to manage
5625     * application restrictions for the calling user via {@link #setApplicationRestrictions} and
5626     * {@link #getApplicationRestrictions}.
5627     * <p>
5628     * This permission is persistent until it is later cleared by calling this method with a
5629     * {@code null} value or uninstalling the managing package.
5630     * <p>
5631     * The supplied application restriction managing package must be installed when calling this
5632     * API, otherwise an {@link NameNotFoundException} will be thrown.
5633     *
5634     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5635     * @param packageName The package name which will be given access to application restrictions
5636     *            APIs. If {@code null} is given the current package will be cleared.
5637     * @throws SecurityException if {@code admin} is not a device or profile owner.
5638     * @throws NameNotFoundException if {@code packageName} is not found
5639     *
5640     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5641     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5642     */
5643    @Deprecated
5644    public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
5645            @Nullable String packageName) throws NameNotFoundException {
5646        throwIfParentInstance("setApplicationRestrictionsManagingPackage");
5647        if (mService != null) {
5648            try {
5649                if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
5650                    throw new NameNotFoundException(packageName);
5651                }
5652            } catch (RemoteException e) {
5653                throw e.rethrowFromSystemServer();
5654            }
5655        }
5656    }
5657
5658    /**
5659     * Called by a profile owner or device owner to retrieve the application restrictions managing
5660     * package for the current user, or {@code null} if none is set. If there are multiple
5661     * delegates this function will return one of them.
5662     *
5663     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5664     * @return The package name allowed to manage application restrictions on the current user, or
5665     *         {@code null} if none is set.
5666     * @throws SecurityException if {@code admin} is not a device or profile owner.
5667     *
5668     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5669     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5670     */
5671    @Deprecated
5672    @Nullable
5673    public String getApplicationRestrictionsManagingPackage(
5674            @NonNull ComponentName admin) {
5675        throwIfParentInstance("getApplicationRestrictionsManagingPackage");
5676        if (mService != null) {
5677            try {
5678                return mService.getApplicationRestrictionsManagingPackage(admin);
5679            } catch (RemoteException e) {
5680                throw e.rethrowFromSystemServer();
5681            }
5682        }
5683        return null;
5684    }
5685
5686    /**
5687     * Called by any application to find out whether it has been granted permission via
5688     * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
5689     * for the calling user.
5690     *
5691     * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
5692     * that method.
5693     *
5694     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
5695     * instead.
5696     */
5697    @Deprecated
5698    public boolean isCallerApplicationRestrictionsManagingPackage() {
5699        throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
5700        if (mService != null) {
5701            try {
5702                return mService.isCallerApplicationRestrictionsManagingPackage(
5703                        mContext.getPackageName());
5704            } catch (RemoteException e) {
5705                throw e.rethrowFromSystemServer();
5706            }
5707        }
5708        return false;
5709    }
5710
5711    /**
5712     * Sets the application restrictions for a given target application running in the calling user.
5713     * <p>
5714     * The caller must be a profile or device owner on that user, or the package allowed to manage
5715     * application restrictions via {@link #setDelegatedScopes} with the
5716     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
5717     * <p>
5718     * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
5719     * <ul>
5720     * <li>{@code boolean}
5721     * <li>{@code int}
5722     * <li>{@code String} or {@code String[]}
5723     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
5724     * </ul>
5725     * <p>
5726     * If the restrictions are not available yet, but may be applied in the near future, the caller
5727     * can notify the target application of that by adding
5728     * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
5729     * <p>
5730     * The application restrictions are only made visible to the target application via
5731     * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
5732     * owner, and the application restrictions managing package via
5733     * {@link #getApplicationRestrictions}.
5734     *
5735     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
5736     *
5737     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5738     *            {@code null} if called by the application restrictions managing package.
5739     * @param packageName The name of the package to update restricted settings for.
5740     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
5741     *            set of active restrictions.
5742     * @throws SecurityException if {@code admin} is not a device or profile owner.
5743     * @see #setDelegatedScopes
5744     * @see #DELEGATION_APP_RESTRICTIONS
5745     * @see UserManager#KEY_RESTRICTIONS_PENDING
5746     */
5747    @WorkerThread
5748    public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
5749            Bundle settings) {
5750        throwIfParentInstance("setApplicationRestrictions");
5751        if (mService != null) {
5752            try {
5753                mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
5754                        settings);
5755            } catch (RemoteException e) {
5756                throw e.rethrowFromSystemServer();
5757            }
5758        }
5759    }
5760
5761    /**
5762     * Sets a list of configuration features to enable for a TrustAgent component. This is meant to
5763     * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
5764     * agents but those enabled by this function call. If flag
5765     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
5766     * <p>
5767     * The calling device admin must have requested
5768     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
5769     * if not, a security exception will be thrown.
5770     * <p>
5771     * This method can be called on the {@link DevicePolicyManager} instance returned by
5772     * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
5773     * the parent profile.
5774     *
5775     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5776     * @param target Component name of the agent to be enabled.
5777     * @param configuration TrustAgent-specific feature bundle. If null for any admin, agent will be
5778     *            strictly disabled according to the state of the
5779     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS} flag.
5780     *            <p>
5781     *            If {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is set and options is not null for all
5782     *            admins, then it's up to the TrustAgent itself to aggregate the values from all
5783     *            device admins.
5784     *            <p>
5785     *            Consult documentation for the specific TrustAgent to determine legal options
5786     *            parameters.
5787     * @throws SecurityException if {@code admin} is not an active administrator or does not use
5788     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
5789     */
5790    public void setTrustAgentConfiguration(@NonNull ComponentName admin,
5791            @NonNull ComponentName target, PersistableBundle configuration) {
5792        if (mService != null) {
5793            try {
5794                mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
5795            } catch (RemoteException e) {
5796                throw e.rethrowFromSystemServer();
5797            }
5798        }
5799    }
5800
5801    /**
5802     * Gets configuration for the given trust agent based on aggregating all calls to
5803     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
5804     * all device admins.
5805     * <p>
5806     * This method can be called on the {@link DevicePolicyManager} instance returned by
5807     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
5808     * on the parent profile.
5809     *
5810     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
5811     * this function returns a list of configurations for all admins that declare
5812     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
5813     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
5814     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
5815     * for this {@param agent} or calls it with a null configuration, null is returned.
5816     * @param agent Which component to get enabled features for.
5817     * @return configuration for the given trust agent.
5818     */
5819    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5820            @Nullable ComponentName admin, @NonNull ComponentName agent) {
5821        return getTrustAgentConfiguration(admin, agent, myUserId());
5822    }
5823
5824    /** @hide per-user version */
5825    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5826            @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
5827        if (mService != null) {
5828            try {
5829                return mService.getTrustAgentConfiguration(admin, agent, userHandle,
5830                        mParentInstance);
5831            } catch (RemoteException e) {
5832                throw e.rethrowFromSystemServer();
5833            }
5834        }
5835        return new ArrayList<PersistableBundle>(); // empty list
5836    }
5837
5838    /**
5839     * Called by a profile owner of a managed profile to set whether caller-Id information from the
5840     * managed profile will be shown in the parent profile, for incoming calls.
5841     * <p>
5842     * The calling device admin must be a profile owner. If it is not, a security exception will be
5843     * thrown.
5844     *
5845     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5846     * @param disabled If true caller-Id information in the managed profile is not displayed.
5847     * @throws SecurityException if {@code admin} is not a device or profile owner.
5848     */
5849    public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
5850        throwIfParentInstance("setCrossProfileCallerIdDisabled");
5851        if (mService != null) {
5852            try {
5853                mService.setCrossProfileCallerIdDisabled(admin, disabled);
5854            } catch (RemoteException e) {
5855                throw e.rethrowFromSystemServer();
5856            }
5857        }
5858    }
5859
5860    /**
5861     * Called by a profile owner of a managed profile to determine whether or not caller-Id
5862     * information has been disabled.
5863     * <p>
5864     * The calling device admin must be a profile owner. If it is not, a security exception will be
5865     * thrown.
5866     *
5867     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5868     * @throws SecurityException if {@code admin} is not a device or profile owner.
5869     */
5870    public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
5871        throwIfParentInstance("getCrossProfileCallerIdDisabled");
5872        if (mService != null) {
5873            try {
5874                return mService.getCrossProfileCallerIdDisabled(admin);
5875            } catch (RemoteException e) {
5876                throw e.rethrowFromSystemServer();
5877            }
5878        }
5879        return false;
5880    }
5881
5882    /**
5883     * Determine whether or not caller-Id information has been disabled.
5884     *
5885     * @param userHandle The user for whom to check the caller-id permission
5886     * @hide
5887     */
5888    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
5889        if (mService != null) {
5890            try {
5891                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
5892            } catch (RemoteException e) {
5893                throw e.rethrowFromSystemServer();
5894            }
5895        }
5896        return false;
5897    }
5898
5899    /**
5900     * Called by a profile owner of a managed profile to set whether contacts search from the
5901     * managed profile will be shown in the parent profile, for incoming calls.
5902     * <p>
5903     * The calling device admin must be a profile owner. If it is not, a security exception will be
5904     * thrown.
5905     *
5906     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5907     * @param disabled If true contacts search in the managed profile is not displayed.
5908     * @throws SecurityException if {@code admin} is not a device or profile owner.
5909     */
5910    public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
5911            boolean disabled) {
5912        throwIfParentInstance("setCrossProfileContactsSearchDisabled");
5913        if (mService != null) {
5914            try {
5915                mService.setCrossProfileContactsSearchDisabled(admin, disabled);
5916            } catch (RemoteException e) {
5917                throw e.rethrowFromSystemServer();
5918            }
5919        }
5920    }
5921
5922    /**
5923     * Called by a profile owner of a managed profile to determine whether or not contacts search
5924     * has been disabled.
5925     * <p>
5926     * The calling device admin must be a profile owner. If it is not, a security exception will be
5927     * thrown.
5928     *
5929     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5930     * @throws SecurityException if {@code admin} is not a device or profile owner.
5931     */
5932    public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
5933        throwIfParentInstance("getCrossProfileContactsSearchDisabled");
5934        if (mService != null) {
5935            try {
5936                return mService.getCrossProfileContactsSearchDisabled(admin);
5937            } catch (RemoteException e) {
5938                throw e.rethrowFromSystemServer();
5939            }
5940        }
5941        return false;
5942    }
5943
5944
5945    /**
5946     * Determine whether or not contacts search has been disabled.
5947     *
5948     * @param userHandle The user for whom to check the contacts search permission
5949     * @hide
5950     */
5951    public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
5952        if (mService != null) {
5953            try {
5954                return mService
5955                        .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
5956            } catch (RemoteException e) {
5957                throw e.rethrowFromSystemServer();
5958            }
5959        }
5960        return false;
5961    }
5962
5963    /**
5964     * Start Quick Contact on the managed profile for the user, if the policy allows.
5965     *
5966     * @hide
5967     */
5968    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5969            boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
5970        if (mService != null) {
5971            try {
5972                mService.startManagedQuickContact(actualLookupKey, actualContactId,
5973                        isContactIdIgnored, directoryId, originalIntent);
5974            } catch (RemoteException e) {
5975                throw e.rethrowFromSystemServer();
5976            }
5977        }
5978    }
5979
5980    /**
5981     * Start Quick Contact on the managed profile for the user, if the policy allows.
5982     * @hide
5983     */
5984    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5985            Intent originalIntent) {
5986        startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
5987                originalIntent);
5988    }
5989
5990    /**
5991     * Called by a profile owner of a managed profile to set whether bluetooth devices can access
5992     * enterprise contacts.
5993     * <p>
5994     * The calling device admin must be a profile owner. If it is not, a security exception will be
5995     * thrown.
5996     * <p>
5997     * This API works on managed profile only.
5998     *
5999     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6000     * @param disabled If true, bluetooth devices cannot access enterprise contacts.
6001     * @throws SecurityException if {@code admin} is not a device or profile owner.
6002     */
6003    public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
6004        throwIfParentInstance("setBluetoothContactSharingDisabled");
6005        if (mService != null) {
6006            try {
6007                mService.setBluetoothContactSharingDisabled(admin, disabled);
6008            } catch (RemoteException e) {
6009                throw e.rethrowFromSystemServer();
6010            }
6011        }
6012    }
6013
6014    /**
6015     * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
6016     * cannot access enterprise contacts.
6017     * <p>
6018     * The calling device admin must be a profile owner. If it is not, a security exception will be
6019     * thrown.
6020     * <p>
6021     * This API works on managed profile only.
6022     *
6023     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6024     * @throws SecurityException if {@code admin} is not a device or profile owner.
6025     */
6026    public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
6027        throwIfParentInstance("getBluetoothContactSharingDisabled");
6028        if (mService != null) {
6029            try {
6030                return mService.getBluetoothContactSharingDisabled(admin);
6031            } catch (RemoteException e) {
6032                throw e.rethrowFromSystemServer();
6033            }
6034        }
6035        return true;
6036    }
6037
6038    /**
6039     * Determine whether or not Bluetooth devices cannot access contacts.
6040     * <p>
6041     * This API works on managed profile UserHandle only.
6042     *
6043     * @param userHandle The user for whom to check the caller-id permission
6044     * @hide
6045     */
6046    public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
6047        if (mService != null) {
6048            try {
6049                return mService.getBluetoothContactSharingDisabledForUser(userHandle
6050                        .getIdentifier());
6051            } catch (RemoteException e) {
6052                throw e.rethrowFromSystemServer();
6053            }
6054        }
6055        return true;
6056    }
6057
6058    /**
6059     * Called by the profile owner of a managed profile so that some intents sent in the managed
6060     * profile can also be resolved in the parent, or vice versa. Only activity intents are
6061     * supported.
6062     *
6063     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6064     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
6065     *            other profile
6066     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
6067     *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
6068     * @throws SecurityException if {@code admin} is not a device or profile owner.
6069     */
6070    public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
6071        throwIfParentInstance("addCrossProfileIntentFilter");
6072        if (mService != null) {
6073            try {
6074                mService.addCrossProfileIntentFilter(admin, filter, flags);
6075            } catch (RemoteException e) {
6076                throw e.rethrowFromSystemServer();
6077            }
6078        }
6079    }
6080
6081    /**
6082     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
6083     * that go from the managed profile to the parent, or from the parent to the managed profile.
6084     * Only removes those that have been set by the profile owner.
6085     * <p>
6086     * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
6087     * the profile is created, some of them ensure the proper functioning of the profile, while
6088     * others enable sharing of data from the parent to the managed profile for user convenience.
6089     * These default intent filters are not cleared when this API is called. If the default cross
6090     * profile data sharing is not desired, they can be disabled with
6091     * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
6092     *
6093     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6094     * @throws SecurityException if {@code admin} is not a device or profile owner.
6095     */
6096    public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
6097        throwIfParentInstance("clearCrossProfileIntentFilters");
6098        if (mService != null) {
6099            try {
6100                mService.clearCrossProfileIntentFilters(admin);
6101            } catch (RemoteException e) {
6102                throw e.rethrowFromSystemServer();
6103            }
6104        }
6105    }
6106
6107    /**
6108     * Called by a profile or device owner to set the permitted accessibility services. When set by
6109     * a device owner or profile owner the restriction applies to all profiles of the user the
6110     * device owner or profile owner is an admin for. By default the user can use any accessiblity
6111     * service. When zero or more packages have been added, accessiblity services that are not in
6112     * the list and not part of the system can not be enabled by the user.
6113     * <p>
6114     * Calling with a null value for the list disables the restriction so that all services can be
6115     * used, calling with an empty list only allows the builtin system's services.
6116     * <p>
6117     * System accessibility services are always available to the user the list can't modify this.
6118     *
6119     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6120     * @param packageNames List of accessibility service package names.
6121     * @return true if setting the restriction succeeded. It fail if there is one or more non-system
6122     *         accessibility services enabled, that are not in the list.
6123     * @throws SecurityException if {@code admin} is not a device or profile owner.
6124     */
6125    public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
6126            List<String> packageNames) {
6127        throwIfParentInstance("setPermittedAccessibilityServices");
6128        if (mService != null) {
6129            try {
6130                return mService.setPermittedAccessibilityServices(admin, packageNames);
6131            } catch (RemoteException e) {
6132                throw e.rethrowFromSystemServer();
6133            }
6134        }
6135        return false;
6136    }
6137
6138    /**
6139     * Returns the list of permitted accessibility services set by this device or profile owner.
6140     * <p>
6141     * An empty list means no accessibility services except system services are allowed. Null means
6142     * all accessibility services are allowed.
6143     *
6144     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6145     * @return List of accessiblity service package names.
6146     * @throws SecurityException if {@code admin} is not a device or profile owner.
6147     */
6148    public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
6149        throwIfParentInstance("getPermittedAccessibilityServices");
6150        if (mService != null) {
6151            try {
6152                return mService.getPermittedAccessibilityServices(admin);
6153            } catch (RemoteException e) {
6154                throw e.rethrowFromSystemServer();
6155            }
6156        }
6157        return null;
6158    }
6159
6160    /**
6161     * Called by the system to check if a specific accessibility service is disabled by admin.
6162     *
6163     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6164     * @param packageName Accessibility service package name that needs to be checked.
6165     * @param userHandle user id the admin is running as.
6166     * @return true if the accessibility service is permitted, otherwise false.
6167     *
6168     * @hide
6169     */
6170    public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
6171            @NonNull String packageName, int userHandle) {
6172        if (mService != null) {
6173            try {
6174                return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
6175                        userHandle);
6176            } catch (RemoteException e) {
6177                throw e.rethrowFromSystemServer();
6178            }
6179        }
6180        return false;
6181    }
6182
6183    /**
6184     * Returns the list of accessibility services permitted by the device or profiles
6185     * owners of this user.
6186     *
6187     * <p>Null means all accessibility services are allowed, if a non-null list is returned
6188     * it will contain the intersection of the permitted lists for any device or profile
6189     * owners that apply to this user. It will also include any system accessibility services.
6190     *
6191     * @param userId which user to check for.
6192     * @return List of accessiblity service package names.
6193     * @hide
6194     */
6195     @SystemApi
6196     public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
6197        throwIfParentInstance("getPermittedAccessibilityServices");
6198        if (mService != null) {
6199            try {
6200                return mService.getPermittedAccessibilityServicesForUser(userId);
6201            } catch (RemoteException e) {
6202                throw e.rethrowFromSystemServer();
6203            }
6204        }
6205        return null;
6206     }
6207
6208    /**
6209     * Called by a profile or device owner to set the permitted input methods services. When set by
6210     * a device owner or profile owner the restriction applies to all profiles of the user the
6211     * device owner or profile owner is an admin for. By default the user can use any input method.
6212     * When zero or more packages have been added, input method that are not in the list and not
6213     * part of the system can not be enabled by the user. This method will fail if it is called for
6214     * a admin that is not for the foreground user or a profile of the foreground user.
6215     * <p>
6216     * Calling with a null value for the list disables the restriction so that all input methods can
6217     * be used, calling with an empty list disables all but the system's own input methods.
6218     * <p>
6219     * System input methods are always available to the user this method can't modify this.
6220     *
6221     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6222     * @param packageNames List of input method package names.
6223     * @return true if setting the restriction succeeded. It will fail if there are one or more
6224     *         non-system input methods currently enabled that are not in the packageNames list.
6225     * @throws SecurityException if {@code admin} is not a device or profile owner.
6226     */
6227    public boolean setPermittedInputMethods(
6228            @NonNull ComponentName admin, List<String> packageNames) {
6229        throwIfParentInstance("setPermittedInputMethods");
6230        if (mService != null) {
6231            try {
6232                return mService.setPermittedInputMethods(admin, packageNames);
6233            } catch (RemoteException e) {
6234                throw e.rethrowFromSystemServer();
6235            }
6236        }
6237        return false;
6238    }
6239
6240
6241    /**
6242     * Returns the list of permitted input methods set by this device or profile owner.
6243     * <p>
6244     * An empty list means no input methods except system input methods are allowed. Null means all
6245     * input methods are allowed.
6246     *
6247     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6248     * @return List of input method package names.
6249     * @throws SecurityException if {@code admin} is not a device or profile owner.
6250     */
6251    public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
6252        throwIfParentInstance("getPermittedInputMethods");
6253        if (mService != null) {
6254            try {
6255                return mService.getPermittedInputMethods(admin);
6256            } catch (RemoteException e) {
6257                throw e.rethrowFromSystemServer();
6258            }
6259        }
6260        return null;
6261    }
6262
6263    /**
6264     * Called by the system to check if a specific input method is disabled by admin.
6265     *
6266     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6267     * @param packageName Input method package name that needs to be checked.
6268     * @param userHandle user id the admin is running as.
6269     * @return true if the input method is permitted, otherwise false.
6270     *
6271     * @hide
6272     */
6273    public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
6274            @NonNull String packageName, int userHandle) {
6275        if (mService != null) {
6276            try {
6277                return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
6278            } catch (RemoteException e) {
6279                throw e.rethrowFromSystemServer();
6280            }
6281        }
6282        return false;
6283    }
6284
6285    /**
6286     * Returns the list of input methods permitted by the device or profiles
6287     * owners of the current user.  (*Not* calling user, due to a limitation in InputMethodManager.)
6288     *
6289     * <p>Null means all input methods are allowed, if a non-null list is returned
6290     * it will contain the intersection of the permitted lists for any device or profile
6291     * owners that apply to this user. It will also include any system input methods.
6292     *
6293     * @return List of input method package names.
6294     * @hide
6295     */
6296    @SystemApi
6297    public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
6298        throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
6299        if (mService != null) {
6300            try {
6301                return mService.getPermittedInputMethodsForCurrentUser();
6302            } catch (RemoteException e) {
6303                throw e.rethrowFromSystemServer();
6304            }
6305        }
6306        return null;
6307    }
6308
6309    /**
6310     * Called by a profile owner of a managed profile to set the packages that are allowed to use
6311     * a {@link android.service.notification.NotificationListenerService} in the primary user to
6312     * see notifications from the managed profile. By default all packages are permitted by this
6313     * policy. When zero or more packages have been added, notification listeners installed on the
6314     * primary user that are not in the list and are not part of the system won't receive events
6315     * for managed profile notifications.
6316     * <p>
6317     * Calling with a {@code null} value for the list disables the restriction so that all
6318     * notification listener services be used. Calling with an empty list disables all but the
6319     * system's own notification listeners. System notification listener services are always
6320     * available to the user.
6321     * <p>
6322     * If a device or profile owner want to stop notification listeners in their user from seeing
6323     * that user's notifications they should prevent that service from running instead (e.g. via
6324     * {@link #setApplicationHidden(ComponentName, String, boolean)})
6325     *
6326     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6327     * @param packageList List of package names to whitelist
6328     * @return true if setting the restriction succeeded. It will fail if called outside a managed
6329     * profile
6330     * @throws SecurityException if {@code admin} is not a profile owner.
6331     *
6332     * @see android.service.notification.NotificationListenerService
6333     */
6334    public boolean setPermittedCrossProfileNotificationListeners(
6335            @NonNull ComponentName admin, @Nullable List<String> packageList) {
6336        throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
6337        if (mService != null) {
6338            try {
6339                return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
6340            } catch (RemoteException e) {
6341                throw e.rethrowFromSystemServer();
6342            }
6343        }
6344        return false;
6345    }
6346
6347    /**
6348     * Returns the list of packages installed on the primary user that allowed to use a
6349     * {@link android.service.notification.NotificationListenerService} to receive
6350     * notifications from this managed profile, as set by the profile owner.
6351     * <p>
6352     * An empty list means no notification listener services except system ones are allowed.
6353     * A {@code null} return value indicates that all notification listeners are allowed.
6354     */
6355    public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
6356            @NonNull ComponentName admin) {
6357        throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
6358        if (mService != null) {
6359            try {
6360                return mService.getPermittedCrossProfileNotificationListeners(admin);
6361            } catch (RemoteException e) {
6362                throw e.rethrowFromSystemServer();
6363            }
6364        }
6365        return null;
6366    }
6367
6368    /**
6369     * Returns true if {@code NotificationListenerServices} from the given package are allowed to
6370     * receive events for notifications from the given user id. Can only be called by the system uid
6371     *
6372     * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
6373     *
6374     * @hide
6375     */
6376    public boolean isNotificationListenerServicePermitted(
6377            @NonNull String packageName, @UserIdInt int userId) {
6378        if (mService != null) {
6379            try {
6380                return mService.isNotificationListenerServicePermitted(packageName, userId);
6381            } catch (RemoteException e) {
6382                throw e.rethrowFromSystemServer();
6383            }
6384        }
6385        return true;
6386    }
6387
6388    /**
6389     * Get the list of apps to keep around as APKs even if no user has currently installed it. This
6390     * function can be called by a device owner or by a delegate given the
6391     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
6392     * <p>
6393     * Please note that packages returned in this method are not automatically pre-cached.
6394     *
6395     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6396     *            {@code null} if the caller is a keep uninstalled packages delegate.
6397     * @return List of package names to keep cached.
6398     * @see #setDelegatedScopes
6399     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
6400     */
6401    public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
6402        throwIfParentInstance("getKeepUninstalledPackages");
6403        if (mService != null) {
6404            try {
6405                return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
6406            } catch (RemoteException e) {
6407                throw e.rethrowFromSystemServer();
6408            }
6409        }
6410        return null;
6411    }
6412
6413    /**
6414     * Set a list of apps to keep around as APKs even if no user has currently installed it. This
6415     * function can be called by a device owner or by a delegate given the
6416     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
6417     *
6418     * <p>Please note that setting this policy does not imply that specified apps will be
6419     * automatically pre-cached.</p>
6420     *
6421     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6422     *            {@code null} if the caller is a keep uninstalled packages delegate.
6423     * @param packageNames List of package names to keep cached.
6424     * @throws SecurityException if {@code admin} is not a device owner.
6425     * @see #setDelegatedScopes
6426     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
6427     */
6428    public void setKeepUninstalledPackages(@Nullable ComponentName admin,
6429            @NonNull List<String> packageNames) {
6430        throwIfParentInstance("setKeepUninstalledPackages");
6431        if (mService != null) {
6432            try {
6433                mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
6434            } catch (RemoteException e) {
6435                throw e.rethrowFromSystemServer();
6436            }
6437        }
6438    }
6439
6440    /**
6441     * Called by a device owner to create a user with the specified name. The UserHandle returned
6442     * by this method should not be persisted as user handles are recycled as users are removed and
6443     * created. If you need to persist an identifier for this user, use
6444     * {@link UserManager#getSerialNumberForUser}.
6445     *
6446     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6447     * @param name the user's name
6448     * @see UserHandle
6449     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6450     *         user could not be created.
6451     *
6452     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
6453     * @removed From {@link android.os.Build.VERSION_CODES#N}
6454     */
6455    @Deprecated
6456    public @Nullable UserHandle createUser(@NonNull ComponentName admin, String name) {
6457        return null;
6458    }
6459
6460    /**
6461     * Called by a device owner to create a user with the specified name. The UserHandle returned
6462     * by this method should not be persisted as user handles are recycled as users are removed and
6463     * created. If you need to persist an identifier for this user, use
6464     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
6465     * immediately.
6466     *
6467     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
6468     * as registered as an active admin on the new user.  The profile owner package will be
6469     * installed on the new user if it already is installed on the device.
6470     *
6471     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
6472     * profileOwnerComponent when onEnable is called.
6473     *
6474     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6475     * @param name the user's name
6476     * @param ownerName the human readable name of the organisation associated with this DPM.
6477     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
6478     *      the user.
6479     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
6480     *      on the new user.
6481     * @see UserHandle
6482     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6483     *         user could not be created.
6484     *
6485     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
6486     * @removed From {@link android.os.Build.VERSION_CODES#N}
6487     */
6488    @Deprecated
6489    public @Nullable UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
6490            String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
6491        return null;
6492    }
6493
6494    /**
6495      * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
6496      */
6497    public static final int SKIP_SETUP_WIZARD = 0x0001;
6498
6499    /**
6500     * Flag used by {@link #createAndManageUser} to specify that the user should be created
6501     * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
6502     * device.
6503     */
6504    public static final int MAKE_USER_EPHEMERAL = 0x0002;
6505
6506    /**
6507     * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
6508     * demo user.
6509     * @hide
6510     */
6511    public static final int MAKE_USER_DEMO = 0x0004;
6512
6513    /**
6514     * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
6515     * the disabling of system apps during provisioning.
6516     */
6517    public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
6518
6519    /**
6520     * @hide
6521     */
6522    @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
6523            SKIP_SETUP_WIZARD,
6524            MAKE_USER_EPHEMERAL,
6525            MAKE_USER_DEMO,
6526            LEAVE_ALL_SYSTEM_APPS_ENABLED
6527    })
6528    @Retention(RetentionPolicy.SOURCE)
6529    public @interface CreateAndManageUserFlags {}
6530
6531
6532    /**
6533     * Called by a device owner to create a user with the specified name and a given component of
6534     * the calling package as profile owner. The UserHandle returned by this method should not be
6535     * persisted as user handles are recycled as users are removed and created. If you need to
6536     * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
6537     * user will not be started in the background.
6538     * <p>
6539     * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
6540     * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
6541     * be registered as an active admin on the new user. The profile owner package will be installed
6542     * on the new user.
6543     * <p>
6544     * If the adminExtras are not null, they will be stored on the device until the user is started
6545     * for the first time. Then the extras will be passed to the admin when onEnable is called.
6546     *
6547     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6548     * @param name The user's name.
6549     * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
6550     *            same package as admin, otherwise no user is created and an
6551     *            IllegalArgumentException is thrown.
6552     * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
6553     *            user.
6554     * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
6555     *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
6556     * @see UserHandle
6557     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6558     *         user could not be created.
6559     * @throws SecurityException if {@code admin} is not a device owner.
6560     */
6561    public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
6562            @NonNull String name,
6563            @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
6564            @CreateAndManageUserFlags int flags) {
6565        throwIfParentInstance("createAndManageUser");
6566        try {
6567            return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
6568        } catch (RemoteException re) {
6569            throw re.rethrowFromSystemServer();
6570        }
6571    }
6572
6573    /**
6574     * Called by a device owner to remove a user/profile and all associated data. The primary user
6575     * can not be removed.
6576     *
6577     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6578     * @param userHandle the user to remove.
6579     * @return {@code true} if the user was removed, {@code false} otherwise.
6580     * @throws SecurityException if {@code admin} is not a device owner.
6581     */
6582    public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6583        throwIfParentInstance("removeUser");
6584        try {
6585            return mService.removeUser(admin, userHandle);
6586        } catch (RemoteException re) {
6587            throw re.rethrowFromSystemServer();
6588        }
6589    }
6590
6591    /**
6592     * Called by a device owner to switch the specified secondary user to the foreground.
6593     *
6594     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6595     * @param userHandle the user to switch to; null will switch to primary.
6596     * @return {@code true} if the switch was successful, {@code false} otherwise.
6597     * @throws SecurityException if {@code admin} is not a device owner.
6598     * @see Intent#ACTION_USER_FOREGROUND
6599     * @see #getSecondaryUsers(ComponentName)
6600     */
6601    public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
6602        throwIfParentInstance("switchUser");
6603        try {
6604            return mService.switchUser(admin, userHandle);
6605        } catch (RemoteException re) {
6606            throw re.rethrowFromSystemServer();
6607        }
6608    }
6609
6610    /**
6611     * Called by a device owner to start the specified secondary user in background.
6612     *
6613     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6614     * @param userHandle the user to be stopped.
6615     * @return {@code true} if the user can be started, {@code false} otherwise.
6616     * @throws SecurityException if {@code admin} is not a device owner.
6617     * @see #getSecondaryUsers(ComponentName)
6618     */
6619    public boolean startUserInBackground(
6620            @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6621        throwIfParentInstance("startUserInBackground");
6622        try {
6623            return mService.startUserInBackground(admin, userHandle);
6624        } catch (RemoteException re) {
6625            throw re.rethrowFromSystemServer();
6626        }
6627    }
6628
6629    /**
6630     * Called by a device owner to stop the specified secondary user.
6631     *
6632     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6633     * @param userHandle the user to be stopped.
6634     * @return {@code true} if the user can be stopped, {@code false} otherwise.
6635     * @throws SecurityException if {@code admin} is not a device owner.
6636     * @see #getSecondaryUsers(ComponentName)
6637     */
6638    public boolean stopUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6639        throwIfParentInstance("stopUser");
6640        try {
6641            return mService.stopUser(admin, userHandle);
6642        } catch (RemoteException re) {
6643            throw re.rethrowFromSystemServer();
6644        }
6645    }
6646
6647    /**
6648     * Called by a profile owner of secondary user that is affiliated with the device to stop the
6649     * calling user and switch back to primary.
6650     *
6651     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6652     * @return {@code true} if the exit was successful, {@code false} otherwise.
6653     * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
6654     * @see #getSecondaryUsers(ComponentName)
6655     */
6656    public boolean logoutUser(@NonNull ComponentName admin) {
6657        throwIfParentInstance("logoutUser");
6658        try {
6659            return mService.logoutUser(admin);
6660        } catch (RemoteException re) {
6661            throw re.rethrowFromSystemServer();
6662        }
6663    }
6664
6665    /**
6666     * Called by a device owner to list all secondary users on the device. Managed profiles are not
6667     * considered as secondary users.
6668     * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
6669     * and {@link #stopUser}.
6670     *
6671     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6672     * @return list of other {@link UserHandle}s on the device.
6673     * @throws SecurityException if {@code admin} is not a device owner.
6674     * @see #removeUser(ComponentName, UserHandle)
6675     * @see #switchUser(ComponentName, UserHandle)
6676     * @see #startUserInBackground(ComponentName, UserHandle)
6677     * @see #stopUser(ComponentName, UserHandle)
6678     */
6679    public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
6680        throwIfParentInstance("getSecondaryUsers");
6681        try {
6682            return mService.getSecondaryUsers(admin);
6683        } catch (RemoteException re) {
6684            throw re.rethrowFromSystemServer();
6685        }
6686    }
6687
6688    /**
6689     * Checks if the profile owner is running in an ephemeral user.
6690     *
6691     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6692     * @return whether the profile owner is running in an ephemeral user.
6693     */
6694    public boolean isEphemeralUser(@NonNull ComponentName admin) {
6695        throwIfParentInstance("isEphemeralUser");
6696        try {
6697            return mService.isEphemeralUser(admin);
6698        } catch (RemoteException re) {
6699            throw re.rethrowFromSystemServer();
6700        }
6701    }
6702
6703    /**
6704     * Retrieves the application restrictions for a given target application running in the calling
6705     * user.
6706     * <p>
6707     * The caller must be a profile or device owner on that user, or the package allowed to manage
6708     * application restrictions via {@link #setDelegatedScopes} with the
6709     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
6710     *
6711     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
6712     *
6713     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6714     *            {@code null} if called by the application restrictions managing package.
6715     * @param packageName The name of the package to fetch restricted settings of.
6716     * @return {@link Bundle} of settings corresponding to what was set last time
6717     *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
6718     *         {@link Bundle} if no restrictions have been set.
6719     * @throws SecurityException if {@code admin} is not a device or profile owner.
6720     * @see #setDelegatedScopes
6721     * @see #DELEGATION_APP_RESTRICTIONS
6722     */
6723    @WorkerThread
6724    public @NonNull Bundle getApplicationRestrictions(
6725            @Nullable ComponentName admin, String packageName) {
6726        throwIfParentInstance("getApplicationRestrictions");
6727        if (mService != null) {
6728            try {
6729                return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
6730                        packageName);
6731            } catch (RemoteException e) {
6732                throw e.rethrowFromSystemServer();
6733            }
6734        }
6735        return null;
6736    }
6737
6738    /**
6739     * Called by a profile or device owner to set a user restriction specified by the key.
6740     * <p>
6741     * The calling device admin must be a profile or device owner; if it is not, a security
6742     * exception will be thrown.
6743     *
6744     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6745     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6746     *            for the list of keys.
6747     * @throws SecurityException if {@code admin} is not a device or profile owner.
6748     */
6749    public void addUserRestriction(@NonNull ComponentName admin, String key) {
6750        throwIfParentInstance("addUserRestriction");
6751        if (mService != null) {
6752            try {
6753                mService.setUserRestriction(admin, key, true);
6754            } catch (RemoteException e) {
6755                throw e.rethrowFromSystemServer();
6756            }
6757        }
6758    }
6759
6760    /**
6761     * Called by a profile or device owner to clear a user restriction specified by the key.
6762     * <p>
6763     * The calling device admin must be a profile or device owner; if it is not, a security
6764     * exception will be thrown.
6765     *
6766     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6767     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6768     *            for the list of keys.
6769     * @throws SecurityException if {@code admin} is not a device or profile owner.
6770     */
6771    public void clearUserRestriction(@NonNull ComponentName admin, String key) {
6772        throwIfParentInstance("clearUserRestriction");
6773        if (mService != null) {
6774            try {
6775                mService.setUserRestriction(admin, key, false);
6776            } catch (RemoteException e) {
6777                throw e.rethrowFromSystemServer();
6778            }
6779        }
6780    }
6781
6782    /**
6783     * Called by a profile or device owner to get user restrictions set with
6784     * {@link #addUserRestriction(ComponentName, String)}.
6785     * <p>
6786     * The target user may have more restrictions set by the system or other device owner / profile
6787     * owner. To get all the user restrictions currently set, use
6788     * {@link UserManager#getUserRestrictions()}.
6789     *
6790     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6791     * @throws SecurityException if {@code admin} is not a device or profile owner.
6792     */
6793    public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
6794        throwIfParentInstance("getUserRestrictions");
6795        Bundle ret = null;
6796        if (mService != null) {
6797            try {
6798                ret = mService.getUserRestrictions(admin);
6799            } catch (RemoteException e) {
6800                throw e.rethrowFromSystemServer();
6801            }
6802        }
6803        return ret == null ? new Bundle() : ret;
6804    }
6805
6806    /**
6807     * Called by any app to display a support dialog when a feature was disabled by an admin.
6808     * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
6809     * display the dialog. It will tell the user that the feature indicated by {@code restriction}
6810     * was disabled by an admin, and include a link for more information. The default content of
6811     * the dialog can be changed by the restricting admin via
6812     * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
6813     * set (i.e. the feature is available), then the return value will be {@code null}.
6814     * @param restriction Indicates for which feature the dialog should be displayed. Can be a
6815     *            user restriction from {@link UserManager}, e.g.
6816     *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
6817     *            {@link #POLICY_DISABLE_CAMERA}, {@link #POLICY_DISABLE_SCREEN_CAPTURE} or
6818     *            {@link #POLICY_MANDATORY_BACKUPS}.
6819     * @return Intent An intent to be used to start the dialog-activity if the restriction is
6820     *            set by an admin, or null if the restriction does not exist or no admin set it.
6821     */
6822    public Intent createAdminSupportIntent(@NonNull String restriction) {
6823        throwIfParentInstance("createAdminSupportIntent");
6824        if (mService != null) {
6825            try {
6826                return mService.createAdminSupportIntent(restriction);
6827            } catch (RemoteException e) {
6828                throw e.rethrowFromSystemServer();
6829            }
6830        }
6831        return null;
6832    }
6833
6834    /**
6835     * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
6836     * actual package file remain. This function can be called by a device owner, profile owner, or
6837     * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6838     * {@link #setDelegatedScopes}.
6839     *
6840     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6841     *            {@code null} if the caller is a package access delegate.
6842     * @param packageName The name of the package to hide or unhide.
6843     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
6844     *            unhidden.
6845     * @return boolean Whether the hidden setting of the package was successfully updated.
6846     * @throws SecurityException if {@code admin} is not a device or profile owner.
6847     * @see #setDelegatedScopes
6848     * @see #DELEGATION_PACKAGE_ACCESS
6849     */
6850    public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
6851            boolean hidden) {
6852        throwIfParentInstance("setApplicationHidden");
6853        if (mService != null) {
6854            try {
6855                return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
6856                        hidden);
6857            } catch (RemoteException e) {
6858                throw e.rethrowFromSystemServer();
6859            }
6860        }
6861        return false;
6862    }
6863
6864    /**
6865     * Determine if a package is hidden. This function can be called by a device owner, profile
6866     * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6867     * {@link #setDelegatedScopes}.
6868     *
6869     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6870     *            {@code null} if the caller is a package access delegate.
6871     * @param packageName The name of the package to retrieve the hidden status of.
6872     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
6873     * @throws SecurityException if {@code admin} is not a device or profile owner.
6874     * @see #setDelegatedScopes
6875     * @see #DELEGATION_PACKAGE_ACCESS
6876     */
6877    public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
6878        throwIfParentInstance("isApplicationHidden");
6879        if (mService != null) {
6880            try {
6881                return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName);
6882            } catch (RemoteException e) {
6883                throw e.rethrowFromSystemServer();
6884            }
6885        }
6886        return false;
6887    }
6888
6889    /**
6890     * Re-enable a system app that was disabled by default when the user was initialized. This
6891     * function can be called by a device owner, profile owner, or by a delegate given the
6892     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6893     *
6894     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6895     *            {@code null} if the caller is an enable system app delegate.
6896     * @param packageName The package to be re-enabled in the calling profile.
6897     * @throws SecurityException if {@code admin} is not a device or profile owner.
6898     * @see #setDelegatedScopes
6899     * @see #DELEGATION_PACKAGE_ACCESS
6900     */
6901    public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
6902        throwIfParentInstance("enableSystemApp");
6903        if (mService != null) {
6904            try {
6905                mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
6906            } catch (RemoteException e) {
6907                throw e.rethrowFromSystemServer();
6908            }
6909        }
6910    }
6911
6912    /**
6913     * Re-enable system apps by intent that were disabled by default when the user was initialized.
6914     * This function can be called by a device owner, profile owner, or by a delegate given the
6915     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6916     *
6917     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6918     *            {@code null} if the caller is an enable system app delegate.
6919     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
6920     *            intent will be re-enabled in the calling profile.
6921     * @return int The number of activities that matched the intent and were installed.
6922     * @throws SecurityException if {@code admin} is not a device or profile owner.
6923     * @see #setDelegatedScopes
6924     * @see #DELEGATION_PACKAGE_ACCESS
6925     */
6926    public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
6927        throwIfParentInstance("enableSystemApp");
6928        if (mService != null) {
6929            try {
6930                return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
6931            } catch (RemoteException e) {
6932                throw e.rethrowFromSystemServer();
6933            }
6934        }
6935        return 0;
6936    }
6937
6938    /**
6939     * Install an existing package that has been installed in another user, or has been kept after
6940     * removal via {@link #setKeepUninstalledPackages}.
6941     * This function can be called by a device owner, profile owner or a delegate given
6942     * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
6943     * When called in a secondary user or managed profile, the user/profile must be affiliated with
6944     * the device. See {@link #isAffiliatedUser}.
6945     *
6946     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6947     * @param packageName The package to be installed in the calling profile.
6948     * @return {@code true} if the app is installed; {@code false} otherwise.
6949     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
6950     * an affiliated user or profile.
6951     * @see #setKeepUninstalledPackages
6952     * @see #setDelegatedScopes
6953     * @see #isAffiliatedUser
6954     * @see #DELEGATION_PACKAGE_ACCESS
6955     */
6956    public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
6957        throwIfParentInstance("installExistingPackage");
6958        if (mService != null) {
6959            try {
6960                return mService.installExistingPackage(admin, mContext.getPackageName(),
6961                        packageName);
6962            } catch (RemoteException e) {
6963                throw e.rethrowFromSystemServer();
6964            }
6965        }
6966        return false;
6967    }
6968
6969    /**
6970     * Called by a device owner or profile owner to disable account management for a specific type
6971     * of account.
6972     * <p>
6973     * The calling device admin must be a device owner or profile owner. If it is not, a security
6974     * exception will be thrown.
6975     * <p>
6976     * When account management is disabled for an account type, adding or removing an account of
6977     * that type will not be possible.
6978     * <p>
6979     * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
6980     * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
6981     * management for a specific type is disabled.
6982     *
6983     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6984     * @param accountType For which account management is disabled or enabled.
6985     * @param disabled The boolean indicating that account management will be disabled (true) or
6986     *            enabled (false).
6987     * @throws SecurityException if {@code admin} is not a device or profile owner.
6988     */
6989    public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
6990            boolean disabled) {
6991        throwIfParentInstance("setAccountManagementDisabled");
6992        if (mService != null) {
6993            try {
6994                mService.setAccountManagementDisabled(admin, accountType, disabled);
6995            } catch (RemoteException e) {
6996                throw e.rethrowFromSystemServer();
6997            }
6998        }
6999    }
7000
7001    /**
7002     * Gets the array of accounts for which account management is disabled by the profile owner.
7003     *
7004     * <p> Account management can be disabled/enabled by calling
7005     * {@link #setAccountManagementDisabled}.
7006     *
7007     * @return a list of account types for which account management has been disabled.
7008     *
7009     * @see #setAccountManagementDisabled
7010     */
7011    public @Nullable String[] getAccountTypesWithManagementDisabled() {
7012        throwIfParentInstance("getAccountTypesWithManagementDisabled");
7013        return getAccountTypesWithManagementDisabledAsUser(myUserId());
7014    }
7015
7016    /**
7017     * @see #getAccountTypesWithManagementDisabled()
7018     * @hide
7019     */
7020    public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7021        if (mService != null) {
7022            try {
7023                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
7024            } catch (RemoteException e) {
7025                throw e.rethrowFromSystemServer();
7026            }
7027        }
7028
7029        return null;
7030    }
7031
7032    /**
7033     * Sets which packages may enter lock task mode.
7034     * <p>
7035     * Any packages that share uid with an allowed package will also be allowed to activate lock
7036     * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
7037     * package list results in locked tasks belonging to those packages to be finished.
7038     * <p>
7039     * This function can only be called by the device owner, a profile owner of an affiliated user
7040     * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
7041     * Any package set via this method will be cleared if the user becomes unaffiliated.
7042     *
7043     * @param packages The list of packages allowed to enter lock task mode
7044     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7045     * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7046     * affiliated user or profile, or the profile owner when no device owner is set.
7047     * @see #isAffiliatedUser
7048     * @see Activity#startLockTask()
7049     * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
7050     * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
7051     * @see UserManager#DISALLOW_CREATE_WINDOWS
7052     */
7053    public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
7054            throws SecurityException {
7055        throwIfParentInstance("setLockTaskPackages");
7056        if (mService != null) {
7057            try {
7058                mService.setLockTaskPackages(admin, packages);
7059            } catch (RemoteException e) {
7060                throw e.rethrowFromSystemServer();
7061            }
7062        }
7063    }
7064
7065    /**
7066     * Returns the list of packages allowed to start the lock task mode.
7067     *
7068     * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7069     * affiliated user or profile, or the profile owner when no device owner is set.
7070     * @see #isAffiliatedUser
7071     * @see #setLockTaskPackages
7072     */
7073    public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
7074        throwIfParentInstance("getLockTaskPackages");
7075        if (mService != null) {
7076            try {
7077                return mService.getLockTaskPackages(admin);
7078            } catch (RemoteException e) {
7079                throw e.rethrowFromSystemServer();
7080            }
7081        }
7082        return new String[0];
7083    }
7084
7085    /**
7086     * This function lets the caller know whether the given component is allowed to start the
7087     * lock task mode.
7088     * @param pkg The package to check
7089     */
7090    public boolean isLockTaskPermitted(String pkg) {
7091        throwIfParentInstance("isLockTaskPermitted");
7092        if (mService != null) {
7093            try {
7094                return mService.isLockTaskPermitted(pkg);
7095            } catch (RemoteException e) {
7096                throw e.rethrowFromSystemServer();
7097            }
7098        }
7099        return false;
7100    }
7101
7102    /**
7103     * Sets which system features to enable for LockTask mode.
7104     * <p>
7105     * Feature flags set through this method will only take effect for the duration when the device
7106     * is in LockTask mode. If this method is not called, none of the features listed here will be
7107     * enabled.
7108     * <p>
7109     * This function can only be called by the device owner, a profile owner of an affiliated user
7110     * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
7111     * Any features set via this method will be cleared if the user becomes unaffiliated.
7112     *
7113     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7114     * @param flags Bitfield of feature flags:
7115     *              {@link #LOCK_TASK_FEATURE_NONE} (default),
7116     *              {@link #LOCK_TASK_FEATURE_SYSTEM_INFO},
7117     *              {@link #LOCK_TASK_FEATURE_NOTIFICATIONS},
7118     *              {@link #LOCK_TASK_FEATURE_HOME},
7119     *              {@link #LOCK_TASK_FEATURE_RECENTS},
7120     *              {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS},
7121     *              {@link #LOCK_TASK_FEATURE_KEYGUARD}
7122     * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7123     * affiliated user or profile, or the profile owner when no device owner is set.
7124     * @see #isAffiliatedUser
7125     * @throws SecurityException if {@code admin} is not the device owner or the profile owner.
7126     */
7127    public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
7128        throwIfParentInstance("setLockTaskFeatures");
7129        if (mService != null) {
7130            try {
7131                mService.setLockTaskFeatures(admin, flags);
7132            } catch (RemoteException e) {
7133                throw e.rethrowFromSystemServer();
7134            }
7135        }
7136    }
7137
7138    /**
7139     * Gets which system features are enabled for LockTask mode.
7140     *
7141     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7142     * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
7143     * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
7144     * affiliated user or profile, or the profile owner when no device owner is set.
7145     * @see #isAffiliatedUser
7146     * @see #setLockTaskFeatures
7147     */
7148    public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
7149        throwIfParentInstance("getLockTaskFeatures");
7150        if (mService != null) {
7151            try {
7152                return mService.getLockTaskFeatures(admin);
7153            } catch (RemoteException e) {
7154                throw e.rethrowFromSystemServer();
7155            }
7156        }
7157        return 0;
7158    }
7159
7160    /**
7161     * Called by device owner to update {@link android.provider.Settings.Global} settings.
7162     * Validation that the value of the setting is in the correct form for the setting type should
7163     * be performed by the caller.
7164     * <p>
7165     * The settings that can be updated with this method are:
7166     * <ul>
7167     * <li>{@link android.provider.Settings.Global#ADB_ENABLED}</li>
7168     * <li>{@link android.provider.Settings.Global#AUTO_TIME}</li>
7169     * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE}</li>
7170     * <li>{@link android.provider.Settings.Global#DATA_ROAMING}</li>
7171     * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
7172     * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}</li>
7173     * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
7174     * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
7175     * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
7176     * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
7177     * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
7178     * </ul>
7179     * <p>
7180     * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
7181     * <ul>
7182     * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
7183     * {@link android.bluetooth.BluetoothAdapter#enable()} and
7184     * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
7185     * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
7186     * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
7187     * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
7188     * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
7189     * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
7190     * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
7191     * </ul>
7192     *
7193     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7194     * @param setting The name of the setting to update.
7195     * @param value The value to update the setting to.
7196     * @throws SecurityException if {@code admin} is not a device owner.
7197     */
7198    public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
7199        throwIfParentInstance("setGlobalSetting");
7200        if (mService != null) {
7201            try {
7202                mService.setGlobalSetting(admin, setting, value);
7203            } catch (RemoteException e) {
7204                throw e.rethrowFromSystemServer();
7205            }
7206        }
7207    }
7208
7209    /**
7210     * Called by device owner to update {@link android.provider.Settings.System} settings.
7211     * Validation that the value of the setting is in the correct form for the setting type should
7212     * be performed by the caller.
7213     * <p>
7214     * The settings that can be updated with this method are:
7215     * <ul>
7216     * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
7217     * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
7218     * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
7219     * </ul>
7220     * <p>
7221     *
7222     * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
7223     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7224     * @param setting The name of the setting to update.
7225     * @param value The value to update the setting to.
7226     * @throws SecurityException if {@code admin} is not a device owner.
7227     */
7228    public void setSystemSetting(@NonNull ComponentName admin, @NonNull String setting,
7229            String value) {
7230        throwIfParentInstance("setSystemSetting");
7231        if (mService != null) {
7232            try {
7233                mService.setSystemSetting(admin, setting, value);
7234            } catch (RemoteException e) {
7235                throw e.rethrowFromSystemServer();
7236            }
7237        }
7238    }
7239
7240    /**
7241     * Called by device owner to set the system wall clock time. This only takes effect if called
7242     * when {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false} will be
7243     * returned.
7244     *
7245     * @param admin Which {@link DeviceAdminReceiver} this request is associated with
7246     * @param millis time in milliseconds since the Epoch
7247     * @return {@code true} if set time succeeded, {@code false} otherwise.
7248     * @throws SecurityException if {@code admin} is not a device owner.
7249     */
7250    public boolean setTime(@NonNull ComponentName admin, long millis) {
7251        throwIfParentInstance("setTime");
7252        if (mService != null) {
7253            try {
7254                return mService.setTime(admin, millis);
7255            } catch (RemoteException e) {
7256                throw e.rethrowFromSystemServer();
7257            }
7258        }
7259        return false;
7260    }
7261
7262    /**
7263     * Called by device owner to set the system's persistent default time zone. This only takes
7264     * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE} is 0, otherwise
7265     * {@code false} will be returned.
7266     *
7267     * @see android.app.AlarmManager#setTimeZone(String)
7268     * @param admin Which {@link DeviceAdminReceiver} this request is associated with
7269     * @param timeZone one of the Olson ids from the list returned by
7270     *     {@link java.util.TimeZone#getAvailableIDs}
7271     * @return {@code true} if set timezone succeeded, {@code false} otherwise.
7272     * @throws SecurityException if {@code admin} is not a device owner.
7273     */
7274    public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
7275        throwIfParentInstance("setTimeZone");
7276        if (mService != null) {
7277            try {
7278                return mService.setTimeZone(admin, timeZone);
7279            } catch (RemoteException e) {
7280                throw e.rethrowFromSystemServer();
7281            }
7282        }
7283        return false;
7284    }
7285
7286    /**
7287     * Called by profile or device owners to update {@link android.provider.Settings.Secure}
7288     * settings. Validation that the value of the setting is in the correct form for the setting
7289     * type should be performed by the caller.
7290     * <p>
7291     * The settings that can be updated by a profile or device owner with this method are:
7292     * <ul>
7293     * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
7294     * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
7295     * </ul>
7296     * <p>
7297     * A device owner can additionally update the following settings:
7298     * <ul>
7299     * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}</li>
7300     * </ul>
7301     *
7302     * <strong>Note: Starting from Android O, apps should no longer call this method with the
7303     * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
7304     * deprecated. Instead, device owners or profile owners should use the restriction
7305     * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
7306     * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
7307     * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
7308     * an {@link UnsupportedOperationException} is thrown.
7309     * </strong>
7310     *
7311     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7312     * @param setting The name of the setting to update.
7313     * @param value The value to update the setting to.
7314     * @throws SecurityException if {@code admin} is not a device or profile owner.
7315     */
7316    public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
7317        throwIfParentInstance("setSecureSetting");
7318        if (mService != null) {
7319            try {
7320                mService.setSecureSetting(admin, setting, value);
7321            } catch (RemoteException e) {
7322                throw e.rethrowFromSystemServer();
7323            }
7324        }
7325    }
7326
7327    /**
7328     * Designates a specific service component as the provider for making permission requests of a
7329     * local or remote administrator of the user.
7330     * <p/>
7331     * Only a profile owner can designate the restrictions provider.
7332     *
7333     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7334     * @param provider The component name of the service that implements
7335     *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
7336     *            provider previously assigned.
7337     * @throws SecurityException if {@code admin} is not a device or profile owner.
7338     */
7339    public void setRestrictionsProvider(@NonNull ComponentName admin,
7340            @Nullable ComponentName provider) {
7341        throwIfParentInstance("setRestrictionsProvider");
7342        if (mService != null) {
7343            try {
7344                mService.setRestrictionsProvider(admin, provider);
7345            } catch (RemoteException re) {
7346                throw re.rethrowFromSystemServer();
7347            }
7348        }
7349    }
7350
7351    /**
7352     * Called by profile or device owners to set the master volume mute on or off.
7353     * This has no effect when set on a managed profile.
7354     *
7355     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7356     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
7357     * @throws SecurityException if {@code admin} is not a device or profile owner.
7358     */
7359    public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
7360        throwIfParentInstance("setMasterVolumeMuted");
7361        if (mService != null) {
7362            try {
7363                mService.setMasterVolumeMuted(admin, on);
7364            } catch (RemoteException re) {
7365                throw re.rethrowFromSystemServer();
7366            }
7367        }
7368    }
7369
7370    /**
7371     * Called by profile or device owners to check whether the master volume mute is on or off.
7372     *
7373     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7374     * @return {@code true} if master volume is muted, {@code false} if it's not.
7375     * @throws SecurityException if {@code admin} is not a device or profile owner.
7376     */
7377    public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
7378        throwIfParentInstance("isMasterVolumeMuted");
7379        if (mService != null) {
7380            try {
7381                return mService.isMasterVolumeMuted(admin);
7382            } catch (RemoteException re) {
7383                throw re.rethrowFromSystemServer();
7384            }
7385        }
7386        return false;
7387    }
7388
7389    /**
7390     * Change whether a user can uninstall a package. This function can be called by a device owner,
7391     * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
7392     * {@link #setDelegatedScopes}.
7393     *
7394     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7395     *             {@code null} if the caller is a block uninstall delegate.
7396     * @param packageName package to change.
7397     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
7398     * @throws SecurityException if {@code admin} is not a device or profile owner.
7399     * @see #setDelegatedScopes
7400     * @see #DELEGATION_BLOCK_UNINSTALL
7401     */
7402    public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
7403            boolean uninstallBlocked) {
7404        throwIfParentInstance("setUninstallBlocked");
7405        if (mService != null) {
7406            try {
7407                mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
7408                    uninstallBlocked);
7409            } catch (RemoteException re) {
7410                throw re.rethrowFromSystemServer();
7411            }
7412        }
7413    }
7414
7415    /**
7416     * Check whether the user has been blocked by device policy from uninstalling a package.
7417     * Requires the caller to be the profile owner if checking a specific admin's policy.
7418     * <p>
7419     * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
7420     * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
7421     * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
7422     * will cause a NullPointerException to be raised.
7423     *
7424     * @param admin The name of the admin component whose blocking policy will be checked, or
7425     *            {@code null} to check whether any admin has blocked the uninstallation.
7426     * @param packageName package to check.
7427     * @return true if uninstallation is blocked.
7428     * @throws SecurityException if {@code admin} is not a device or profile owner.
7429     */
7430    public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
7431        throwIfParentInstance("isUninstallBlocked");
7432        if (mService != null) {
7433            try {
7434                return mService.isUninstallBlocked(admin, packageName);
7435            } catch (RemoteException re) {
7436                throw re.rethrowFromSystemServer();
7437            }
7438        }
7439        return false;
7440    }
7441
7442    /**
7443     * Called by the profile owner of a managed profile to enable widget providers from a given
7444     * package to be available in the parent profile. As a result the user will be able to add
7445     * widgets from the white-listed package running under the profile to a widget host which runs
7446     * under the parent profile, for example the home screen. Note that a package may have zero or
7447     * more provider components, where each component provides a different widget type.
7448     * <p>
7449     * <strong>Note:</strong> By default no widget provider package is white-listed.
7450     *
7451     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7452     * @param packageName The package from which widget providers are white-listed.
7453     * @return Whether the package was added.
7454     * @throws SecurityException if {@code admin} is not a profile owner.
7455     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
7456     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
7457     */
7458    public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
7459        throwIfParentInstance("addCrossProfileWidgetProvider");
7460        if (mService != null) {
7461            try {
7462                return mService.addCrossProfileWidgetProvider(admin, packageName);
7463            } catch (RemoteException re) {
7464                throw re.rethrowFromSystemServer();
7465            }
7466        }
7467        return false;
7468    }
7469
7470    /**
7471     * Called by the profile owner of a managed profile to disable widget providers from a given
7472     * package to be available in the parent profile. For this method to take effect the package
7473     * should have been added via
7474     * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
7475     * <p>
7476     * <strong>Note:</strong> By default no widget provider package is white-listed.
7477     *
7478     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7479     * @param packageName The package from which widget providers are no longer white-listed.
7480     * @return Whether the package was removed.
7481     * @throws SecurityException if {@code admin} is not a profile owner.
7482     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
7483     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
7484     */
7485    public boolean removeCrossProfileWidgetProvider(
7486            @NonNull ComponentName admin, String packageName) {
7487        throwIfParentInstance("removeCrossProfileWidgetProvider");
7488        if (mService != null) {
7489            try {
7490                return mService.removeCrossProfileWidgetProvider(admin, packageName);
7491            } catch (RemoteException re) {
7492                throw re.rethrowFromSystemServer();
7493            }
7494        }
7495        return false;
7496    }
7497
7498    /**
7499     * Called by the profile owner of a managed profile to query providers from which packages are
7500     * available in the parent profile.
7501     *
7502     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7503     * @return The white-listed package list.
7504     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
7505     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
7506     * @throws SecurityException if {@code admin} is not a profile owner.
7507     */
7508    public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
7509        throwIfParentInstance("getCrossProfileWidgetProviders");
7510        if (mService != null) {
7511            try {
7512                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
7513                if (providers != null) {
7514                    return providers;
7515                }
7516            } catch (RemoteException re) {
7517                throw re.rethrowFromSystemServer();
7518            }
7519        }
7520        return Collections.emptyList();
7521    }
7522
7523    /**
7524     * Called by profile or device owners to set the user's photo.
7525     *
7526     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7527     * @param icon the bitmap to set as the photo.
7528     * @throws SecurityException if {@code admin} is not a device or profile owner.
7529     */
7530    public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
7531        throwIfParentInstance("setUserIcon");
7532        try {
7533            mService.setUserIcon(admin, icon);
7534        } catch (RemoteException re) {
7535            throw re.rethrowFromSystemServer();
7536        }
7537    }
7538
7539    /**
7540     * Called by device owners to set a local system update policy. When a new policy is set,
7541     * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
7542     *
7543     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
7544     *            components in the device owner package can set system update policies and the most
7545     *            recent policy takes effect.
7546     * @param policy the new policy, or {@code null} to clear the current policy.
7547     * @throws SecurityException if {@code admin} is not a device owner.
7548     * @see SystemUpdatePolicy
7549     */
7550    public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
7551        throwIfParentInstance("setSystemUpdatePolicy");
7552        if (mService != null) {
7553            try {
7554                mService.setSystemUpdatePolicy(admin, policy);
7555            } catch (RemoteException re) {
7556                throw re.rethrowFromSystemServer();
7557            }
7558        }
7559    }
7560
7561    /**
7562     * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
7563     *
7564     * @return The current policy object, or {@code null} if no policy is set.
7565     */
7566    public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
7567        throwIfParentInstance("getSystemUpdatePolicy");
7568        if (mService != null) {
7569            try {
7570                return mService.getSystemUpdatePolicy();
7571            } catch (RemoteException re) {
7572                throw re.rethrowFromSystemServer();
7573            }
7574        }
7575        return null;
7576    }
7577
7578    /**
7579     * Called by a device owner or profile owner of secondary users that is affiliated with the
7580     * device to disable the keyguard altogether.
7581     * <p>
7582     * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
7583     * type. However, this call has no effect if a password, pin or pattern is currently set. If a
7584     * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
7585     * disabled.
7586     *
7587     * <p>
7588     * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
7589     * keyguard if it is currently shown.
7590     *
7591     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7592     * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
7593     * @return {@code false} if attempting to disable the keyguard while a lock password was in
7594     *         place. {@code true} otherwise.
7595     * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
7596     * secondary user that is affiliated with the device.
7597     * @see #isAffiliatedUser
7598     * @see #getSecondaryUsers
7599     */
7600    public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
7601        throwIfParentInstance("setKeyguardDisabled");
7602        try {
7603            return mService.setKeyguardDisabled(admin, disabled);
7604        } catch (RemoteException re) {
7605            throw re.rethrowFromSystemServer();
7606        }
7607    }
7608
7609    /**
7610     * Called by device owner or profile owner of secondary users  that is affiliated with the
7611     * device to disable the status bar. Disabling the status bar blocks notifications, quick
7612     * settings and other screen overlays that allow escaping from a single use device.
7613     * <p>
7614     * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
7615     * status bar in LockTask mode can be configured with
7616     * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
7617     * LockTask mode will be registered, but will only take effect when the device leaves LockTask
7618     * mode.
7619     *
7620     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7621     * @param disabled {@code true} disables the status bar, {@code false} reenables it.
7622     * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
7623     * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
7624     * secondary user that is affiliated with the device.
7625     * @see #isAffiliatedUser
7626     * @see #getSecondaryUsers
7627     */
7628    public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
7629        throwIfParentInstance("setStatusBarDisabled");
7630        try {
7631            return mService.setStatusBarDisabled(admin, disabled);
7632        } catch (RemoteException re) {
7633            throw re.rethrowFromSystemServer();
7634        }
7635    }
7636
7637    /**
7638     * Called by the system update service to notify device and profile owners of pending system
7639     * updates.
7640     *
7641     * This method should only be used when it is unknown whether the pending system
7642     * update is a security patch. Otherwise, use
7643     * {@link #notifyPendingSystemUpdate(long, boolean)}.
7644     *
7645     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
7646     *         indicating when the current pending update was first available. {@code -1} if no
7647     *         update is available.
7648     * @see #notifyPendingSystemUpdate(long, boolean)
7649     * @hide
7650     */
7651    @SystemApi
7652    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
7653    public void notifyPendingSystemUpdate(long updateReceivedTime) {
7654        throwIfParentInstance("notifyPendingSystemUpdate");
7655        if (mService != null) {
7656            try {
7657                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
7658            } catch (RemoteException re) {
7659                throw re.rethrowFromSystemServer();
7660            }
7661        }
7662    }
7663
7664    /**
7665     * Called by the system update service to notify device and profile owners of pending system
7666     * updates.
7667     *
7668     * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
7669     * when it is known whether the pending system update is a security patch.
7670     *
7671     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
7672     *         indicating when the current pending update was first available. {@code -1} if no
7673     *         update is available.
7674     * @param isSecurityPatch {@code true} if this system update is purely a security patch;
7675     *         {@code false} if not.
7676     * @see #notifyPendingSystemUpdate(long)
7677     * @hide
7678     */
7679    @SystemApi
7680    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
7681    public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
7682        throwIfParentInstance("notifyPendingSystemUpdate");
7683        if (mService != null) {
7684            try {
7685                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
7686                        isSecurityPatch));
7687            } catch (RemoteException re) {
7688                throw re.rethrowFromSystemServer();
7689            }
7690        }
7691    }
7692
7693    /**
7694     * Called by device or profile owners to get information about a pending system update.
7695     *
7696     * @param admin Which profile or device owner this request is associated with.
7697     * @return Information about a pending system update or {@code null} if no update pending.
7698     * @throws SecurityException if {@code admin} is not a device or profile owner.
7699     * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
7700     */
7701    public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
7702        throwIfParentInstance("getPendingSystemUpdate");
7703        try {
7704            return mService.getPendingSystemUpdate(admin);
7705        } catch (RemoteException re) {
7706            throw re.rethrowFromSystemServer();
7707        }
7708    }
7709
7710    /**
7711     * Set the default response for future runtime permission requests by applications. This
7712     * function can be called by a device owner, profile owner, or by a delegate given the
7713     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7714     * The policy can allow for normal operation which prompts the user to grant a permission, or
7715     * can allow automatic granting or denying of runtime permission requests by an application.
7716     * This also applies to new permissions declared by app updates. When a permission is denied or
7717     * granted this way, the effect is equivalent to setting the permission * grant state via
7718     * {@link #setPermissionGrantState}.
7719     * <p/>
7720     * As this policy only acts on runtime permission requests, it only applies to applications
7721     * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
7722     *
7723     * @param admin Which profile or device owner this request is associated with.
7724     * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
7725     *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
7726     * @throws SecurityException if {@code admin} is not a device or profile owner.
7727     * @see #setPermissionGrantState
7728     * @see #setDelegatedScopes
7729     * @see #DELEGATION_PERMISSION_GRANT
7730     */
7731    public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
7732        throwIfParentInstance("setPermissionPolicy");
7733        try {
7734            mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
7735        } catch (RemoteException re) {
7736            throw re.rethrowFromSystemServer();
7737        }
7738    }
7739
7740    /**
7741     * Returns the current runtime permission policy set by the device or profile owner. The
7742     * default is {@link #PERMISSION_POLICY_PROMPT}.
7743     *
7744     * @param admin Which profile or device owner this request is associated with.
7745     * @return the current policy for future permission requests.
7746     */
7747    public int getPermissionPolicy(ComponentName admin) {
7748        throwIfParentInstance("getPermissionPolicy");
7749        try {
7750            return mService.getPermissionPolicy(admin);
7751        } catch (RemoteException re) {
7752            throw re.rethrowFromSystemServer();
7753        }
7754    }
7755
7756    /**
7757     * Sets the grant state of a runtime permission for a specific application. The state can be
7758     * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
7759     * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
7760     * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
7761     * the permission is granted and the user cannot manage it through the UI. This might affect all
7762     * permissions in a group that the runtime permission belongs to. This method can only be called
7763     * by a profile owner, device owner, or a delegate given the
7764     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7765     * <p/>
7766     * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
7767     * the permission. It retains the previous grant, if any.
7768     * <p/>
7769     * Permissions can be granted or revoked only for applications built with a
7770     * {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
7771     *
7772     * @param admin Which profile or device owner this request is associated with.
7773     * @param packageName The application to grant or revoke a permission to.
7774     * @param permission The permission to grant or revoke.
7775     * @param grantState The permission grant state which is one of
7776     *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
7777     *            {@link #PERMISSION_GRANT_STATE_GRANTED},
7778     * @return whether the permission was successfully granted or revoked.
7779     * @throws SecurityException if {@code admin} is not a device or profile owner.
7780     * @see #PERMISSION_GRANT_STATE_DENIED
7781     * @see #PERMISSION_GRANT_STATE_DEFAULT
7782     * @see #PERMISSION_GRANT_STATE_GRANTED
7783     * @see #setDelegatedScopes
7784     * @see #DELEGATION_PERMISSION_GRANT
7785     */
7786    public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName,
7787            String permission, int grantState) {
7788        throwIfParentInstance("setPermissionGrantState");
7789        try {
7790            return mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
7791                    permission, grantState);
7792        } catch (RemoteException re) {
7793            throw re.rethrowFromSystemServer();
7794        }
7795    }
7796
7797    /**
7798     * Returns the current grant state of a runtime permission for a specific application. This
7799     * function can be called by a device owner, profile owner, or by a delegate given the
7800     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7801     *
7802     * @param admin Which profile or device owner this request is associated with, or {@code null}
7803     *            if the caller is a permission grant delegate.
7804     * @param packageName The application to check the grant state for.
7805     * @param permission The permission to check for.
7806     * @return the current grant state specified by device policy. If the profile or device owner
7807     *         has not set a grant state, the return value is
7808     *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
7809     *         permission is currently granted for the package.
7810     *         <p/>
7811     *         If a grant state was set by the profile or device owner, then the return value will
7812     *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
7813     *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
7814     *         currently denied or granted.
7815     * @throws SecurityException if {@code admin} is not a device or profile owner.
7816     * @see #setPermissionGrantState(ComponentName, String, String, int)
7817     * @see PackageManager#checkPermission(String, String)
7818     * @see #setDelegatedScopes
7819     * @see #DELEGATION_PERMISSION_GRANT
7820     */
7821    public int getPermissionGrantState(@Nullable ComponentName admin, String packageName,
7822            String permission) {
7823        throwIfParentInstance("getPermissionGrantState");
7824        try {
7825            return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
7826                    permission);
7827        } catch (RemoteException re) {
7828            throw re.rethrowFromSystemServer();
7829        }
7830    }
7831
7832    /**
7833     * Returns whether it is possible for the caller to initiate provisioning of a managed profile
7834     * or device, setting itself as the device or profile owner.
7835     *
7836     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7837     * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
7838     * @return whether provisioning a managed profile or device is possible.
7839     * @throws IllegalArgumentException if the supplied action is not valid.
7840     */
7841    public boolean isProvisioningAllowed(@NonNull String action) {
7842        throwIfParentInstance("isProvisioningAllowed");
7843        try {
7844            return mService.isProvisioningAllowed(action, mContext.getPackageName());
7845        } catch (RemoteException re) {
7846            throw re.rethrowFromSystemServer();
7847        }
7848    }
7849
7850    /**
7851     * Checks whether it is possible to initiate provisioning a managed device,
7852     * profile or user, setting the given package as owner.
7853     *
7854     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7855     *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
7856     *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
7857     *        {@link #ACTION_PROVISION_MANAGED_USER}
7858     * @param packageName The package of the component that would be set as device, user, or profile
7859     *        owner.
7860     * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
7861     * @hide
7862     */
7863    public @ProvisioningPreCondition int checkProvisioningPreCondition(
7864            String action, @NonNull String packageName) {
7865        try {
7866            return mService.checkProvisioningPreCondition(action, packageName);
7867        } catch (RemoteException re) {
7868            throw re.rethrowFromSystemServer();
7869        }
7870    }
7871
7872    /**
7873     * Return if this user is a managed profile of another user. An admin can become the profile
7874     * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
7875     * user with {@link #createAndManageUser}
7876     * @param admin Which profile owner this request is associated with.
7877     * @return if this user is a managed profile of another user.
7878     */
7879    public boolean isManagedProfile(@NonNull ComponentName admin) {
7880        throwIfParentInstance("isManagedProfile");
7881        try {
7882            return mService.isManagedProfile(admin);
7883        } catch (RemoteException re) {
7884            throw re.rethrowFromSystemServer();
7885        }
7886    }
7887
7888    /**
7889     * @hide
7890     * Return if this user is a system-only user. An admin can manage a device from a system only
7891     * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
7892     * @param admin Which device owner this request is associated with.
7893     * @return if this user is a system-only user.
7894     */
7895    public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
7896        try {
7897            return mService.isSystemOnlyUser(admin);
7898        } catch (RemoteException re) {
7899            throw re.rethrowFromSystemServer();
7900        }
7901    }
7902
7903    /**
7904     * Called by device owner to get the MAC address of the Wi-Fi device.
7905     *
7906     * @param admin Which device owner this request is associated with.
7907     * @return the MAC address of the Wi-Fi device, or null when the information is not available.
7908     *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
7909     *         <p>
7910     *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
7911     * @throws SecurityException if {@code admin} is not a device owner.
7912     */
7913    public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
7914        throwIfParentInstance("getWifiMacAddress");
7915        try {
7916            return mService.getWifiMacAddress(admin);
7917        } catch (RemoteException re) {
7918            throw re.rethrowFromSystemServer();
7919        }
7920    }
7921
7922    /**
7923     * Called by device owner to reboot the device. If there is an ongoing call on the device,
7924     * throws an {@link IllegalStateException}.
7925     * @param admin Which device owner the request is associated with.
7926     * @throws IllegalStateException if device has an ongoing call.
7927     * @throws SecurityException if {@code admin} is not a device owner.
7928     * @see TelephonyManager#CALL_STATE_IDLE
7929     */
7930    public void reboot(@NonNull ComponentName admin) {
7931        throwIfParentInstance("reboot");
7932        try {
7933            mService.reboot(admin);
7934        } catch (RemoteException re) {
7935            throw re.rethrowFromSystemServer();
7936        }
7937    }
7938
7939    /**
7940     * Called by a device admin to set the short support message. This will be displayed to the user
7941     * in settings screens where funtionality has been disabled by the admin. The message should be
7942     * limited to a short statement such as "This setting is disabled by your administrator. Contact
7943     * someone@example.com for support." If the message is longer than 200 characters it may be
7944     * truncated.
7945     * <p>
7946     * If the short support message needs to be localized, it is the responsibility of the
7947     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7948     * and set a new version of this string accordingly.
7949     *
7950     * @see #setLongSupportMessage
7951     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7952     * @param message Short message to be displayed to the user in settings or null to clear the
7953     *            existing message.
7954     * @throws SecurityException if {@code admin} is not an active administrator.
7955     */
7956    public void setShortSupportMessage(@NonNull ComponentName admin,
7957            @Nullable CharSequence message) {
7958        throwIfParentInstance("setShortSupportMessage");
7959        if (mService != null) {
7960            try {
7961                mService.setShortSupportMessage(admin, message);
7962            } catch (RemoteException e) {
7963                throw e.rethrowFromSystemServer();
7964            }
7965        }
7966    }
7967
7968    /**
7969     * Called by a device admin to get the short support message.
7970     *
7971     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7972     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
7973     *         null if no message has been set.
7974     * @throws SecurityException if {@code admin} is not an active administrator.
7975     */
7976    public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
7977        throwIfParentInstance("getShortSupportMessage");
7978        if (mService != null) {
7979            try {
7980                return mService.getShortSupportMessage(admin);
7981            } catch (RemoteException e) {
7982                throw e.rethrowFromSystemServer();
7983            }
7984        }
7985        return null;
7986    }
7987
7988    /**
7989     * Called by a device admin to set the long support message. This will be displayed to the user
7990     * in the device administators settings screen.
7991     * <p>
7992     * If the long support message needs to be localized, it is the responsibility of the
7993     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7994     * and set a new version of this string accordingly.
7995     *
7996     * @see #setShortSupportMessage
7997     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7998     * @param message Long message to be displayed to the user in settings or null to clear the
7999     *            existing message.
8000     * @throws SecurityException if {@code admin} is not an active administrator.
8001     */
8002    public void setLongSupportMessage(@NonNull ComponentName admin,
8003            @Nullable CharSequence message) {
8004        throwIfParentInstance("setLongSupportMessage");
8005        if (mService != null) {
8006            try {
8007                mService.setLongSupportMessage(admin, message);
8008            } catch (RemoteException e) {
8009                throw e.rethrowFromSystemServer();
8010            }
8011        }
8012    }
8013
8014    /**
8015     * Called by a device admin to get the long support message.
8016     *
8017     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8018     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
8019     *         null if no message has been set.
8020     * @throws SecurityException if {@code admin} is not an active administrator.
8021     */
8022    public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
8023        throwIfParentInstance("getLongSupportMessage");
8024        if (mService != null) {
8025            try {
8026                return mService.getLongSupportMessage(admin);
8027            } catch (RemoteException e) {
8028                throw e.rethrowFromSystemServer();
8029            }
8030        }
8031        return null;
8032    }
8033
8034    /**
8035     * Called by the system to get the short support message.
8036     *
8037     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8038     * @param userHandle user id the admin is running as.
8039     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
8040     *
8041     * @hide
8042     */
8043    public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
8044            int userHandle) {
8045        if (mService != null) {
8046            try {
8047                return mService.getShortSupportMessageForUser(admin, userHandle);
8048            } catch (RemoteException e) {
8049                throw e.rethrowFromSystemServer();
8050            }
8051        }
8052        return null;
8053    }
8054
8055
8056    /**
8057     * Called by the system to get the long support message.
8058     *
8059     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8060     * @param userHandle user id the admin is running as.
8061     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
8062     *
8063     * @hide
8064     */
8065    public @Nullable CharSequence getLongSupportMessageForUser(
8066            @NonNull ComponentName admin, int userHandle) {
8067        if (mService != null) {
8068            try {
8069                return mService.getLongSupportMessageForUser(admin, userHandle);
8070            } catch (RemoteException e) {
8071                throw e.rethrowFromSystemServer();
8072            }
8073        }
8074        return null;
8075    }
8076
8077    /**
8078     * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
8079     * whose calls act on the parent profile.
8080     *
8081     * <p>The following methods are supported for the parent instance, all other methods will
8082     * throw a SecurityException when called on the parent instance:
8083     * <ul>
8084     * <li>{@link #getPasswordQuality}</li>
8085     * <li>{@link #setPasswordQuality}</li>
8086     * <li>{@link #getPasswordMinimumLength}</li>
8087     * <li>{@link #setPasswordMinimumLength}</li>
8088     * <li>{@link #getPasswordMinimumUpperCase}</li>
8089     * <li>{@link #setPasswordMinimumUpperCase}</li>
8090     * <li>{@link #getPasswordMinimumLowerCase}</li>
8091     * <li>{@link #setPasswordMinimumLowerCase}</li>
8092     * <li>{@link #getPasswordMinimumLetters}</li>
8093     * <li>{@link #setPasswordMinimumLetters}</li>
8094     * <li>{@link #getPasswordMinimumNumeric}</li>
8095     * <li>{@link #setPasswordMinimumNumeric}</li>
8096     * <li>{@link #getPasswordMinimumSymbols}</li>
8097     * <li>{@link #setPasswordMinimumSymbols}</li>
8098     * <li>{@link #getPasswordMinimumNonLetter}</li>
8099     * <li>{@link #setPasswordMinimumNonLetter}</li>
8100     * <li>{@link #getPasswordHistoryLength}</li>
8101     * <li>{@link #setPasswordHistoryLength}</li>
8102     * <li>{@link #getPasswordExpirationTimeout}</li>
8103     * <li>{@link #setPasswordExpirationTimeout}</li>
8104     * <li>{@link #getPasswordExpiration}</li>
8105     * <li>{@link #getPasswordMaximumLength}</li>
8106     * <li>{@link #isActivePasswordSufficient}</li>
8107     * <li>{@link #getCurrentFailedPasswordAttempts}</li>
8108     * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
8109     * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
8110     * <li>{@link #getMaximumTimeToLock}</li>
8111     * <li>{@link #setMaximumTimeToLock}</li>
8112     * <li>{@link #lockNow}</li>
8113     * <li>{@link #getKeyguardDisabledFeatures}</li>
8114     * <li>{@link #setKeyguardDisabledFeatures}</li>
8115     * <li>{@link #getTrustAgentConfiguration}</li>
8116     * <li>{@link #setTrustAgentConfiguration}</li>
8117     * <li>{@link #getRequiredStrongAuthTimeout}</li>
8118     * <li>{@link #setRequiredStrongAuthTimeout}</li>
8119     * </ul>
8120     *
8121     * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
8122     * @throws SecurityException if {@code admin} is not a profile owner.
8123     */
8124    public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
8125        throwIfParentInstance("getParentProfileInstance");
8126        try {
8127            if (!mService.isManagedProfile(admin)) {
8128                throw new SecurityException("The current user does not have a parent profile.");
8129            }
8130            return new DevicePolicyManager(mContext, mService, true);
8131        } catch (RemoteException e) {
8132            throw e.rethrowFromSystemServer();
8133        }
8134    }
8135
8136    /**
8137     * Called by device owner to control the security logging feature.
8138     *
8139     * <p> Security logs contain various information intended for security auditing purposes.
8140     * See {@link SecurityEvent} for details.
8141     *
8142     * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
8143     * are unaffiliated secondary users or profiles on the device, regardless of whether the
8144     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
8145     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
8146     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
8147     *
8148     * @param admin Which device owner this request is associated with.
8149     * @param enabled whether security logging should be enabled or not.
8150     * @throws SecurityException if {@code admin} is not a device owner.
8151     * @see #setAffiliationIds
8152     * @see #retrieveSecurityLogs
8153     */
8154    public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
8155        throwIfParentInstance("setSecurityLoggingEnabled");
8156        try {
8157            mService.setSecurityLoggingEnabled(admin, enabled);
8158        } catch (RemoteException re) {
8159            throw re.rethrowFromSystemServer();
8160        }
8161    }
8162
8163    /**
8164     * Return whether security logging is enabled or not by the device owner.
8165     *
8166     * <p>Can only be called by the device owner, otherwise a {@link SecurityException} will be
8167     * thrown.
8168     *
8169     * @param admin Which device owner this request is associated with.
8170     * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
8171     * @throws SecurityException if {@code admin} is not a device owner.
8172     */
8173    public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
8174        throwIfParentInstance("isSecurityLoggingEnabled");
8175        try {
8176            return mService.isSecurityLoggingEnabled(admin);
8177        } catch (RemoteException re) {
8178            throw re.rethrowFromSystemServer();
8179        }
8180    }
8181
8182    /**
8183     * Called by device owner to retrieve all new security logging entries since the last call to
8184     * this API after device boots.
8185     *
8186     * <p> Access to the logs is rate limited and it will only return new logs after the device
8187     * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
8188     *
8189     * <p>If there is any other user or profile on the device, it must be affiliated with the
8190     * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8191     *
8192     * @param admin Which device owner this request is associated with.
8193     * @return the new batch of security logs which is a list of {@link SecurityEvent},
8194     * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
8195     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8196     * profile or secondary user that is not affiliated with the device.
8197     * @see #isAffiliatedUser
8198     * @see DeviceAdminReceiver#onSecurityLogsAvailable
8199     */
8200    public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
8201        throwIfParentInstance("retrieveSecurityLogs");
8202        try {
8203            ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
8204            if (list != null) {
8205                return list.getList();
8206            } else {
8207                // Rate limit exceeded.
8208                return null;
8209            }
8210        } catch (RemoteException re) {
8211            throw re.rethrowFromSystemServer();
8212        }
8213    }
8214
8215    /**
8216     * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
8217     * profile.
8218     *
8219     * @hide
8220     */
8221    public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
8222        mContext.checkSelfPermission(
8223                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
8224        if (!uInfo.isManagedProfile()) {
8225            throw new SecurityException("The user " + uInfo.id
8226                    + " does not have a parent profile.");
8227        }
8228        return new DevicePolicyManager(mContext, mService, true);
8229    }
8230
8231    /**
8232     * Called by a device or profile owner to restrict packages from accessing metered data.
8233     *
8234     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
8235     * @param packageNames the list of package names to be restricted.
8236     * @return a list of package names which could not be restricted.
8237     * @throws SecurityException if {@code admin} is not a device or profile owner.
8238     */
8239    public @NonNull List<String> setMeteredDataDisabled(@NonNull ComponentName admin,
8240            @NonNull List<String> packageNames) {
8241        throwIfParentInstance("setMeteredDataDisabled");
8242        if (mService != null) {
8243            try {
8244                return mService.setMeteredDataDisabled(admin, packageNames);
8245            } catch (RemoteException re) {
8246                throw re.rethrowFromSystemServer();
8247            }
8248        }
8249        return packageNames;
8250    }
8251
8252    /**
8253     * Called by a device or profile owner to retrieve the list of packages which are restricted
8254     * by the admin from accessing metered data.
8255     *
8256     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
8257     * @return the list of restricted package names.
8258     * @throws SecurityException if {@code admin} is not a device or profile owner.
8259     */
8260    public @NonNull List<String> getMeteredDataDisabled(@NonNull ComponentName admin) {
8261        throwIfParentInstance("getMeteredDataDisabled");
8262        if (mService != null) {
8263            try {
8264                return mService.getMeteredDataDisabled(admin);
8265            } catch (RemoteException re) {
8266                throw re.rethrowFromSystemServer();
8267            }
8268        }
8269        return new ArrayList<>();
8270    }
8271
8272    /**
8273     * Called by device owners to retrieve device logs from before the device's last reboot.
8274     * <p>
8275     * <strong> This API is not supported on all devices. Calling this API on unsupported devices
8276     * will result in {@code null} being returned. The device logs are retrieved from a RAM region
8277     * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
8278     * about data corruption when parsing. </strong>
8279     *
8280     * <p>If there is any other user or profile on the device, it must be affiliated with the
8281     * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8282     *
8283     * @param admin Which device owner this request is associated with.
8284     * @return Device logs from before the latest reboot of the system, or {@code null} if this API
8285     *         is not supported on the device.
8286     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8287     * profile or secondary user that is not affiliated with the device.
8288     * @see #isAffiliatedUser
8289     * @see #retrieveSecurityLogs
8290     */
8291    public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
8292            @NonNull ComponentName admin) {
8293        throwIfParentInstance("retrievePreRebootSecurityLogs");
8294        try {
8295            ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
8296            if (list != null) {
8297                return list.getList();
8298            } else {
8299                return null;
8300            }
8301        } catch (RemoteException re) {
8302            throw re.rethrowFromSystemServer();
8303        }
8304    }
8305
8306    /**
8307     * Called by a profile owner of a managed profile to set the color used for customization. This
8308     * color is used as background color of the confirm credentials screen for that user. The
8309     * default color is teal (#00796B).
8310     * <p>
8311     * The confirm credentials screen can be created using
8312     * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
8313     *
8314     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8315     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
8316     * @throws SecurityException if {@code admin} is not a profile owner.
8317     */
8318    public void setOrganizationColor(@NonNull ComponentName admin, int color) {
8319        throwIfParentInstance("setOrganizationColor");
8320        try {
8321            // always enforce alpha channel to have 100% opacity
8322            color |= 0xFF000000;
8323            mService.setOrganizationColor(admin, color);
8324        } catch (RemoteException re) {
8325            throw re.rethrowFromSystemServer();
8326        }
8327    }
8328
8329    /**
8330     * @hide
8331     *
8332     * Sets the color used for customization.
8333     *
8334     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
8335     * @param userId which user to set the color to.
8336     * @RequiresPermission(allOf = {
8337     *       Manifest.permission.MANAGE_USERS,
8338     *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
8339     */
8340    public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
8341        try {
8342            // always enforce alpha channel to have 100% opacity
8343            color |= 0xFF000000;
8344            mService.setOrganizationColorForUser(color, userId);
8345        } catch (RemoteException re) {
8346            throw re.rethrowFromSystemServer();
8347        }
8348    }
8349
8350    /**
8351     * Called by a profile owner of a managed profile to retrieve the color used for customization.
8352     * This color is used as background color of the confirm credentials screen for that user.
8353     *
8354     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8355     * @return The 24bit (0xRRGGBB) representation of the color to be used.
8356     * @throws SecurityException if {@code admin} is not a profile owner.
8357     */
8358    public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
8359        throwIfParentInstance("getOrganizationColor");
8360        try {
8361            return mService.getOrganizationColor(admin);
8362        } catch (RemoteException re) {
8363            throw re.rethrowFromSystemServer();
8364        }
8365    }
8366
8367    /**
8368     * @hide
8369     * Retrieve the customization color for a given user.
8370     *
8371     * @param userHandle The user id of the user we're interested in.
8372     * @return The 24bit (0xRRGGBB) representation of the color to be used.
8373     */
8374    public @ColorInt int getOrganizationColorForUser(int userHandle) {
8375        try {
8376            return mService.getOrganizationColorForUser(userHandle);
8377        } catch (RemoteException re) {
8378            throw re.rethrowFromSystemServer();
8379        }
8380    }
8381
8382    /**
8383     * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
8384     * the organization under management.
8385     *
8386     * <p>If the organization name needs to be localized, it is the responsibility of the {@link
8387     * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
8388     * a new version of this string accordingly.
8389     *
8390     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8391     * @param title The organization name or {@code null} to clear a previously set name.
8392     * @throws SecurityException if {@code admin} is not a device or profile owner.
8393     */
8394    public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
8395        throwIfParentInstance("setOrganizationName");
8396        try {
8397            mService.setOrganizationName(admin, title);
8398        } catch (RemoteException re) {
8399            throw re.rethrowFromSystemServer();
8400        }
8401    }
8402
8403    /**
8404     * Called by a profile owner of a managed profile to retrieve the name of the organization under
8405     * management.
8406     *
8407     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8408     * @return The organization name or {@code null} if none is set.
8409     * @throws SecurityException if {@code admin} is not a profile owner.
8410     */
8411    public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
8412        throwIfParentInstance("getOrganizationName");
8413        try {
8414            return mService.getOrganizationName(admin);
8415        } catch (RemoteException re) {
8416            throw re.rethrowFromSystemServer();
8417        }
8418    }
8419
8420    /**
8421     * Called by the system to retrieve the name of the organization managing the device.
8422     *
8423     * @return The organization name or {@code null} if none is set.
8424     * @throws SecurityException if the caller is not the device owner, does not hold the
8425     *         MANAGE_USERS permission and is not the system.
8426     *
8427     * @hide
8428     */
8429    @SystemApi
8430    @TestApi
8431    @SuppressLint("Doclava125")
8432    public @Nullable CharSequence getDeviceOwnerOrganizationName() {
8433        try {
8434            return mService.getDeviceOwnerOrganizationName();
8435        } catch (RemoteException re) {
8436            throw re.rethrowFromSystemServer();
8437        }
8438    }
8439
8440    /**
8441     * Retrieve the default title message used in the confirm credentials screen for a given user.
8442     *
8443     * @param userHandle The user id of the user we're interested in.
8444     * @return The organization name or {@code null} if none is set.
8445     *
8446     * @hide
8447     */
8448    public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
8449        try {
8450            return mService.getOrganizationNameForUser(userHandle);
8451        } catch (RemoteException re) {
8452            throw re.rethrowFromSystemServer();
8453        }
8454    }
8455
8456    /**
8457     * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
8458     *         return {@link #STATE_USER_UNMANAGED}
8459     * @hide
8460     */
8461    @SystemApi
8462    @UserProvisioningState
8463    public int getUserProvisioningState() {
8464        throwIfParentInstance("getUserProvisioningState");
8465        if (mService != null) {
8466            try {
8467                return mService.getUserProvisioningState();
8468            } catch (RemoteException e) {
8469                throw e.rethrowFromSystemServer();
8470            }
8471        }
8472        return STATE_USER_UNMANAGED;
8473    }
8474
8475    /**
8476     * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
8477     *
8478     * @param state to store
8479     * @param userHandle for user
8480     * @hide
8481     */
8482    public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
8483        if (mService != null) {
8484            try {
8485                mService.setUserProvisioningState(state, userHandle);
8486            } catch (RemoteException e) {
8487                throw e.rethrowFromSystemServer();
8488            }
8489        }
8490    }
8491
8492    /**
8493     * Indicates the entity that controls the device or profile owner. Two users/profiles are
8494     * affiliated if the set of ids set by their device or profile owners intersect.
8495     *
8496     * <p>A user/profile that is affiliated with the device owner user is considered to be
8497     * affiliated with the device.
8498     *
8499     * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
8500     * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user or profile
8501     * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
8502     * affiliation ids are set by its profile owner as soon as possible after the user/profile is
8503     * created.
8504     *
8505     * @param admin Which profile or device owner this request is associated with.
8506     * @param ids A set of opaque non-empty affiliation ids.
8507     *
8508     * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
8509     * @see #isAffiliatedUser
8510     */
8511    public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
8512        throwIfParentInstance("setAffiliationIds");
8513        if (ids == null) {
8514            throw new IllegalArgumentException("ids must not be null");
8515        }
8516        try {
8517            mService.setAffiliationIds(admin, new ArrayList<>(ids));
8518        } catch (RemoteException e) {
8519            throw e.rethrowFromSystemServer();
8520        }
8521    }
8522
8523    /**
8524     * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
8525     * empty set if none have been set.
8526     */
8527    public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
8528        throwIfParentInstance("getAffiliationIds");
8529        try {
8530            return new ArraySet<>(mService.getAffiliationIds(admin));
8531        } catch (RemoteException e) {
8532            throw e.rethrowFromSystemServer();
8533        }
8534    }
8535
8536    /**
8537     * Returns whether this user/profile is affiliated with the device.
8538     * <p>
8539     * By definition, the user that the device owner runs on is always affiliated with the device.
8540     * Any other user/profile is considered affiliated with the device if the set specified by its
8541     * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
8542     * @see #setAffiliationIds
8543     */
8544    public boolean isAffiliatedUser() {
8545        throwIfParentInstance("isAffiliatedUser");
8546        try {
8547            return mService.isAffiliatedUser();
8548        } catch (RemoteException e) {
8549            throw e.rethrowFromSystemServer();
8550        }
8551    }
8552
8553    /**
8554     * @hide
8555     * Returns whether the uninstall for {@code packageName} for the current user is in queue
8556     * to be started
8557     * @param packageName the package to check for
8558     * @return whether the uninstall intent for {@code packageName} is pending
8559     */
8560    public boolean isUninstallInQueue(String packageName) {
8561        try {
8562            return mService.isUninstallInQueue(packageName);
8563        } catch (RemoteException re) {
8564            throw re.rethrowFromSystemServer();
8565        }
8566    }
8567
8568    /**
8569     * @hide
8570     * @param packageName the package containing active DAs to be uninstalled
8571     */
8572    public void uninstallPackageWithActiveAdmins(String packageName) {
8573        try {
8574            mService.uninstallPackageWithActiveAdmins(packageName);
8575        } catch (RemoteException re) {
8576            throw re.rethrowFromSystemServer();
8577        }
8578    }
8579
8580    /**
8581     * @hide
8582     * Remove a test admin synchronously without sending it a broadcast about being removed.
8583     * If the admin is a profile owner or device owner it will still be removed.
8584     *
8585     * @param userHandle user id to remove the admin for.
8586     * @param admin The administration compononent to remove.
8587     * @throws SecurityException if the caller is not shell / root or the admin package
8588     *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
8589     */
8590    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
8591        try {
8592            mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
8593        } catch (RemoteException re) {
8594            throw re.rethrowFromSystemServer();
8595        }
8596    }
8597
8598    /**
8599     * Returns whether the device has been provisioned.
8600     *
8601     * <p>Not for use by third-party applications.
8602     *
8603     * @hide
8604     */
8605    @SystemApi
8606    public boolean isDeviceProvisioned() {
8607        try {
8608            return mService.isDeviceProvisioned();
8609        } catch (RemoteException re) {
8610            throw re.rethrowFromSystemServer();
8611        }
8612    }
8613
8614    /**
8615      * Writes that the provisioning configuration has been applied.
8616      *
8617      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
8618      * permission.
8619      *
8620      * <p>Not for use by third-party applications.
8621      *
8622      * @hide
8623      */
8624    @SystemApi
8625    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8626    public void setDeviceProvisioningConfigApplied() {
8627        try {
8628            mService.setDeviceProvisioningConfigApplied();
8629        } catch (RemoteException re) {
8630            throw re.rethrowFromSystemServer();
8631        }
8632    }
8633
8634    /**
8635     * Returns whether the provisioning configuration has been applied.
8636     *
8637     * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
8638     *
8639     * <p>Not for use by third-party applications.
8640     *
8641     * @return whether the provisioning configuration has been applied.
8642     *
8643     * @hide
8644     */
8645    @SystemApi
8646    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8647    public boolean isDeviceProvisioningConfigApplied() {
8648        try {
8649            return mService.isDeviceProvisioningConfigApplied();
8650        } catch (RemoteException re) {
8651            throw re.rethrowFromSystemServer();
8652        }
8653    }
8654
8655    /**
8656     * @hide
8657     * Force update user setup completed status. This API has no effect on user build.
8658     * @throws {@link SecurityException} if the caller has no
8659     *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
8660     *         not {@link UserHandle#SYSTEM_USER}
8661     */
8662    public void forceUpdateUserSetupComplete() {
8663        try {
8664            mService.forceUpdateUserSetupComplete();
8665        } catch (RemoteException re) {
8666            throw re.rethrowFromSystemServer();
8667        }
8668    }
8669
8670    private void throwIfParentInstance(String functionName) {
8671        if (mParentInstance) {
8672            throw new SecurityException(functionName + " cannot be called on the parent instance");
8673        }
8674    }
8675
8676    /**
8677     * Allows the device owner to enable or disable the backup service.
8678     *
8679     * <p> Backup service manages all backup and restore mechanisms on the device. Setting this to
8680     * false will prevent data from being backed up or restored.
8681     *
8682     * <p> Backup service is off by default when device owner is present.
8683     *
8684     * <p> If backups are made mandatory by specifying a non-null mandatory backup transport using
8685     * the {@link DevicePolicyManager#setMandatoryBackupTransport} method, the backup service is
8686     * automatically enabled.
8687     *
8688     * <p> If the backup service is disabled using this method after the mandatory backup transport
8689     * has been set, the mandatory backup transport is cleared.
8690     *
8691     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8692     * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
8693     * @throws SecurityException if {@code admin} is not a device owner.
8694     */
8695    public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
8696        throwIfParentInstance("setBackupServiceEnabled");
8697        try {
8698            mService.setBackupServiceEnabled(admin, enabled);
8699        } catch (RemoteException re) {
8700            throw re.rethrowFromSystemServer();
8701        }
8702    }
8703
8704    /**
8705     * Return whether the backup service is enabled by the device owner.
8706     *
8707     * <p> Backup service manages all backup and restore mechanisms on the device.
8708     *
8709     * @return {@code true} if backup service is enabled, {@code false} otherwise.
8710     * @see #setBackupServiceEnabled
8711     */
8712    public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
8713        throwIfParentInstance("isBackupServiceEnabled");
8714        try {
8715            return mService.isBackupServiceEnabled(admin);
8716        } catch (RemoteException re) {
8717            throw re.rethrowFromSystemServer();
8718        }
8719    }
8720
8721    /**
8722     * Makes backups mandatory and enforces the usage of the specified backup transport.
8723     *
8724     * <p>When a {@code null} backup transport is specified, backups are made optional again.
8725     * <p>Only device owner can call this method.
8726     * <p>If backups were disabled and a non-null backup transport {@link ComponentName} is
8727     * specified, backups will be enabled.
8728     *
8729     * @param admin admin Which {@link DeviceAdminReceiver} this request is associated with.
8730     * @param backupTransportComponent The backup transport layer to be used for mandatory backups.
8731     * @throws SecurityException if {@code admin} is not a device owner.
8732     */
8733    public void setMandatoryBackupTransport(
8734            @NonNull ComponentName admin, @Nullable ComponentName backupTransportComponent) {
8735        try {
8736            mService.setMandatoryBackupTransport(admin, backupTransportComponent);
8737        } catch (RemoteException re) {
8738            throw re.rethrowFromSystemServer();
8739        }
8740    }
8741
8742    /**
8743     * Returns the backup transport which has to be used for backups if backups are mandatory or
8744     * {@code null} if backups are not mandatory.
8745     *
8746     * @return a {@link ComponentName} of the backup transport layer to be used if backups are
8747     *         mandatory or {@code null} if backups are not mandatory.
8748     */
8749    public ComponentName getMandatoryBackupTransport() {
8750        try {
8751            return mService.getMandatoryBackupTransport();
8752        } catch (RemoteException re) {
8753            throw re.rethrowFromSystemServer();
8754        }
8755    }
8756
8757
8758    /**
8759     * Called by a device owner to control the network logging feature.
8760     *
8761     * <p> Network logs contain DNS lookup and connect() library call events. The following library
8762     *     functions are recorded while network logging is active:
8763     *     <ul>
8764     *       <li>{@code getaddrinfo()}</li>
8765     *       <li>{@code gethostbyname()}</li>
8766     *       <li>{@code connect()}</li>
8767     *     </ul>
8768     *
8769     * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
8770     *     full system call logging; event reporting is enabled by default for all processes but not
8771     *     strongly enforced.
8772     *     Events from applications using alternative implementations of libc, making direct kernel
8773     *     calls, or deliberately obfuscating traffic may not be recorded.
8774     *
8775     * <p> Some common network events may not be reported. For example:
8776     *     <ul>
8777     *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
8778     *           an alternative system for name resolution, and so avoid calling
8779     *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
8780     *       <li>Applications may use datagram sockets for performance reasons, for example
8781     *           for a game client. Calling {@code connect()} is unnecessary for this kind of
8782     *           socket, so it will not trigger a network event.</li>
8783     *     </ul>
8784     *
8785     * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
8786     *     always-on VPN service.
8787     *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
8788     *     and {@link android.net.VpnService} for details.
8789     *
8790     * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
8791     * are unaffiliated secondary users or profiles on the device, regardless of whether the
8792     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
8793     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
8794     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
8795     *
8796     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8797     * @param enabled whether network logging should be enabled or not.
8798     * @throws SecurityException if {@code admin} is not a device owner.
8799     * @see #setAffiliationIds
8800     * @see #retrieveNetworkLogs
8801     */
8802    public void setNetworkLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
8803        throwIfParentInstance("setNetworkLoggingEnabled");
8804        try {
8805            mService.setNetworkLoggingEnabled(admin, enabled);
8806        } catch (RemoteException re) {
8807            throw re.rethrowFromSystemServer();
8808        }
8809    }
8810
8811    /**
8812     * Return whether network logging is enabled by a device owner.
8813     *
8814     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
8815     * be {@code null} if the caller has MANAGE_USERS permission.
8816     * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
8817     * @throws SecurityException if {@code admin} is not a device owner and caller has
8818     * no MANAGE_USERS permission
8819     */
8820    public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
8821        throwIfParentInstance("isNetworkLoggingEnabled");
8822        try {
8823            return mService.isNetworkLoggingEnabled(admin);
8824        } catch (RemoteException re) {
8825            throw re.rethrowFromSystemServer();
8826        }
8827    }
8828
8829    /**
8830     * Called by device owner to retrieve the most recent batch of network logging events.
8831     * A device owner has to provide a batchToken provided as part of
8832     * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
8833     * token of the most recent available batch of logs, {@code null} will be returned.
8834     *
8835     * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
8836     *
8837     * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
8838     *
8839     * <p> Access to the logs is rate limited and this method will only return a new batch of logs
8840     * after the device device owner has been notified via
8841     * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
8842     *
8843     * <p>If a secondary user or profile is created, calling this method will throw a
8844     * {@link SecurityException} until all users become affiliated again. It will also no longer be
8845     * possible to retrieve the network logs batch with the most recent batchToken provided
8846     * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
8847     * {@link DevicePolicyManager#setAffiliationIds}.
8848     *
8849     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8850     * @param batchToken A token of the batch to retrieve
8851     * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
8852     *        {@code null} if the batch represented by batchToken is no longer available or if
8853     *        logging is disabled.
8854     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8855     * profile or secondary user that is not affiliated with the device.
8856     * @see #setAffiliationIds
8857     * @see DeviceAdminReceiver#onNetworkLogsAvailable
8858     */
8859    public @Nullable List<NetworkEvent> retrieveNetworkLogs(@NonNull ComponentName admin,
8860            long batchToken) {
8861        throwIfParentInstance("retrieveNetworkLogs");
8862        try {
8863            return mService.retrieveNetworkLogs(admin, batchToken);
8864        } catch (RemoteException re) {
8865            throw re.rethrowFromSystemServer();
8866        }
8867    }
8868
8869    /**
8870     * Called by a device owner to bind to a service from a profile owner or vice versa.
8871     * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
8872     * device/profile owners are allowed to bind to services of another profile/device owner.
8873     * <p>
8874     * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
8875     * Note that the {@link Context} used to obtain this
8876     * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
8877     * to bind to the {@link android.app.Service}.
8878     *
8879     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8880     * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
8881     *        explicit component name or a package name to match an
8882     *        {@link IntentFilter} published by a service.
8883     * @param conn Receives information as the service is started and stopped in main thread. This
8884     *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
8885     * @param flags Operation options for the binding operation. See
8886     *        {@link Context#bindService(Intent, ServiceConnection, int)}.
8887     * @param targetUser Which user to bind to. Must be one of the users returned by
8888     *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
8889     *        be thrown.
8890     * @return If you have successfully bound to the service, {@code true} is returned;
8891     *         {@code false} is returned if the connection is not made and you will not
8892     *         receive the service object.
8893     *
8894     * @see Context#bindService(Intent, ServiceConnection, int)
8895     * @see #getBindDeviceAdminTargetUsers(ComponentName)
8896     */
8897    public boolean bindDeviceAdminServiceAsUser(
8898            @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
8899            @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
8900        throwIfParentInstance("bindDeviceAdminServiceAsUser");
8901        // Keep this in sync with ContextImpl.bindServiceCommon.
8902        try {
8903            final IServiceConnection sd = mContext.getServiceDispatcher(
8904                    conn, mContext.getMainThreadHandler(), flags);
8905            serviceIntent.prepareToLeaveProcess(mContext);
8906            return mService.bindDeviceAdminServiceAsUser(admin,
8907                    mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
8908                    sd, flags, targetUser.getIdentifier());
8909        } catch (RemoteException re) {
8910            throw re.rethrowFromSystemServer();
8911        }
8912    }
8913
8914    /**
8915     * Returns the list of target users that the calling device or profile owner can use when
8916     * calling {@link #bindDeviceAdminServiceAsUser}.
8917     * <p>
8918     * A device owner can bind to a service from a profile owner and vice versa, provided that:
8919     * <ul>
8920     * <li>Both belong to the same package name.
8921     * <li>Both users are affiliated. See {@link #setAffiliationIds}.
8922     * </ul>
8923     */
8924    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
8925        throwIfParentInstance("getBindDeviceAdminTargetUsers");
8926        try {
8927            return mService.getBindDeviceAdminTargetUsers(admin);
8928        } catch (RemoteException re) {
8929            throw re.rethrowFromSystemServer();
8930        }
8931    }
8932
8933    /**
8934     * Called by the system to get the time at which the device owner last retrieved security
8935     * logging entries.
8936     *
8937     * @return the time at which the device owner most recently retrieved security logging entries,
8938     *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
8939     * @throws SecurityException if the caller is not the device owner, does not hold the
8940     *         MANAGE_USERS permission and is not the system.
8941     *
8942     * @hide
8943     */
8944    @TestApi
8945    public long getLastSecurityLogRetrievalTime() {
8946        try {
8947            return mService.getLastSecurityLogRetrievalTime();
8948        } catch (RemoteException re) {
8949            throw re.rethrowFromSystemServer();
8950        }
8951    }
8952
8953    /**
8954     * Called by the system to get the time at which the device owner last requested a bug report.
8955     *
8956     * @return the time at which the device owner most recently requested a bug report, in
8957     *         milliseconds since epoch; -1 if a bug report was never requested.
8958     * @throws SecurityException if the caller is not the device owner, does not hold the
8959     *         MANAGE_USERS permission and is not the system.
8960     *
8961     * @hide
8962     */
8963    @TestApi
8964    public long getLastBugReportRequestTime() {
8965        try {
8966            return mService.getLastBugReportRequestTime();
8967        } catch (RemoteException re) {
8968            throw re.rethrowFromSystemServer();
8969        }
8970    }
8971
8972    /**
8973     * Called by the system to get the time at which the device owner last retrieved network logging
8974     * events.
8975     *
8976     * @return the time at which the device owner most recently retrieved network logging events, in
8977     *         milliseconds since epoch; -1 if network logging events were never retrieved.
8978     * @throws SecurityException if the caller is not the device owner, does not hold the
8979     *         MANAGE_USERS permission and is not the system.
8980     *
8981     * @hide
8982     */
8983    @TestApi
8984    public long getLastNetworkLogRetrievalTime() {
8985        try {
8986            return mService.getLastNetworkLogRetrievalTime();
8987        } catch (RemoteException re) {
8988            throw re.rethrowFromSystemServer();
8989        }
8990    }
8991
8992    /**
8993     * Called by the system to find out whether the current user's IME was set by the device/profile
8994     * owner or the user.
8995     *
8996     * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
8997     *         otherwise.
8998     * @throws SecurityException if the caller is not the device owner/profile owner.
8999     *
9000     * @hide
9001     */
9002    @TestApi
9003    public boolean isCurrentInputMethodSetByOwner() {
9004        try {
9005            return mService.isCurrentInputMethodSetByOwner();
9006        } catch (RemoteException re) {
9007            throw re.rethrowFromSystemServer();
9008        }
9009    }
9010
9011    /**
9012     * Called by the system to get a list of CA certificates that were installed by the device or
9013     * profile owner.
9014     *
9015     * <p> The caller must be the target user's device owner/profile Owner or hold the
9016     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
9017     *
9018     * @param user The user for whom to retrieve information.
9019     * @return list of aliases identifying CA certificates installed by the device or profile owner
9020     * @throws SecurityException if the caller does not have permission to retrieve information
9021     *         about the given user's CA certificates.
9022     *
9023     * @hide
9024     */
9025    @TestApi
9026    public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
9027        try {
9028            return mService.getOwnerInstalledCaCerts(user).getList();
9029        } catch (RemoteException re) {
9030            throw re.rethrowFromSystemServer();
9031        }
9032    }
9033
9034    /**
9035     * Called by the device owner or profile owner to clear application user data of a given
9036     * package. The behaviour of this is equivalent to the target application calling
9037     * {@link android.app.ActivityManager#clearApplicationUserData()}.
9038     *
9039     * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
9040     * external storage or user dictionary. This data will not be wiped by calling this API.
9041     *
9042     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9043     * @param packageName The name of the package which will have its user data wiped.
9044     * @param executor The executor through which the listener should be invoked.
9045     * @param listener A callback object that will inform the caller when the clearing is done.
9046     * @throws SecurityException if the caller is not the device owner/profile owner.
9047     * @return whether the clearing succeeded.
9048     */
9049    public boolean clearApplicationUserData(@NonNull ComponentName admin,
9050            @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
9051            @NonNull OnClearApplicationUserDataListener listener) {
9052        throwIfParentInstance("clearAppData");
9053        Preconditions.checkNotNull(executor);
9054        try {
9055            return mService.clearApplicationUserData(admin, packageName,
9056                    new IPackageDataObserver.Stub() {
9057                        public void onRemoveCompleted(String pkg, boolean succeeded) {
9058                            executor.execute(() ->
9059                                    listener.onApplicationUserDataCleared(pkg, succeeded));
9060                        }
9061                    });
9062        } catch (RemoteException re) {
9063            throw re.rethrowFromSystemServer();
9064        }
9065    }
9066
9067    /**
9068     * Called by a device owner to specify whether logout is enabled for all secondary users. The
9069     * system may show a logout button that stops the user and switches back to the primary user.
9070     *
9071     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9072     * @param enabled whether logout should be enabled or not.
9073     * @throws SecurityException if {@code admin} is not a device owner.
9074     */
9075    public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
9076        throwIfParentInstance("setLogoutEnabled");
9077        try {
9078            mService.setLogoutEnabled(admin, enabled);
9079        } catch (RemoteException re) {
9080            throw re.rethrowFromSystemServer();
9081        }
9082    }
9083
9084    /**
9085     * Returns whether logout is enabled by a device owner.
9086     *
9087     * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
9088     */
9089    public boolean isLogoutEnabled() {
9090        throwIfParentInstance("isLogoutEnabled");
9091        try {
9092            return mService.isLogoutEnabled();
9093        } catch (RemoteException re) {
9094            throw re.rethrowFromSystemServer();
9095        }
9096    }
9097
9098    /**
9099     * Callback used in {@link #clearApplicationUserData}
9100     * to indicate that the clearing of an application's user data is done.
9101     */
9102    public interface OnClearApplicationUserDataListener {
9103        /**
9104         * Method invoked when clearing the application user data has completed.
9105         *
9106         * @param packageName The name of the package which had its user data cleared.
9107         * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
9108         *                  apps and protected system packages.
9109         */
9110        void onApplicationUserDataCleared(String packageName, boolean succeeded);
9111    }
9112
9113    /**
9114     * Returns set of system apps that should be removed during provisioning.
9115     *
9116     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9117     * @param userId ID of the user to be provisioned.
9118     * @param provisioningAction action indicating type of provisioning, should be one of
9119     * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
9120     * {@link #ACTION_PROVISION_MANAGED_USER}.
9121     *
9122     * @hide
9123     */
9124    public Set<String> getDisallowedSystemApps(ComponentName admin, int userId,
9125            String provisioningAction) {
9126        try {
9127            return new ArraySet<>(
9128                    mService.getDisallowedSystemApps(admin, userId, provisioningAction));
9129        } catch (RemoteException re) {
9130            throw re.rethrowFromSystemServer();
9131        }
9132    }
9133
9134    /**
9135     * Changes the current administrator to another one. All policies from the current
9136     * administrator are migrated to the new administrator. The whole operation is atomic -
9137     * the transfer is either complete or not done at all.
9138     *
9139     * <p>Depending on the current administrator (device owner, profile owner), you have the
9140     * following expected behaviour:
9141     * <ul>
9142     *     <li>A device owner can only be transferred to a new device owner</li>
9143     *     <li>A profile owner can only be transferred to a new profile owner</li>
9144     * </ul>
9145     *
9146     * <p>Use the {@code bundle} parameter to pass data to the new administrator. The parameters
9147     * will be received in the
9148     * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)} callback.
9149     *
9150     * <p>The incoming target administrator must have the
9151     * {@link DeviceAdminReceiver#SUPPORT_TRANSFER_OWNERSHIP_META_DATA} <code>meta-data</code> tag
9152     * included in its corresponding <code>receiver</code> component with a value of {@code true}.
9153     * Otherwise an {@link IllegalArgumentException} will be thrown.
9154     *
9155     * @param admin which {@link DeviceAdminReceiver} this request is associated with
9156     * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
9157     * @param bundle data to be sent to the new administrator
9158     * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
9159     * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null},
9160     * both are components in the same package or {@code target} is not an active admin
9161     */
9162    public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
9163            PersistableBundle bundle) {
9164        throwIfParentInstance("transferOwnership");
9165        try {
9166            mService.transferOwnership(admin, target, bundle);
9167        } catch (RemoteException re) {
9168            throw re.rethrowFromSystemServer();
9169        }
9170    }
9171
9172    /**
9173     * Called by a device owner to specify the user session start message. This may be displayed
9174     * during a user switch.
9175     * <p>
9176     * The message should be limited to a short statement or it may be truncated.
9177     * <p>
9178     * If the message needs to be localized, it is the responsibility of the
9179     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9180     * and set a new version of this message accordingly.
9181     *
9182     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9183     * @param startUserSessionMessage message for starting user session, or {@code null} to use
9184     * system default message.
9185     * @throws SecurityException if {@code admin} is not a device owner.
9186     */
9187    public void setStartUserSessionMessage(
9188            @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
9189        throwIfParentInstance("setStartUserSessionMessage");
9190        try {
9191            mService.setStartUserSessionMessage(admin, startUserSessionMessage);
9192        } catch (RemoteException re) {
9193            throw re.rethrowFromSystemServer();
9194        }
9195    }
9196
9197    /**
9198     * Called by a device owner to specify the user session end message. This may be displayed
9199     * during a user switch.
9200     * <p>
9201     * The message should be limited to a short statement or it may be truncated.
9202     * <p>
9203     * If the message needs to be localized, it is the responsibility of the
9204     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9205     * and set a new version of this message accordingly.
9206     *
9207     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9208     * @param endUserSessionMessage message for ending user session, or {@code null} to use system
9209     * default message.
9210     * @throws SecurityException if {@code admin} is not a device owner.
9211     */
9212    public void setEndUserSessionMessage(
9213            @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
9214        throwIfParentInstance("setEndUserSessionMessage");
9215        try {
9216            mService.setEndUserSessionMessage(admin, endUserSessionMessage);
9217        } catch (RemoteException re) {
9218            throw re.rethrowFromSystemServer();
9219        }
9220    }
9221
9222    /**
9223     * Returns the user session start message.
9224     *
9225     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9226     * @throws SecurityException if {@code admin} is not a device owner.
9227     */
9228    public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
9229        throwIfParentInstance("getStartUserSessionMessage");
9230        try {
9231            return mService.getStartUserSessionMessage(admin);
9232        } catch (RemoteException re) {
9233            throw re.rethrowFromSystemServer();
9234        }
9235    }
9236
9237    /**
9238     * Returns the user session end message.
9239     *
9240     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9241     * @throws SecurityException if {@code admin} is not a device owner.
9242     */
9243    public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
9244        throwIfParentInstance("getEndUserSessionMessage");
9245        try {
9246            return mService.getEndUserSessionMessage(admin);
9247        } catch (RemoteException re) {
9248            throw re.rethrowFromSystemServer();
9249        }
9250    }
9251
9252    /**
9253     * Allows/disallows printing.
9254     *
9255     * Called by a device owner or a profile owner.
9256     * Device owner changes policy for all users. Profile owner can override it if present.
9257     * Printing is enabled by default. If {@code FEATURE_PRINTING} is absent, the call is ignored.
9258     *
9259     * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9260     * @param enabled whether printing should be allowed or not.
9261     * @throws SecurityException if {@code admin} is neither device, nor profile owner.
9262     */
9263    public void setPrintingEnabled(@NonNull ComponentName admin, boolean enabled) {
9264        try {
9265            mService.setPrintingEnabled(admin, enabled);
9266        } catch (RemoteException re) {
9267            throw re.rethrowFromSystemServer();
9268        }
9269    }
9270
9271    /**
9272     * Returns whether printing is enabled for this user.
9273     *
9274     * Always {@code false} if {@code FEATURE_PRINTING} is absent.
9275     * Otherwise, {@code true} by default.
9276     *
9277     * @return {@code true} iff printing is enabled.
9278     */
9279    public boolean isPrintingEnabled() {
9280        try {
9281            return mService.isPrintingEnabled();
9282        } catch (RemoteException re) {
9283            throw re.rethrowFromSystemServer();
9284        }
9285    }
9286
9287    /**
9288     * Returns error message to be displayed when printing is disabled.
9289     *
9290     * Used only by PrintService.
9291     * @return Localized error message.
9292     * @hide
9293     */
9294    @SystemApi
9295    public CharSequence getPrintingDisabledReason() {
9296        try {
9297            return mService.getPrintingDisabledReason();
9298        } catch (RemoteException re) {
9299            throw re.rethrowFromSystemServer();
9300        }
9301    }
9302}
9303