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