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