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