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