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