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