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