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