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