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