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