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