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