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