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