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