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