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