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