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