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