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