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