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