DevicePolicyManager.java revision d86d58cd010b087d6d481062f84c894e0ced7bbc
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.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
21import android.annotation.SystemApi;
22import android.app.Activity;
23import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.pm.ActivityInfo;
28import android.content.pm.PackageManager;
29import android.content.pm.ResolveInfo;
30import android.graphics.Bitmap;
31import android.net.ProxyInfo;
32import android.os.Bundle;
33import android.os.Handler;
34import android.os.PersistableBundle;
35import android.os.Process;
36import android.os.RemoteCallback;
37import android.os.RemoteException;
38import android.os.ServiceManager;
39import android.os.UserHandle;
40import android.os.UserManager;
41import android.provider.Settings;
42import android.security.Credentials;
43import android.service.restrictions.RestrictionsReceiver;
44import android.util.Log;
45
46import com.android.org.conscrypt.TrustedCertificateStore;
47
48import org.xmlpull.v1.XmlPullParserException;
49
50import java.io.ByteArrayInputStream;
51import java.io.IOException;
52import java.net.InetSocketAddress;
53import java.net.Proxy;
54import java.security.KeyFactory;
55import java.security.PrivateKey;
56import java.security.cert.Certificate;
57import java.security.cert.CertificateException;
58import java.security.cert.CertificateFactory;
59import java.security.cert.X509Certificate;
60import java.security.spec.PKCS8EncodedKeySpec;
61import java.security.spec.InvalidKeySpecException;
62import java.security.NoSuchAlgorithmException;
63import java.util.ArrayList;
64import java.util.Collections;
65import java.util.List;
66
67/**
68 * Public interface for managing policies enforced on a device. Most clients of this class must be
69 * registered with the system as a
70 * <a href="{@docRoot}guide/topics/admin/device-admin.html">device administrator</a>. Additionally,
71 * a device administrator may be registered as either a profile or device owner. A given method is
72 * accessible to all device administrators unless the documentation for that method specifies that
73 * it is restricted to either device or profile owners.
74 *
75 * <div class="special reference">
76 * <h3>Developer Guides</h3>
77 * <p>For more information about managing policies for device administration, read the
78 * <a href="{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a>
79 * developer guide.</p>
80 * </div>
81 */
82public class DevicePolicyManager {
83    private static String TAG = "DevicePolicyManager";
84
85    private final Context mContext;
86    private final IDevicePolicyManager mService;
87
88    private DevicePolicyManager(Context context, Handler handler) {
89        mContext = context;
90        mService = IDevicePolicyManager.Stub.asInterface(
91                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
92    }
93
94    /** @hide */
95    public static DevicePolicyManager create(Context context, Handler handler) {
96        DevicePolicyManager me = new DevicePolicyManager(context, handler);
97        return me.mService != null ? me : null;
98    }
99
100    /**
101     * Activity action: Starts the provisioning flow which sets up a managed profile.
102     *
103     * <p>A managed profile allows data separation for example for the usage of a
104     * device as a personal and corporate device. The user which provisioning is started from and
105     * the managed profile share a launcher.
106     *
107     * <p>This intent will typically be sent by a mobile device management application (MDM).
108     * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
109     * control over the profile.
110     *
111     * In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
112     * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
113     * As of {@link android.os.Build.VERSION_CODES#MNC}, it should contain the extra
114     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
115     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
116     *
117     * <p> When managed provisioning has completed, broadcasts are sent to the application specified
118     * in the provisioning intent. The
119     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
120     * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
121     * the primary profile.
122     *
123     * <p> If provisioning fails, the managedProfile is removed so the device returns to its
124     * previous state.
125     *
126     * <p>Input: Nothing.</p>
127     * <p>Output: Nothing</p>
128     */
129    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
130    public static final String ACTION_PROVISION_MANAGED_PROFILE
131        = "android.app.action.PROVISION_MANAGED_PROFILE";
132
133    /**
134     * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that allows
135     * a mobile device management application that starts managed profile provisioning to pass data
136     * to itself on the managed profile when provisioning completes. The mobile device management
137     * application sends this extra in an intent with the action
138     * {@link #ACTION_PROVISION_MANAGED_PROFILE} and receives it in
139     * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
140     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
141     * during the managed profile provisioning.
142     */
143    public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
144            "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
145
146    /**
147     * A String extra holding the package name of the mobile device management application that
148     * will be set as the profile owner or device owner.
149     *
150     * <p>If an application starts provisioning directly via an intent with action
151     * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
152     * application that started provisioning. The package will be set as profile owner in that case.
153     *
154     * <p>This package is set as device owner when device owner provisioning is started by an NFC
155     * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
156     *
157     * <p> When this extra is set, the application must have exactly one device admin receiver.
158     * This receiver will be set as the profile or device owner and active admin.</p>
159
160     * @see DeviceAdminReceiver
161     * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
162     * supported.
163     */
164    @Deprecated
165    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
166        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
167
168    /**
169     * A ComponentName extra indicating the device admin receiver of the mobile device management
170     * application that will be set as the profile owner or device owner and active admin.
171     *
172     * <p>If an application starts provisioning directly via an intent with action
173     * {@link #ACTION_PROVISION_MANAGED_PROFILE} the package name of this component has to match the
174     * package name of the application that started provisioning.
175     *
176     * <p>This component is set as device owner and active admin when device owner provisioning is
177     * started by an NFC message containing an NFC record with MIME type
178     * {@link #MIME_TYPE_PROVISIONING_NFC_V2}. For the NFC record, the component name should be
179     * flattened to a string, via {@link ComponentName#flattenToShortString()}.
180     *
181     * @see DeviceAdminReceiver
182     */
183    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
184        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
185
186    /**
187     * An {@link android.accounts.Account} extra holding the account to migrate during managed
188     * profile provisioning. If the account supplied is present in the primary user, it will be
189     * copied, along with its credentials to the managed profile and removed from the primary user.
190     *
191     * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}.
192     */
193
194    public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
195        = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
196
197    /**
198     * A String extra that, holds the email address of the account which a managed profile is
199     * created for. Used with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
200     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}.
201     *
202     * <p> This extra is part of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}.
203     *
204     * <p> If the {@link #ACTION_PROVISION_MANAGED_PROFILE} intent that starts managed provisioning
205     * contains this extra, it is forwarded in the
206     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} intent to the mobile
207     * device management application that was set as the profile owner during provisioning.
208     * It is usually used to avoid that the user has to enter their email address twice.
209     */
210    public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
211        = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
212
213    /**
214     * A Boolean extra that can be used by the mobile device management application to skip the
215     * disabling of system apps during provisioning when set to <code>true</code>.
216     *
217     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
218     * provisioning via an NFC bump.
219     */
220    public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
221            "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
222
223    /**
224     * A String extra holding the time zone {@link android.app.AlarmManager} that the device
225     * will be set to.
226     *
227     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
228     * provisioning via an NFC bump.
229     */
230    public static final String EXTRA_PROVISIONING_TIME_ZONE
231        = "android.app.extra.PROVISIONING_TIME_ZONE";
232
233    /**
234     * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
235     * {@link android.app.AlarmManager}.
236     *
237     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
238     * provisioning via an NFC bump.
239     */
240    public static final String EXTRA_PROVISIONING_LOCAL_TIME
241        = "android.app.extra.PROVISIONING_LOCAL_TIME";
242
243    /**
244     * A String extra holding the {@link java.util.Locale} that the device will be set to.
245     * Format: xx_yy, where xx is the language code, and yy the country code.
246     *
247     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
248     * provisioning via an NFC bump.
249     */
250    public static final String EXTRA_PROVISIONING_LOCALE
251        = "android.app.extra.PROVISIONING_LOCALE";
252
253    /**
254     * A String extra holding the ssid of the wifi network that should be used during nfc device
255     * owner provisioning for downloading the mobile device management application.
256     *
257     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
258     * provisioning via an NFC bump.
259     */
260    public static final String EXTRA_PROVISIONING_WIFI_SSID
261        = "android.app.extra.PROVISIONING_WIFI_SSID";
262
263    /**
264     * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
265     * is hidden or not.
266     *
267     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
268     * provisioning via an NFC bump.
269     */
270    public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
271        = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
272
273    /**
274     * A String extra indicating the security type of the wifi network in
275     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
276     *
277     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
278     * provisioning via an NFC bump.
279     */
280    public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
281        = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
282
283    /**
284     * A String extra holding the password of the wifi network in
285     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
286     *
287     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
288     * provisioning via an NFC bump.
289     */
290    public static final String EXTRA_PROVISIONING_WIFI_PASSWORD
291        = "android.app.extra.PROVISIONING_WIFI_PASSWORD";
292
293    /**
294     * A String extra holding the proxy host for the wifi network in
295     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
296     *
297     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
298     * provisioning via an NFC bump.
299     */
300    public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
301        = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
302
303    /**
304     * An int extra holding the proxy port for the wifi network in
305     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
306     *
307     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
308     * provisioning via an NFC bump.
309     */
310    public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
311        = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
312
313    /**
314     * A String extra holding the proxy bypass for the wifi network in
315     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
316     *
317     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
318     * provisioning via an NFC bump.
319     */
320    public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
321        = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
322
323    /**
324     * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
325     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
326     *
327     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
328     * provisioning via an NFC bump.
329     */
330    public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
331        = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
332
333    /**
334     * A String extra holding a url that specifies the download location of the device admin
335     * package. When not provided it is assumed that the device admin package is already installed.
336     *
337     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
338     * provisioning via an NFC bump.
339     */
340    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
341        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
342
343    /**
344     * An int extra holding a minimum required version code for the device admin package. If the
345     * device admin is already installed on the device, it will only be re-downloaded from
346     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
347     * installed package is less than this version code.
348     *
349     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
350     * provisioning via an NFC bump.
351     */
352    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
353        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
354
355    /**
356     * A String extra holding a http cookie header which should be used in the http request to the
357     * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
358     *
359     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
360     * provisioning via an NFC bump.
361     */
362    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
363        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
364
365    /**
366     * A String extra holding the URL-safe base64 encoded SHA-1 checksum of the file at download
367     * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
368     *
369     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_CERTIFICATE_CHECKSUM} should be
370     * present. The provided checksum should match the checksum of the file at the download
371     * location. If the checksum doesn't match an error will be shown to the user and the user will
372     * be asked to factory reset the device.
373     *
374     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
375     * provisioning via an NFC bump.
376     */
377    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
378        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
379
380    /**
381     * A String extra holding the URL-safe base64 encoded SHA-1 checksum of any certificate of the
382     * android package archive at the download location specified in {@link
383     * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
384     *
385     * <p>The certificates of an android package archive can be obtained using
386     * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
387     * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
388     *
389     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} should be
390     * present. The provided checksum should match the checksum of any certificate of the file at
391     * the download location. If the checksum does not match an error will be shown to the user and
392     * the user will be asked to factory reset the device.
393     *
394     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
395     * provisioning via an NFC bump.
396     */
397    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_CERTIFICATE_CHECKSUM
398        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_CERTIFICATE_CHECKSUM";
399
400    /**
401     * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
402     * has completed successfully.
403     *
404     * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
405     * intent (@see #ACTION_PROVISION_MANAGED_PROFILE).
406     *
407     * <p>This intent will contain the extra {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} which
408     * corresponds to the account requested to be migrated at provisioning time, if any.
409     */
410    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
411    public static final String ACTION_MANAGED_PROFILE_PROVISIONED
412        = "android.app.action.MANAGED_PROFILE_PROVISIONED";
413
414    /**
415     * A boolean extra indicating whether device encryption can be skipped as part of Device Owner
416     * provisioning.
417     *
418     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
419     * provisioning via an NFC bump.
420     */
421    public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
422             "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
423
424    /**
425     * On devices managed by a device owner app, a {@link ComponentName} extra indicating the
426     * component of the application that is temporarily granted device owner privileges during
427     * device initialization and profile owner privileges during secondary user initialization.
428     *
429     * <p>
430     * It can also be used in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts
431     * device owner provisioning via an NFC bump. For the NFC record, it should be flattened to a
432     * string first.
433     *
434     * @see ComponentName#flattenToShortString()
435     */
436    public static final String EXTRA_PROVISIONING_DEVICE_INITIALIZER_COMPONENT_NAME
437        = "android.app.extra.PROVISIONING_DEVICE_INITIALIZER_COMPONENT_NAME";
438
439    /**
440     * A String extra holding an http url that specifies the download location of the device
441     * initializer package. When not provided it is assumed that the device initializer package is
442     * already installed.
443     *
444     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
445     * provisioning via an NFC bump.
446     */
447    public static final String EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_LOCATION
448        = "android.app.extra.PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_LOCATION";
449
450    /**
451     * An int extra holding a minimum required version code for the device initializer package.
452     * If the initializer is already installed on the device, it will only be re-downloaded from
453     * {@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_LOCATION} if the version of
454     * the installed package is less than this version code.
455     *
456     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
457     * provisioning via an NFC bump.
458     */
459    public static final String EXTRA_PROVISIONING_DEVICE_INITIALIZER_MINIMUM_VERSION_CODE
460        = "android.app.extra.PROVISIONING_DEVICE_INITIALIZER_MINIMUM_VERSION_CODE";
461
462    /**
463     * A String extra holding a http cookie header which should be used in the http request to the
464     * url specified in {@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_LOCATION}.
465     *
466     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
467     * provisioning via an NFC bump.
468     */
469    public static final String EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_COOKIE_HEADER
470        = "android.app.extra.PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_COOKIE_HEADER";
471
472    /**
473     * A String extra holding the URL-safe base64 encoded SHA-1 checksum of the file at download
474     * location specified in
475     * {@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_LOCATION}.
476     *
477     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_CERTIFICATE_CHECKSUM}
478     * should be present. The provided checksum should match the checksum of the file at the
479     * download location. If the checksum doesn't match an error will be shown to the user and the
480     * user will be asked to factory reset the device.
481     *
482     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
483     * provisioning via an NFC bump.
484     */
485    public static final String EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_CHECKSUM
486        = "android.app.extra.PROVISIONING_DEVICE_INITIALIZER_PACKAGE_CHECKSUM";
487
488    /**
489     * A String extra holding the URL-safe base64 encoded SHA-1 checksum of any certificate of the
490     * android package archive at the download location specified in {@link
491     * #EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_LOCATION}.
492     *
493     * <p>The certificates of an android package archive can be obtained using
494     * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
495     * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
496     *
497     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_CHECKSUM}
498     * should be present. The provided checksum should match the checksum of any certificate of the
499     * file at the download location. If the checksum doesn't match an error will be shown to the
500     * user and the user will be asked to factory reset the device.
501     *
502     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
503     * provisioning via an NFC bump.
504     */
505    public static final String EXTRA_PROVISIONING_DEVICE_INITIALIZER_CERTIFICATE_CHECKSUM
506        = "android.app.extra.PROVISIONING_DEVICE_INITIALIZER_CERTIFICATE_CHECKSUM";
507
508    /**
509     * A String extra holding the MAC address of the Bluetooth device to connect to with status
510     * updates during provisioning.
511     *
512     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
513     * provisioning via an NFC bump.
514     */
515    public static final String EXTRA_PROVISIONING_BT_MAC_ADDRESS
516            = "android.app.extra.PROVISIONING_BT_MAC_ADDRESS";
517
518    /**
519     * A String extra holding the Bluetooth service UUID on the device to connect to with status
520     * updates during provisioning.
521     *
522     * <p>This value must be specified when {@code #EXTRA_PROVISIONING_BT_MAC_ADDRESS} is present.
523     *
524     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
525     * provisioning via an NFC bump.
526     */
527    public static final String EXTRA_PROVISIONING_BT_UUID
528            = "android.app.extra.PROVISIONING_BT_UUID";
529
530    /**
531     * A String extra holding a unique identifier used to identify the device connecting over
532     * Bluetooth. This identifier will be part of every status message sent to the remote device.
533     *
534     * <p>This value must be specified when {@code #EXTRA_PROVISIONING_BT_MAC_ADDRESS} is present.
535     *
536     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
537     * provisioning via an NFC bump.
538     */
539    public static final String EXTRA_PROVISIONING_BT_DEVICE_ID
540            = "android.app.extra.PROVISIONING_BT_DEVICE_ID";
541
542    /**
543     * A Boolean extra that that will cause a provisioned device to temporarily proxy network
544     * traffic over Bluetooth. When a Wi-Fi network is available, the network proxy will stop.
545     *
546     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
547     * provisioning via an NFC bump.
548     */
549    public static final String EXTRA_PROVISIONING_BT_USE_PROXY
550            = "android.app.extra.PROVISIONING_BT_USE_PROXY";
551
552    /**
553     * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
554     * holds data needed by the system to wipe factory reset protection. The data needed to wipe
555     * the device depend on the installed factory reset protection implementation. For example,
556     * if an account is needed to unlock a device, this extra may contain data used to
557     * authenticate that account.
558     *
559     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner
560     * provisioning via an NFC bump.
561     */
562    public static final String EXTRA_PROVISIONING_RESET_PROTECTION_PARAMETERS
563            = "android.app.extra.PROVISIONING_RESET_PROTECTION_PARAMETERS";
564
565    /**
566     * This MIME type is used for starting the Device Owner provisioning that does not require
567     * provisioning features introduced in Android API level
568     * {@link android.os.Build.VERSION_CODES#MNC} or later levels.
569     *
570     * <p>For more information about the provisioning process see
571     * {@link #MIME_TYPE_PROVISIONING_NFC_V2}.
572     *
573     * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
574     * contains the following properties:
575     * <ul>
576     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
577     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
578     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
579     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
580     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
581     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
582     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
583     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
584     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
585     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
586     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
587     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
588     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
589     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
590     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li></ul>
591     *
592     * <p>
593     * As of {@link android.os.Build.VERSION_CODES#MNC}, the properties should contain
594     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
595     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
596     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
597     *
598     * @see #MIME_TYPE_PROVISIONING_NFC_V2
599     *
600     */
601    public static final String MIME_TYPE_PROVISIONING_NFC
602        = "application/com.android.managedprovisioning";
603
604
605    /**
606     * This MIME type is used for starting the Device Owner provisioning that requires
607     * new provisioning features introduced in API version
608     * {@link android.os.Build.VERSION_CODES#MNC} in addition to those supported in earlier
609     * versions.
610     *
611     * <p>During device owner provisioning a device admin app is set as the owner of the device.
612     * A device owner has full control over the device. The device owner can not be modified by the
613     * user and the only way of resetting the device is if the device owner app calls a factory
614     * reset.
615     *
616     * <p> A typical use case would be a device that is owned by a company, but used by either an
617     * employee or client.
618     *
619     * <p> The NFC message should be sent to an unprovisioned device.
620     *
621     * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
622     * contains the following properties in addition to properties listed at
623     * {@link #MIME_TYPE_PROVISIONING_NFC}:
624     * <ul>
625     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
626     * <li>{@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_COMPONENT_NAME}, optional</li>
627     * <li>{@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
628     * <li>{@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
629     * <li>{@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_PACKAGE_CHECKSUM}, optional</li>
630     * <li>{@link #EXTRA_PROVISIONING_DEVICE_INITIALIZER_MINIMUM_VERSION_CODE}, optional</li>
631     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}.
632     * Replaces {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}. The value of the property
633     * should be converted to a String via
634     * {@link android.content.ComponentName#flattenToString()}</li>
635     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE}, optional</li>
636     * <li>{@link #EXTRA_PROVISIONING_BT_MAC_ADDRESS}, optional</li>
637     * <li>{@link #EXTRA_PROVISIONING_BT_UUID}, optional</li>
638     * <li>{@link #EXTRA_PROVISIONING_BT_DEVICE_ID}, optional</li>
639     * <li>{@link #EXTRA_PROVISIONING_BT_USE_PROXY}, optional</li></ul>
640     *
641     * <p> When device owner provisioning has completed, an intent of the type
642     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcasted to the
643     * device owner.
644     *
645     * <p>
646     * If provisioning fails, the device is factory reset.
647     *
648     * <p>Input: Nothing.</p>
649     * <p>Output: Nothing</p>
650     */
651    public static final String MIME_TYPE_PROVISIONING_NFC_V2
652            = "application/com.android.managedprovisioning.v2";
653
654    /**
655     * Activity action: ask the user to add a new device administrator to the system.
656     * The desired policy is the ComponentName of the policy in the
657     * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
658     * bring the user through adding the device administrator to the system (or
659     * allowing them to reject it).
660     *
661     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
662     * field to provide the user with additional explanation (in addition
663     * to your component's description) about what is being added.
664     *
665     * <p>If your administrator is already active, this will ordinarily return immediately (without
666     * user intervention).  However, if your administrator has been updated and is requesting
667     * additional uses-policy flags, the user will be presented with the new list.  New policies
668     * will not be available to the updated administrator until the user has accepted the new list.
669     */
670    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
671    public static final String ACTION_ADD_DEVICE_ADMIN
672            = "android.app.action.ADD_DEVICE_ADMIN";
673
674    /**
675     * @hide
676     * Activity action: ask the user to add a new device administrator as the profile owner
677     * for this user. Only system apps can launch this intent.
678     *
679     * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
680     * extra field. This will invoke a UI to bring the user through adding the profile owner admin
681     * to remotely control restrictions on the user.
682     *
683     * <p>The intent must be invoked via {@link Activity#startActivityForResult()} to receive the
684     * result of whether or not the user approved the action. If approved, the result will
685     * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
686     * as a profile owner.
687     *
688     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
689     * field to provide the user with additional explanation (in addition
690     * to your component's description) about what is being added.
691     *
692     * <p>If there is already a profile owner active or the caller is not a system app, the
693     * operation will return a failure result.
694     */
695    @SystemApi
696    public static final String ACTION_SET_PROFILE_OWNER
697            = "android.app.action.SET_PROFILE_OWNER";
698
699    /**
700     * Protected broadcast action that will be sent to managed provisioning to notify it that a
701     * status update has been reported by the device initializer. The status update will be
702     * reported to the remote setup device over Bluetooth.
703     *
704     * <p>Broadcasts with this action must supply a
705     * {@linkplain DeviceInitializerStatus#FLAG_STATUS_CUSTOM custom} status code in the
706     * {@link EXTRA_DEVICE_INITIALIZER_STATUS_CODE} extra.
707     *
708     * <p>Broadcasts may optionally contain a description in the
709     * {@link EXTRA_DEVICE_INITIALIZER_STATUS_DESCRIPTION} extra.
710     * @hide
711     */
712    @SystemApi
713    public static final String ACTION_SEND_DEVICE_INITIALIZER_STATUS
714            = "android.app.action.SEND_DEVICE_INITIALIZER_STATUS";
715
716    /**
717     * An integer extra that contains the status code that defines a status update. This extra must
718     * sent as part of a broadcast with an action of {@code ACTION_SEND_DEVICE_INITIALIZER_STATUS}.
719     *
720     * <p>The status code sent with this extra must be a custom status code as defined by
721     * {@link DeviceInitializerStatus#FLAG_STATUS_CUSTOM}.
722     * @hide
723     */
724    @SystemApi
725    public static final String EXTRA_DEVICE_INITIALIZER_STATUS_CODE
726            = "android.app.extra.DEVICE_INITIALIZER_STATUS_CODE";
727
728    /**
729     * A {@code String} extra that contains an optional description accompanying a status update.
730     * This extra my be sent as part of a broadcast with an action of
731     * {@code ACTION_SEND_DEVICE_INITIALIZER_STATUS}.
732     * @hide
733     */
734    @SystemApi
735    public static final String EXTRA_DEVICE_INITIALIZER_STATUS_DESCRIPTION
736            = "android.app.extra.DEVICE_INITIALIZER_STATUS_DESCRIPTION";
737
738    /**
739     * @hide
740     * Name of the profile owner admin that controls the user.
741     */
742    @SystemApi
743    public static final String EXTRA_PROFILE_OWNER_NAME
744            = "android.app.extra.PROFILE_OWNER_NAME";
745
746    /**
747     * Activity action: send when any policy admin changes a policy.
748     * This is generally used to find out when a new policy is in effect.
749     *
750     * @hide
751     */
752    public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
753            = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
754
755    /**
756     * The ComponentName of the administrator component.
757     *
758     * @see #ACTION_ADD_DEVICE_ADMIN
759     */
760    public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
761
762    /**
763     * An optional CharSequence providing additional explanation for why the
764     * admin is being added.
765     *
766     * @see #ACTION_ADD_DEVICE_ADMIN
767     */
768    public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
769
770    /**
771     * Activity action: have the user enter a new password. This activity should
772     * be launched after using {@link #setPasswordQuality(ComponentName, int)},
773     * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
774     * enter a new password that meets the current requirements. You can use
775     * {@link #isActivePasswordSufficient()} to determine whether you need to
776     * have the user select a new password in order to meet the current
777     * constraints. Upon being resumed from this activity, you can check the new
778     * password characteristics to see if they are sufficient.
779     */
780    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
781    public static final String ACTION_SET_NEW_PASSWORD
782            = "android.app.action.SET_NEW_PASSWORD";
783
784    /**
785     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
786     * the parent profile to access intents sent from the managed profile.
787     * That is, when an app in the managed profile calls
788     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
789     * matching activity in the parent profile.
790     */
791    public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
792
793    /**
794     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
795     * the managed profile to access intents sent from the parent profile.
796     * That is, when an app in the parent profile calls
797     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
798     * matching activity in the managed profile.
799     */
800    public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
801
802    /**
803     * Broadcast action: notify that a new local system update policy has been set by the device
804     * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
805     */
806    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
807    public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
808            = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
809
810    /**
811     * Permission policy to prompt user for new permission requests for runtime permissions.
812     * Already granted or denied permissions are not affected by this.
813     */
814    public static final int PERMISSION_POLICY_PROMPT = 0;
815
816    /**
817     * Permission policy to always grant new permission requests for runtime permissions.
818     * Already granted or denied permissions are not affected by this.
819     */
820    public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
821
822    /**
823     * Permission policy to always deny new permission requests for runtime permissions.
824     * Already granted or denied permissions are not affected by this.
825     */
826    public static final int PERMISSION_POLICY_AUTO_DENY = 2;
827
828
829    /**
830     * Return true if the given administrator component is currently
831     * active (enabled) in the system.
832     */
833    public boolean isAdminActive(ComponentName who) {
834        return isAdminActiveAsUser(who, UserHandle.myUserId());
835    }
836
837    /**
838     * @see #isAdminActive(ComponentName)
839     * @hide
840     */
841    public boolean isAdminActiveAsUser(ComponentName who, int userId) {
842        if (mService != null) {
843            try {
844                return mService.isAdminActive(who, userId);
845            } catch (RemoteException e) {
846                Log.w(TAG, "Failed talking with device policy service", e);
847            }
848        }
849        return false;
850    }
851    /**
852     * Return true if the given administrator component is currently being removed
853     * for the user.
854     * @hide
855     */
856    public boolean isRemovingAdmin(ComponentName who, int userId) {
857        if (mService != null) {
858            try {
859                return mService.isRemovingAdmin(who, userId);
860            } catch (RemoteException e) {
861                Log.w(TAG, "Failed talking with device policy service", e);
862            }
863        }
864        return false;
865    }
866
867
868    /**
869     * Return a list of all currently active device administrator's component
870     * names.  Note that if there are no administrators than null may be
871     * returned.
872     */
873    public List<ComponentName> getActiveAdmins() {
874        return getActiveAdminsAsUser(UserHandle.myUserId());
875    }
876
877    /**
878     * @see #getActiveAdmins()
879     * @hide
880     */
881    public List<ComponentName> getActiveAdminsAsUser(int userId) {
882        if (mService != null) {
883            try {
884                return mService.getActiveAdmins(userId);
885            } catch (RemoteException e) {
886                Log.w(TAG, "Failed talking with device policy service", e);
887            }
888        }
889        return null;
890    }
891
892    /**
893     * Used by package administration code to determine if a package can be stopped
894     * or uninstalled.
895     * @hide
896     */
897    public boolean packageHasActiveAdmins(String packageName) {
898        if (mService != null) {
899            try {
900                return mService.packageHasActiveAdmins(packageName, UserHandle.myUserId());
901            } catch (RemoteException e) {
902                Log.w(TAG, "Failed talking with device policy service", e);
903            }
904        }
905        return false;
906    }
907
908    /**
909     * Remove a current administration component.  This can only be called
910     * by the application that owns the administration component; if you
911     * try to remove someone else's component, a security exception will be
912     * thrown.
913     */
914    public void removeActiveAdmin(ComponentName who) {
915        if (mService != null) {
916            try {
917                mService.removeActiveAdmin(who, UserHandle.myUserId());
918            } catch (RemoteException e) {
919                Log.w(TAG, "Failed talking with device policy service", e);
920            }
921        }
922    }
923
924    /**
925     * Returns true if an administrator has been granted a particular device policy.  This can
926     * be used to check if the administrator was activated under an earlier set of policies,
927     * but requires additional policies after an upgrade.
928     *
929     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  Must be
930     * an active administrator, or an exception will be thrown.
931     * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
932     */
933    public boolean hasGrantedPolicy(ComponentName admin, int usesPolicy) {
934        if (mService != null) {
935            try {
936                return mService.hasGrantedPolicy(admin, usesPolicy, UserHandle.myUserId());
937            } catch (RemoteException e) {
938                Log.w(TAG, "Failed talking with device policy service", e);
939            }
940        }
941        return false;
942    }
943
944    /**
945     * Constant for {@link #setPasswordQuality}: the policy has no requirements
946     * for the password.  Note that quality constants are ordered so that higher
947     * values are more restrictive.
948     */
949    public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
950
951    /**
952     * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
953     * recognition technology.  This implies technologies that can recognize the identity of
954     * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
955     * Note that quality constants are ordered so that higher values are more restrictive.
956     */
957    public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
958
959    /**
960     * Constant for {@link #setPasswordQuality}: the policy requires some kind
961     * of password, but doesn't care what it is.  Note that quality constants
962     * are ordered so that higher values are more restrictive.
963     */
964    public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
965
966    /**
967     * Constant for {@link #setPasswordQuality}: the user must have entered a
968     * password containing at least numeric characters.  Note that quality
969     * constants are ordered so that higher values are more restrictive.
970     */
971    public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
972
973    /**
974     * Constant for {@link #setPasswordQuality}: the user must have entered a
975     * password containing at least numeric characters with no repeating (4444)
976     * or ordered (1234, 4321, 2468) sequences.  Note that quality
977     * constants are ordered so that higher values are more restrictive.
978     */
979    public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
980
981    /**
982     * Constant for {@link #setPasswordQuality}: the user must have entered a
983     * password containing at least alphabetic (or other symbol) characters.
984     * Note that quality constants are ordered so that higher values are more
985     * restrictive.
986     */
987    public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
988
989    /**
990     * Constant for {@link #setPasswordQuality}: the user must have entered a
991     * password containing at least <em>both></em> numeric <em>and</em>
992     * alphabetic (or other symbol) characters.  Note that quality constants are
993     * ordered so that higher values are more restrictive.
994     */
995    public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
996
997    /**
998     * Constant for {@link #setPasswordQuality}: the user must have entered a
999     * password containing at least a letter, a numerical digit and a special
1000     * symbol, by default. With this password quality, passwords can be
1001     * restricted to contain various sets of characters, like at least an
1002     * uppercase letter, etc. These are specified using various methods,
1003     * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
1004     * that quality constants are ordered so that higher values are more
1005     * restrictive.
1006     */
1007    public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
1008
1009    /**
1010     * Called by an application that is administering the device to set the
1011     * password restrictions it is imposing.  After setting this, the user
1012     * will not be able to enter a new password that is not at least as
1013     * restrictive as what has been set.  Note that the current password
1014     * will remain until the user has set a new one, so the change does not
1015     * take place immediately.  To prompt the user for a new password, use
1016     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value.
1017     *
1018     * <p>Quality constants are ordered so that higher values are more restrictive;
1019     * thus the highest requested quality constant (between the policy set here,
1020     * the user's preference, and any other considerations) is the one that
1021     * is in effect.
1022     *
1023     * <p>The calling device admin must have requested
1024     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1025     * this method; if it has not, a security exception will be thrown.
1026     *
1027     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1028     * @param quality The new desired quality.  One of
1029     * {@link #PASSWORD_QUALITY_UNSPECIFIED}, {@link #PASSWORD_QUALITY_SOMETHING},
1030     * {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX},
1031     * {@link #PASSWORD_QUALITY_ALPHABETIC}, {@link #PASSWORD_QUALITY_ALPHANUMERIC}
1032     * or {@link #PASSWORD_QUALITY_COMPLEX}.
1033     */
1034    public void setPasswordQuality(ComponentName admin, int quality) {
1035        if (mService != null) {
1036            try {
1037                mService.setPasswordQuality(admin, quality);
1038            } catch (RemoteException e) {
1039                Log.w(TAG, "Failed talking with device policy service", e);
1040            }
1041        }
1042    }
1043
1044    /**
1045     * Retrieve the current minimum password quality for all admins of this user
1046     * and its profiles or a particular one.
1047     * @param admin The name of the admin component to check, or null to aggregate
1048     * all admins.
1049     */
1050    public int getPasswordQuality(ComponentName admin) {
1051        return getPasswordQuality(admin, UserHandle.myUserId());
1052    }
1053
1054    /** @hide per-user version */
1055    public int getPasswordQuality(ComponentName admin, int userHandle) {
1056        if (mService != null) {
1057            try {
1058                return mService.getPasswordQuality(admin, userHandle);
1059            } catch (RemoteException e) {
1060                Log.w(TAG, "Failed talking with device policy service", e);
1061            }
1062        }
1063        return PASSWORD_QUALITY_UNSPECIFIED;
1064    }
1065
1066    /**
1067     * Called by an application that is administering the device to set the
1068     * minimum allowed password length.  After setting this, the user
1069     * will not be able to enter a new password that is not at least as
1070     * restrictive as what has been set.  Note that the current password
1071     * will remain until the user has set a new one, so the change does not
1072     * take place immediately.  To prompt the user for a new password, use
1073     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value.  This
1074     * constraint is only imposed if the administrator has also requested either
1075     * {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX},
1076     * {@link #PASSWORD_QUALITY_ALPHABETIC}, {@link #PASSWORD_QUALITY_ALPHANUMERIC},
1077     * or {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}.
1078     *
1079     * <p>The calling device admin must have requested
1080     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1081     * this method; if it has not, a security exception will be thrown.
1082     *
1083     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1084     * @param length The new desired minimum password length.  A value of 0
1085     * means there is no restriction.
1086     */
1087    public void setPasswordMinimumLength(ComponentName admin, int length) {
1088        if (mService != null) {
1089            try {
1090                mService.setPasswordMinimumLength(admin, length);
1091            } catch (RemoteException e) {
1092                Log.w(TAG, "Failed talking with device policy service", e);
1093            }
1094        }
1095    }
1096
1097    /**
1098     * Retrieve the current minimum password length for all admins of this
1099     * user and its profiles or a particular one.
1100     * @param admin The name of the admin component to check, or null to aggregate
1101     * all admins.
1102     */
1103    public int getPasswordMinimumLength(ComponentName admin) {
1104        return getPasswordMinimumLength(admin, UserHandle.myUserId());
1105    }
1106
1107    /** @hide per-user version */
1108    public int getPasswordMinimumLength(ComponentName admin, int userHandle) {
1109        if (mService != null) {
1110            try {
1111                return mService.getPasswordMinimumLength(admin, userHandle);
1112            } catch (RemoteException e) {
1113                Log.w(TAG, "Failed talking with device policy service", e);
1114            }
1115        }
1116        return 0;
1117    }
1118
1119    /**
1120     * Called by an application that is administering the device to set the
1121     * minimum number of upper case letters required in the password. After
1122     * setting this, the user will not be able to enter a new password that is
1123     * not at least as restrictive as what has been set. Note that the current
1124     * password will remain until the user has set a new one, so the change does
1125     * not take place immediately. To prompt the user for a new password, use
1126     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1127     * constraint is only imposed if the administrator has also requested
1128     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1129     * default value is 0.
1130     * <p>
1131     * The calling device admin must have requested
1132     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1133     * this method; if it has not, a security exception will be thrown.
1134     *
1135     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1136     *            with.
1137     * @param length The new desired minimum number of upper case letters
1138     *            required in the password. A value of 0 means there is no
1139     *            restriction.
1140     */
1141    public void setPasswordMinimumUpperCase(ComponentName admin, int length) {
1142        if (mService != null) {
1143            try {
1144                mService.setPasswordMinimumUpperCase(admin, length);
1145            } catch (RemoteException e) {
1146                Log.w(TAG, "Failed talking with device policy service", e);
1147            }
1148        }
1149    }
1150
1151    /**
1152     * Retrieve the current number of upper case letters required in the
1153     * password for all admins of this user and its profiles or a particular one.
1154     * This is the same value as set by
1155     * {#link {@link #setPasswordMinimumUpperCase(ComponentName, int)}
1156     * and only applies when the password quality is
1157     * {@link #PASSWORD_QUALITY_COMPLEX}.
1158     *
1159     * @param admin The name of the admin component to check, or null to
1160     *            aggregate all admins.
1161     * @return The minimum number of upper case letters required in the
1162     *         password.
1163     */
1164    public int getPasswordMinimumUpperCase(ComponentName admin) {
1165        return getPasswordMinimumUpperCase(admin, UserHandle.myUserId());
1166    }
1167
1168    /** @hide per-user version */
1169    public int getPasswordMinimumUpperCase(ComponentName admin, int userHandle) {
1170        if (mService != null) {
1171            try {
1172                return mService.getPasswordMinimumUpperCase(admin, userHandle);
1173            } catch (RemoteException e) {
1174                Log.w(TAG, "Failed talking with device policy service", e);
1175            }
1176        }
1177        return 0;
1178    }
1179
1180    /**
1181     * Called by an application that is administering the device to set the
1182     * minimum number of lower case letters required in the password. After
1183     * setting this, the user will not be able to enter a new password that is
1184     * not at least as restrictive as what has been set. Note that the current
1185     * password will remain until the user has set a new one, so the change does
1186     * not take place immediately. To prompt the user for a new password, use
1187     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1188     * constraint is only imposed if the administrator has also requested
1189     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1190     * default value is 0.
1191     * <p>
1192     * 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
1197     *            with.
1198     * @param length The new desired minimum number of lower case letters
1199     *            required in the password. A value of 0 means there is no
1200     *            restriction.
1201     */
1202    public void setPasswordMinimumLowerCase(ComponentName admin, int length) {
1203        if (mService != null) {
1204            try {
1205                mService.setPasswordMinimumLowerCase(admin, length);
1206            } catch (RemoteException e) {
1207                Log.w(TAG, "Failed talking with device policy service", e);
1208            }
1209        }
1210    }
1211
1212    /**
1213     * Retrieve the current number of lower case letters required in the
1214     * password for all admins of this user and its profiles or a particular one.
1215     * This is the same value as set by
1216     * {#link {@link #setPasswordMinimumLowerCase(ComponentName, int)}
1217     * and only applies when the password quality is
1218     * {@link #PASSWORD_QUALITY_COMPLEX}.
1219     *
1220     * @param admin The name of the admin component to check, or null to
1221     *            aggregate all admins.
1222     * @return The minimum number of lower case letters required in the
1223     *         password.
1224     */
1225    public int getPasswordMinimumLowerCase(ComponentName admin) {
1226        return getPasswordMinimumLowerCase(admin, UserHandle.myUserId());
1227    }
1228
1229    /** @hide per-user version */
1230    public int getPasswordMinimumLowerCase(ComponentName admin, int userHandle) {
1231        if (mService != null) {
1232            try {
1233                return mService.getPasswordMinimumLowerCase(admin, userHandle);
1234            } catch (RemoteException e) {
1235                Log.w(TAG, "Failed talking with device policy service", e);
1236            }
1237        }
1238        return 0;
1239    }
1240
1241    /**
1242     * Called by an application that is administering the device to set the
1243     * minimum number of letters required in the password. After setting this,
1244     * the user will not be able to enter a new password that is not at least as
1245     * restrictive as what has been set. Note that the current password will
1246     * remain until the user has set a new one, so the change does not take
1247     * place immediately. To prompt the user for a new password, use
1248     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1249     * constraint is only imposed if the administrator has also requested
1250     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1251     * default value is 1.
1252     * <p>
1253     * The calling device admin must have requested
1254     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1255     * this method; if it has not, a security exception will be thrown.
1256     *
1257     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1258     *            with.
1259     * @param length The new desired minimum number of letters required in the
1260     *            password. A value of 0 means there is no restriction.
1261     */
1262    public void setPasswordMinimumLetters(ComponentName admin, int length) {
1263        if (mService != null) {
1264            try {
1265                mService.setPasswordMinimumLetters(admin, length);
1266            } catch (RemoteException e) {
1267                Log.w(TAG, "Failed talking with device policy service", e);
1268            }
1269        }
1270    }
1271
1272    /**
1273     * Retrieve the current number of letters required in the password for all
1274     * admins or a particular one. This is the same value as
1275     * set by {#link {@link #setPasswordMinimumLetters(ComponentName, int)}
1276     * and only applies when the password quality is
1277     * {@link #PASSWORD_QUALITY_COMPLEX}.
1278     *
1279     * @param admin The name of the admin component to check, or null to
1280     *            aggregate all admins.
1281     * @return The minimum number of letters required in the password.
1282     */
1283    public int getPasswordMinimumLetters(ComponentName admin) {
1284        return getPasswordMinimumLetters(admin, UserHandle.myUserId());
1285    }
1286
1287    /** @hide per-user version */
1288    public int getPasswordMinimumLetters(ComponentName admin, int userHandle) {
1289        if (mService != null) {
1290            try {
1291                return mService.getPasswordMinimumLetters(admin, userHandle);
1292            } catch (RemoteException e) {
1293                Log.w(TAG, "Failed talking with device policy service", e);
1294            }
1295        }
1296        return 0;
1297    }
1298
1299    /**
1300     * Called by an application that is administering the device to set the
1301     * minimum number of numerical digits required in the password. After
1302     * setting this, the user will not be able to enter a new password that is
1303     * not at least as restrictive as what has been set. Note that the current
1304     * password will remain until the user has set a new one, so the change does
1305     * not take place immediately. To prompt the user for a new password, use
1306     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1307     * constraint is only imposed if the administrator has also requested
1308     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1309     * default value is 1.
1310     * <p>
1311     * The calling device admin must have requested
1312     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1313     * this method; if it has not, a security exception will be thrown.
1314     *
1315     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1316     *            with.
1317     * @param length The new desired minimum number of numerical digits required
1318     *            in the password. A value of 0 means there is no restriction.
1319     */
1320    public void setPasswordMinimumNumeric(ComponentName admin, int length) {
1321        if (mService != null) {
1322            try {
1323                mService.setPasswordMinimumNumeric(admin, length);
1324            } catch (RemoteException e) {
1325                Log.w(TAG, "Failed talking with device policy service", e);
1326            }
1327        }
1328    }
1329
1330    /**
1331     * Retrieve the current number of numerical digits required in the password
1332     * for all admins of this user and its profiles or a particular one.
1333     * This is the same value as set by
1334     * {#link {@link #setPasswordMinimumNumeric(ComponentName, int)}
1335     * and only applies when the password quality is
1336     * {@link #PASSWORD_QUALITY_COMPLEX}.
1337     *
1338     * @param admin The name of the admin component to check, or null to
1339     *            aggregate all admins.
1340     * @return The minimum number of numerical digits required in the password.
1341     */
1342    public int getPasswordMinimumNumeric(ComponentName admin) {
1343        return getPasswordMinimumNumeric(admin, UserHandle.myUserId());
1344    }
1345
1346    /** @hide per-user version */
1347    public int getPasswordMinimumNumeric(ComponentName admin, int userHandle) {
1348        if (mService != null) {
1349            try {
1350                return mService.getPasswordMinimumNumeric(admin, userHandle);
1351            } catch (RemoteException e) {
1352                Log.w(TAG, "Failed talking with device policy service", e);
1353            }
1354        }
1355        return 0;
1356    }
1357
1358    /**
1359     * Called by an application that is administering the device to set the
1360     * minimum number of symbols required in the password. After setting this,
1361     * the user will not be able to enter a new password that is not at least as
1362     * restrictive as what has been set. Note that the current password will
1363     * remain until the user has set a new one, so the change does not take
1364     * place immediately. To prompt the user for a new password, use
1365     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1366     * constraint is only imposed if the administrator has also requested
1367     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1368     * default value is 1.
1369     * <p>
1370     * The calling device admin must have requested
1371     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1372     * this method; if it has not, a security exception will be thrown.
1373     *
1374     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1375     *            with.
1376     * @param length The new desired minimum number of symbols required in the
1377     *            password. A value of 0 means there is no restriction.
1378     */
1379    public void setPasswordMinimumSymbols(ComponentName admin, int length) {
1380        if (mService != null) {
1381            try {
1382                mService.setPasswordMinimumSymbols(admin, length);
1383            } catch (RemoteException e) {
1384                Log.w(TAG, "Failed talking with device policy service", e);
1385            }
1386        }
1387    }
1388
1389    /**
1390     * Retrieve the current number of symbols required in the password for all
1391     * admins or a particular one. This is the same value as
1392     * set by {#link {@link #setPasswordMinimumSymbols(ComponentName, int)}
1393     * and only applies when the password quality is
1394     * {@link #PASSWORD_QUALITY_COMPLEX}.
1395     *
1396     * @param admin The name of the admin component to check, or null to
1397     *            aggregate all admins.
1398     * @return The minimum number of symbols required in the password.
1399     */
1400    public int getPasswordMinimumSymbols(ComponentName admin) {
1401        return getPasswordMinimumSymbols(admin, UserHandle.myUserId());
1402    }
1403
1404    /** @hide per-user version */
1405    public int getPasswordMinimumSymbols(ComponentName admin, int userHandle) {
1406        if (mService != null) {
1407            try {
1408                return mService.getPasswordMinimumSymbols(admin, userHandle);
1409            } catch (RemoteException e) {
1410                Log.w(TAG, "Failed talking with device policy service", e);
1411            }
1412        }
1413        return 0;
1414    }
1415
1416    /**
1417     * Called by an application that is administering the device to set the
1418     * minimum number of non-letter characters (numerical digits or symbols)
1419     * required in the password. After setting this, the user will not be able
1420     * to enter a new password that is not at least as restrictive as what has
1421     * been set. Note that the current password will remain until the user has
1422     * set a new one, so the change does not take place immediately. To prompt
1423     * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} after
1424     * setting this value. This constraint is only imposed if the administrator
1425     * has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
1426     * {@link #setPasswordQuality}. The default value is 0.
1427     * <p>
1428     * The calling device admin must have requested
1429     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1430     * this method; if it has not, a security exception will be thrown.
1431     *
1432     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1433     *            with.
1434     * @param length The new desired minimum number of letters required in the
1435     *            password. A value of 0 means there is no restriction.
1436     */
1437    public void setPasswordMinimumNonLetter(ComponentName admin, int length) {
1438        if (mService != null) {
1439            try {
1440                mService.setPasswordMinimumNonLetter(admin, length);
1441            } catch (RemoteException e) {
1442                Log.w(TAG, "Failed talking with device policy service", e);
1443            }
1444        }
1445    }
1446
1447    /**
1448     * Retrieve the current number of non-letter characters required in the
1449     * password for all admins of this user and its profiles or a particular one.
1450     * This is the same value as set by
1451     * {#link {@link #setPasswordMinimumNonLetter(ComponentName, int)}
1452     * and only applies when the password quality is
1453     * {@link #PASSWORD_QUALITY_COMPLEX}.
1454     *
1455     * @param admin The name of the admin component to check, or null to
1456     *            aggregate all admins.
1457     * @return The minimum number of letters required in the password.
1458     */
1459    public int getPasswordMinimumNonLetter(ComponentName admin) {
1460        return getPasswordMinimumNonLetter(admin, UserHandle.myUserId());
1461    }
1462
1463    /** @hide per-user version */
1464    public int getPasswordMinimumNonLetter(ComponentName admin, int userHandle) {
1465        if (mService != null) {
1466            try {
1467                return mService.getPasswordMinimumNonLetter(admin, userHandle);
1468            } catch (RemoteException e) {
1469                Log.w(TAG, "Failed talking with device policy service", e);
1470            }
1471        }
1472        return 0;
1473    }
1474
1475  /**
1476   * Called by an application that is administering the device to set the length
1477   * of the password history. After setting this, the user will not be able to
1478   * enter a new password that is the same as any password in the history. Note
1479   * that the current password will remain until the user has set a new one, so
1480   * the change does not take place immediately. To prompt the user for a new
1481   * password, use {@link #ACTION_SET_NEW_PASSWORD} after setting this value.
1482   * This constraint is only imposed if the administrator has also requested
1483   * either {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}
1484   * {@link #PASSWORD_QUALITY_ALPHABETIC}, or {@link #PASSWORD_QUALITY_ALPHANUMERIC}
1485   * with {@link #setPasswordQuality}.
1486   *
1487   * <p>
1488   * The calling device admin must have requested
1489   * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this
1490   * method; if it has not, a security exception will be thrown.
1491   *
1492   * @param admin Which {@link DeviceAdminReceiver} this request is associated
1493   *        with.
1494   * @param length The new desired length of password history. A value of 0
1495   *        means there is no restriction.
1496   */
1497    public void setPasswordHistoryLength(ComponentName admin, int length) {
1498        if (mService != null) {
1499            try {
1500                mService.setPasswordHistoryLength(admin, length);
1501            } catch (RemoteException e) {
1502                Log.w(TAG, "Failed talking with device policy service", e);
1503            }
1504        }
1505    }
1506
1507    /**
1508     * Called by a device admin to set the password expiration timeout. Calling this method
1509     * will restart the countdown for password expiration for the given admin, as will changing
1510     * the device password (for all admins).
1511     *
1512     * <p>The provided timeout is the time delta in ms and will be added to the current time.
1513     * For example, to have the password expire 5 days from now, timeout would be
1514     * 5 * 86400 * 1000 = 432000000 ms for timeout.
1515     *
1516     * <p>To disable password expiration, a value of 0 may be used for timeout.
1517     *
1518     * <p>The calling device admin must have requested
1519     * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this
1520     * method; if it has not, a security exception will be thrown.
1521     *
1522     * <p> Note that setting the password will automatically reset the expiration time for all
1523     * active admins. Active admins do not need to explicitly call this method in that case.
1524     *
1525     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1526     * @param timeout The limit (in ms) that a password can remain in effect. A value of 0
1527     *        means there is no restriction (unlimited).
1528     */
1529    public void setPasswordExpirationTimeout(ComponentName admin, long timeout) {
1530        if (mService != null) {
1531            try {
1532                mService.setPasswordExpirationTimeout(admin, timeout);
1533            } catch (RemoteException e) {
1534                Log.w(TAG, "Failed talking with device policy service", e);
1535            }
1536        }
1537    }
1538
1539    /**
1540     * Get the password expiration timeout for the given admin. The expiration timeout is the
1541     * recurring expiration timeout provided in the call to
1542     * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
1543     * aggregate of all policy administrators if admin is null.
1544     *
1545     * @param admin The name of the admin component to check, or null to aggregate all admins.
1546     * @return The timeout for the given admin or the minimum of all timeouts
1547     */
1548    public long getPasswordExpirationTimeout(ComponentName admin) {
1549        if (mService != null) {
1550            try {
1551                return mService.getPasswordExpirationTimeout(admin, UserHandle.myUserId());
1552            } catch (RemoteException e) {
1553                Log.w(TAG, "Failed talking with device policy service", e);
1554            }
1555        }
1556        return 0;
1557    }
1558
1559    /**
1560     * Get the current password expiration time for the given admin or an aggregate of
1561     * all admins of this user and its profiles if admin is null. If the password is
1562     * expired, this will return the time since the password expired as a negative number.
1563     * If admin is null, then a composite of all expiration timeouts is returned
1564     * - which will be the minimum of all timeouts.
1565     *
1566     * @param admin The name of the admin component to check, or null to aggregate all admins.
1567     * @return The password expiration time, in ms.
1568     */
1569    public long getPasswordExpiration(ComponentName admin) {
1570        if (mService != null) {
1571            try {
1572                return mService.getPasswordExpiration(admin, UserHandle.myUserId());
1573            } catch (RemoteException e) {
1574                Log.w(TAG, "Failed talking with device policy service", e);
1575            }
1576        }
1577        return 0;
1578    }
1579
1580    /**
1581     * Retrieve the current password history length for all admins of this
1582     * user and its profiles or a particular one.
1583     * @param admin The name of the admin component to check, or null to aggregate
1584     * all admins.
1585     * @return The length of the password history
1586     */
1587    public int getPasswordHistoryLength(ComponentName admin) {
1588        return getPasswordHistoryLength(admin, UserHandle.myUserId());
1589    }
1590
1591    /** @hide per-user version */
1592    public int getPasswordHistoryLength(ComponentName admin, int userHandle) {
1593        if (mService != null) {
1594            try {
1595                return mService.getPasswordHistoryLength(admin, userHandle);
1596            } catch (RemoteException e) {
1597                Log.w(TAG, "Failed talking with device policy service", e);
1598            }
1599        }
1600        return 0;
1601    }
1602
1603    /**
1604     * Return the maximum password length that the device supports for a
1605     * particular password quality.
1606     * @param quality The quality being interrogated.
1607     * @return Returns the maximum length that the user can enter.
1608     */
1609    public int getPasswordMaximumLength(int quality) {
1610        // Kind-of arbitrary.
1611        return 16;
1612    }
1613
1614    /**
1615     * Determine whether the current password the user has set is sufficient
1616     * to meet the policy requirements (quality, minimum length) that have been
1617     * requested by the admins of this user and its profiles.
1618     *
1619     * <p>The calling device admin must have requested
1620     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1621     * this method; if it has not, a security exception will be thrown.
1622     *
1623     * @return Returns true if the password meets the current requirements, else false.
1624     */
1625    public boolean isActivePasswordSufficient() {
1626        if (mService != null) {
1627            try {
1628                return mService.isActivePasswordSufficient(UserHandle.myUserId());
1629            } catch (RemoteException e) {
1630                Log.w(TAG, "Failed talking with device policy service", e);
1631            }
1632        }
1633        return false;
1634    }
1635
1636    /**
1637     * Retrieve the number of times the user has failed at entering a
1638     * password since that last successful password entry.
1639     *
1640     * <p>The calling device admin must have requested
1641     * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call
1642     * this method; if it has not, a security exception will be thrown.
1643     */
1644    public int getCurrentFailedPasswordAttempts() {
1645        if (mService != null) {
1646            try {
1647                return mService.getCurrentFailedPasswordAttempts(UserHandle.myUserId());
1648            } catch (RemoteException e) {
1649                Log.w(TAG, "Failed talking with device policy service", e);
1650            }
1651        }
1652        return -1;
1653    }
1654
1655    /**
1656     * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
1657     *
1658     * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
1659     * @hide
1660     */
1661    public boolean getDoNotAskCredentialsOnBoot() {
1662        if (mService != null) {
1663            try {
1664                return mService.getDoNotAskCredentialsOnBoot();
1665            } catch (RemoteException e) {
1666                Log.w(TAG, "Failed to call getDoNotAskCredentialsOnBoot()", e);
1667            }
1668        }
1669        return false;
1670    }
1671
1672    /**
1673     * Setting this to a value greater than zero enables a built-in policy
1674     * that will perform a device wipe after too many incorrect
1675     * device-unlock passwords have been entered.  This built-in policy combines
1676     * watching for failed passwords and wiping the device, and requires
1677     * that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
1678     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
1679     *
1680     * <p>To implement any other policy (e.g. wiping data for a particular
1681     * application only, erasing or revoking credentials, or reporting the
1682     * failure to a server), you should implement
1683     * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)}
1684     * instead.  Do not use this API, because if the maximum count is reached,
1685     * the device will be wiped immediately, and your callback will not be invoked.
1686     *
1687     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1688     * @param num The number of failed password attempts at which point the
1689     * device will wipe its data.
1690     */
1691    public void setMaximumFailedPasswordsForWipe(ComponentName admin, int num) {
1692        if (mService != null) {
1693            try {
1694                mService.setMaximumFailedPasswordsForWipe(admin, num);
1695            } catch (RemoteException e) {
1696                Log.w(TAG, "Failed talking with device policy service", e);
1697            }
1698        }
1699    }
1700
1701    /**
1702     * Retrieve the current maximum number of login attempts that are allowed
1703     * before the device wipes itself, for all admins of this user and its profiles
1704     * or a particular one.
1705     * @param admin The name of the admin component to check, or null to aggregate
1706     * all admins.
1707     */
1708    public int getMaximumFailedPasswordsForWipe(ComponentName admin) {
1709        return getMaximumFailedPasswordsForWipe(admin, UserHandle.myUserId());
1710    }
1711
1712    /** @hide per-user version */
1713    public int getMaximumFailedPasswordsForWipe(ComponentName admin, int userHandle) {
1714        if (mService != null) {
1715            try {
1716                return mService.getMaximumFailedPasswordsForWipe(admin, userHandle);
1717            } catch (RemoteException e) {
1718                Log.w(TAG, "Failed talking with device policy service", e);
1719            }
1720        }
1721        return 0;
1722    }
1723
1724    /**
1725     * Returns the profile with the smallest maximum failed passwords for wipe,
1726     * for the given user. So for primary user, it might return the primary or
1727     * a managed profile. For a secondary user, it would be the same as the
1728     * user passed in.
1729     * @hide Used only by Keyguard
1730     */
1731    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
1732        if (mService != null) {
1733            try {
1734                return mService.getProfileWithMinimumFailedPasswordsForWipe(userHandle);
1735            } catch (RemoteException e) {
1736                Log.w(TAG, "Failed talking with device policy service", e);
1737            }
1738        }
1739        return UserHandle.USER_NULL;
1740    }
1741
1742    /**
1743     * Flag for {@link #resetPassword}: don't allow other admins to change
1744     * the password again until the user has entered it.
1745     */
1746    public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
1747
1748    /**
1749     * Flag for {@link #resetPassword}: don't ask for user credentials on device boot.
1750     * If the flag is set, the device can be booted without asking for user password.
1751     * The absence of this flag does not change the current boot requirements. This flag
1752     * can be set by the device owner only. If the app is not the device owner, the flag
1753     * is ignored. Once the flag is set, it cannot be reverted back without resetting the
1754     * device to factory defaults.
1755     */
1756    public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
1757
1758    /**
1759     * Force a new device unlock password (the password needed to access the
1760     * entire device, not for individual accounts) on the user.  This takes
1761     * effect immediately.
1762     * The given password must be sufficient for the
1763     * current password quality and length constraints as returned by
1764     * {@link #getPasswordQuality(ComponentName)} and
1765     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet
1766     * these constraints, then it will be rejected and false returned.  Note
1767     * that the password may be a stronger quality (containing alphanumeric
1768     * characters when the requested quality is only numeric), in which case
1769     * the currently active quality will be increased to match.
1770     *
1771     * <p>Calling with a null or empty password will clear any existing PIN,
1772     * pattern or password if the current password constraints allow it.
1773     *
1774     * <p>The calling device admin must have requested
1775     * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call
1776     * this method; if it has not, a security exception will be thrown.
1777     *
1778     * <p>Calling this from a managed profile will throw a security exception.
1779     *
1780     * @param password The new password for the user. Null or empty clears the password.
1781     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
1782     *              {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
1783     * @return Returns true if the password was applied, or false if it is
1784     * not acceptable for the current constraints.
1785     */
1786    public boolean resetPassword(String password, int flags) {
1787        if (mService != null) {
1788            try {
1789                return mService.resetPassword(password, flags);
1790            } catch (RemoteException e) {
1791                Log.w(TAG, "Failed talking with device policy service", e);
1792            }
1793        }
1794        return false;
1795    }
1796
1797    /**
1798     * Called by an application that is administering the device to set the
1799     * maximum time for user activity until the device will lock.  This limits
1800     * the length that the user can set.  It takes effect immediately.
1801     *
1802     * <p>The calling device admin must have requested
1803     * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} to be able to call
1804     * this method; if it has not, a security exception will be thrown.
1805     *
1806     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1807     * @param timeMs The new desired maximum time to lock in milliseconds.
1808     * A value of 0 means there is no restriction.
1809     */
1810    public void setMaximumTimeToLock(ComponentName admin, long timeMs) {
1811        if (mService != null) {
1812            try {
1813                mService.setMaximumTimeToLock(admin, timeMs);
1814            } catch (RemoteException e) {
1815                Log.w(TAG, "Failed talking with device policy service", e);
1816            }
1817        }
1818    }
1819
1820    /**
1821     * Retrieve the current maximum time to unlock for all admins of this user
1822     * and its profiles or a particular one.
1823     * @param admin The name of the admin component to check, or null to aggregate
1824     * all admins.
1825     * @return time in milliseconds for the given admin or the minimum value (strictest) of
1826     * all admins if admin is null. Returns 0 if there are no restrictions.
1827     */
1828    public long getMaximumTimeToLock(ComponentName admin) {
1829        return getMaximumTimeToLock(admin, UserHandle.myUserId());
1830    }
1831
1832    /** @hide per-user version */
1833    public long getMaximumTimeToLock(ComponentName admin, int userHandle) {
1834        if (mService != null) {
1835            try {
1836                return mService.getMaximumTimeToLock(admin, userHandle);
1837            } catch (RemoteException e) {
1838                Log.w(TAG, "Failed talking with device policy service", e);
1839            }
1840        }
1841        return 0;
1842    }
1843
1844    /**
1845     * Make the device lock immediately, as if the lock screen timeout has
1846     * expired at the point of this call.
1847     *
1848     * <p>The calling device admin must have requested
1849     * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} to be able to call
1850     * this method; if it has not, a security exception will be thrown.
1851     */
1852    public void lockNow() {
1853        if (mService != null) {
1854            try {
1855                mService.lockNow();
1856            } catch (RemoteException e) {
1857                Log.w(TAG, "Failed talking with device policy service", e);
1858            }
1859        }
1860    }
1861
1862    /**
1863     * Flag for {@link #wipeData(int)}: also erase the device's external
1864     * storage (such as SD cards).
1865     */
1866    public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
1867
1868    /**
1869     * Flag for {@link #wipeData(int)}: also erase the factory reset protection
1870     * data.
1871     *
1872     * <p>This flag may only be set by device owner admins; if it is set by
1873     * other admins a {@link SecurityException} will be thrown.
1874     */
1875    public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
1876
1877    /**
1878     * Ask the user data be wiped.  Wiping the primary user will cause the
1879     * device to reboot, erasing all user data while next booting up.
1880     *
1881     * <p>The calling device admin must have requested
1882     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to be able to call
1883     * this method; if it has not, a security exception will be thrown.
1884     *
1885     * @param flags Bit mask of additional options: currently supported flags
1886     * are {@link #WIPE_EXTERNAL_STORAGE} and
1887     * {@link #WIPE_RESET_PROTECTION_DATA}.
1888     */
1889    public void wipeData(int flags) {
1890        if (mService != null) {
1891            try {
1892                mService.wipeData(flags, UserHandle.myUserId());
1893            } catch (RemoteException e) {
1894                Log.w(TAG, "Failed talking with device policy service", e);
1895            }
1896        }
1897    }
1898
1899    /**
1900     * Called by an application that is administering the device to set the
1901     * global proxy and exclusion list.
1902     * <p>
1903     * The calling device admin must have requested
1904     * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
1905     * this method; if it has not, a security exception will be thrown.
1906     * Only the first device admin can set the proxy. If a second admin attempts
1907     * to set the proxy, the {@link ComponentName} of the admin originally setting the
1908     * proxy will be returned. If successful in setting the proxy, null will
1909     * be returned.
1910     * The method can be called repeatedly by the device admin alrady setting the
1911     * proxy to update the proxy and exclusion list.
1912     *
1913     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1914     *            with.
1915     * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
1916     *            Pass Proxy.NO_PROXY to reset the proxy.
1917     * @param exclusionList a list of domains to be excluded from the global proxy.
1918     * @return returns null if the proxy was successfully set, or a {@link ComponentName}
1919     *            of the device admin that sets thew proxy otherwise.
1920     * @hide
1921     */
1922    public ComponentName setGlobalProxy(ComponentName admin, Proxy proxySpec,
1923            List<String> exclusionList ) {
1924        if (proxySpec == null) {
1925            throw new NullPointerException();
1926        }
1927        if (mService != null) {
1928            try {
1929                String hostSpec;
1930                String exclSpec;
1931                if (proxySpec.equals(Proxy.NO_PROXY)) {
1932                    hostSpec = null;
1933                    exclSpec = null;
1934                } else {
1935                    if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
1936                        throw new IllegalArgumentException();
1937                    }
1938                    InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
1939                    String hostName = sa.getHostName();
1940                    int port = sa.getPort();
1941                    StringBuilder hostBuilder = new StringBuilder();
1942                    hostSpec = hostBuilder.append(hostName)
1943                        .append(":").append(Integer.toString(port)).toString();
1944                    if (exclusionList == null) {
1945                        exclSpec = "";
1946                    } else {
1947                        StringBuilder listBuilder = new StringBuilder();
1948                        boolean firstDomain = true;
1949                        for (String exclDomain : exclusionList) {
1950                            if (!firstDomain) {
1951                                listBuilder = listBuilder.append(",");
1952                            } else {
1953                                firstDomain = false;
1954                            }
1955                            listBuilder = listBuilder.append(exclDomain.trim());
1956                        }
1957                        exclSpec = listBuilder.toString();
1958                    }
1959                    if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
1960                            != android.net.Proxy.PROXY_VALID)
1961                        throw new IllegalArgumentException();
1962                }
1963                return mService.setGlobalProxy(admin, hostSpec, exclSpec);
1964            } catch (RemoteException e) {
1965                Log.w(TAG, "Failed talking with device policy service", e);
1966            }
1967        }
1968        return null;
1969    }
1970
1971    /**
1972     * Set a network-independent global HTTP proxy.  This is not normally what you want
1973     * for typical HTTP proxies - they are generally network dependent.  However if you're
1974     * doing something unusual like general internal filtering this may be useful.  On
1975     * a private network where the proxy is not accessible, you may break HTTP using this.
1976     *
1977     * <p>This method requires the caller to be the device owner.
1978     *
1979     * <p>This proxy is only a recommendation and it is possible that some apps will ignore it.
1980     * @see ProxyInfo
1981     *
1982     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1983     *            with.
1984     * @param proxyInfo The a {@link ProxyInfo} object defining the new global
1985     *        HTTP proxy.  A {@code null} value will clear the global HTTP proxy.
1986     */
1987    public void setRecommendedGlobalProxy(ComponentName admin, ProxyInfo proxyInfo) {
1988        if (mService != null) {
1989            try {
1990                mService.setRecommendedGlobalProxy(admin, proxyInfo);
1991            } catch (RemoteException e) {
1992                Log.w(TAG, "Failed talking with device policy service", e);
1993            }
1994        }
1995    }
1996
1997    /**
1998     * Returns the component name setting the global proxy.
1999     * @return ComponentName object of the device admin that set the global proxy, or
2000     *            null if no admin has set the proxy.
2001     * @hide
2002     */
2003    public ComponentName getGlobalProxyAdmin() {
2004        if (mService != null) {
2005            try {
2006                return mService.getGlobalProxyAdmin(UserHandle.myUserId());
2007            } catch (RemoteException e) {
2008                Log.w(TAG, "Failed talking with device policy service", e);
2009            }
2010        }
2011        return null;
2012    }
2013
2014    /**
2015     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
2016     * indicating that encryption is not supported.
2017     */
2018    public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
2019
2020    /**
2021     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
2022     * indicating that encryption is supported, but is not currently active.
2023     */
2024    public static final int ENCRYPTION_STATUS_INACTIVE = 1;
2025
2026    /**
2027     * Result code for {@link #getStorageEncryptionStatus}:
2028     * indicating that encryption is not currently active, but is currently
2029     * being activated.  This is only reported by devices that support
2030     * encryption of data and only when the storage is currently
2031     * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
2032     * to become encrypted will never return this value.
2033     */
2034    public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
2035
2036    /**
2037     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
2038     * indicating that encryption is active.
2039     */
2040    public static final int ENCRYPTION_STATUS_ACTIVE = 3;
2041
2042    /**
2043     * Result code for {@link #getStorageEncryptionStatus}:
2044     * indicating that encryption is active, but an encryption key has not
2045     * been set by the user.
2046     */
2047    public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
2048
2049    /**
2050     * Activity action: begin the process of encrypting data on the device.  This activity should
2051     * be launched after using {@link #setStorageEncryption} to request encryption be activated.
2052     * After resuming from this activity, use {@link #getStorageEncryption}
2053     * to check encryption status.  However, on some devices this activity may never return, as
2054     * it may trigger a reboot and in some cases a complete data wipe of the device.
2055     */
2056    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2057    public static final String ACTION_START_ENCRYPTION
2058            = "android.app.action.START_ENCRYPTION";
2059
2060    /**
2061     * Widgets are enabled in keyguard
2062     */
2063    public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
2064
2065    /**
2066     * Disable all keyguard widgets. Has no effect.
2067     */
2068    public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
2069
2070    /**
2071     * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
2072     */
2073    public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
2074
2075    /**
2076     * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
2077     */
2078    public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
2079
2080    /**
2081     * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
2082     */
2083    public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
2084
2085    /**
2086     * Ignore trust agent state on secure keyguard screens
2087     * (e.g. PIN/Pattern/Password).
2088     */
2089    public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
2090
2091    /**
2092     * Disable fingerprint sensor on keyguard secure screens (e.g. PIN/Pattern/Password).
2093     */
2094    public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
2095
2096    /**
2097     * Disable all current and future keyguard customizations.
2098     */
2099    public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
2100
2101    /**
2102     * Called by an application that is administering the device to
2103     * request that the storage system be encrypted.
2104     *
2105     * <p>When multiple device administrators attempt to control device
2106     * encryption, the most secure, supported setting will always be
2107     * used.  If any device administrator requests device encryption,
2108     * it will be enabled;  Conversely, if a device administrator
2109     * attempts to disable device encryption while another
2110     * device administrator has enabled it, the call to disable will
2111     * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
2112     *
2113     * <p>This policy controls encryption of the secure (application data) storage area.  Data
2114     * written to other storage areas may or may not be encrypted, and this policy does not require
2115     * or control the encryption of any other storage areas.
2116     * There is one exception:  If {@link android.os.Environment#isExternalStorageEmulated()} is
2117     * {@code true}, then the directory returned by
2118     * {@link android.os.Environment#getExternalStorageDirectory()} must be written to disk
2119     * within the encrypted storage area.
2120     *
2121     * <p>Important Note:  On some devices, it is possible to encrypt storage without requiring
2122     * the user to create a device PIN or Password.  In this case, the storage is encrypted, but
2123     * the encryption key may not be fully secured.  For maximum security, the administrator should
2124     * also require (and check for) a pattern, PIN, or password.
2125     *
2126     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2127     * @param encrypt true to request encryption, false to release any previous request
2128     * @return the new request status (for all active admins) - will be one of
2129     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, or
2130     * {@link #ENCRYPTION_STATUS_ACTIVE}.  This is the value of the requests;  Use
2131     * {@link #getStorageEncryptionStatus()} to query the actual device state.
2132     */
2133    public int setStorageEncryption(ComponentName admin, boolean encrypt) {
2134        if (mService != null) {
2135            try {
2136                return mService.setStorageEncryption(admin, encrypt);
2137            } catch (RemoteException e) {
2138                Log.w(TAG, "Failed talking with device policy service", e);
2139            }
2140        }
2141        return ENCRYPTION_STATUS_UNSUPPORTED;
2142    }
2143
2144    /**
2145     * Called by an application that is administering the device to
2146     * determine the requested setting for secure storage.
2147     *
2148     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
2149     * this will return the requested encryption setting as an aggregate of all active
2150     * administrators.
2151     * @return true if the admin(s) are requesting encryption, false if not.
2152     */
2153    public boolean getStorageEncryption(ComponentName admin) {
2154        if (mService != null) {
2155            try {
2156                return mService.getStorageEncryption(admin, UserHandle.myUserId());
2157            } catch (RemoteException e) {
2158                Log.w(TAG, "Failed talking with device policy service", e);
2159            }
2160        }
2161        return false;
2162    }
2163
2164    /**
2165     * Called by an application that is administering the device to
2166     * determine the current encryption status of the device.
2167     *
2168     * Depending on the returned status code, the caller may proceed in different
2169     * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
2170     * storage system does not support encryption.  If the
2171     * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
2172     * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
2173     * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
2174     * storage system has enabled encryption but no password is set so further action
2175     * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING} or
2176     * {@link #ENCRYPTION_STATUS_ACTIVE}, no further action is required.
2177     *
2178     * @return current status of encryption. The value will be one of
2179     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
2180     * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
2181     * or {@link #ENCRYPTION_STATUS_ACTIVE}.
2182     */
2183    public int getStorageEncryptionStatus() {
2184        return getStorageEncryptionStatus(UserHandle.myUserId());
2185    }
2186
2187    /** @hide per-user version */
2188    public int getStorageEncryptionStatus(int userHandle) {
2189        if (mService != null) {
2190            try {
2191                return mService.getStorageEncryptionStatus(userHandle);
2192            } catch (RemoteException e) {
2193                Log.w(TAG, "Failed talking with device policy service", e);
2194            }
2195        }
2196        return ENCRYPTION_STATUS_UNSUPPORTED;
2197    }
2198
2199    /**
2200     * Installs the given certificate as a user CA.
2201     *
2202     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use
2203     * <code>null</code> if calling from a delegated certificate installer.
2204     * @param certBuffer encoded form of the certificate to install.
2205     *
2206     * @return false if the certBuffer cannot be parsed or installation is
2207     *         interrupted, true otherwise.
2208     */
2209    public boolean installCaCert(ComponentName admin, byte[] certBuffer) {
2210        if (mService != null) {
2211            try {
2212                return mService.installCaCert(admin, certBuffer);
2213            } catch (RemoteException e) {
2214                Log.w(TAG, "Failed talking with device policy service", e);
2215            }
2216        }
2217        return false;
2218    }
2219
2220    /**
2221     * Uninstalls the given certificate from trusted user CAs, if present.
2222     *
2223     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use
2224     * <code>null</code> if calling from a delegated certificate installer.
2225     * @param certBuffer encoded form of the certificate to remove.
2226     */
2227    public void uninstallCaCert(ComponentName admin, byte[] certBuffer) {
2228        if (mService != null) {
2229            try {
2230                final String alias = getCaCertAlias(certBuffer);
2231                mService.uninstallCaCert(admin, alias);
2232            } catch (CertificateException e) {
2233                Log.w(TAG, "Unable to parse certificate", e);
2234            } catch (RemoteException e) {
2235                Log.w(TAG, "Failed talking with device policy service", e);
2236            }
2237        }
2238    }
2239
2240    /**
2241     * Returns all CA certificates that are currently trusted, excluding system CA certificates.
2242     * If a user has installed any certificates by other means than device policy these will be
2243     * included too.
2244     *
2245     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use
2246     * <code>null</code> if calling from a delegated certificate installer.
2247     * @return a List of byte[] arrays, each encoding one user CA certificate.
2248     */
2249    public List<byte[]> getInstalledCaCerts(ComponentName admin) {
2250        List<byte[]> certs = new ArrayList<byte[]>();
2251        if (mService != null) {
2252            try {
2253                mService.enforceCanManageCaCerts(admin);
2254                final TrustedCertificateStore certStore = new TrustedCertificateStore();
2255                for (String alias : certStore.userAliases()) {
2256                    try {
2257                        certs.add(certStore.getCertificate(alias).getEncoded());
2258                    } catch (CertificateException ce) {
2259                        Log.w(TAG, "Could not encode certificate: " + alias, ce);
2260                    }
2261                }
2262            } catch (RemoteException re) {
2263                Log.w(TAG, "Failed talking with device policy service", re);
2264            }
2265        }
2266        return certs;
2267    }
2268
2269    /**
2270     * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
2271     * means other than device policy will also be removed, except for system CA certificates.
2272     *
2273     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use
2274     * <code>null</code> if calling from a delegated certificate installer.
2275     */
2276    public void uninstallAllUserCaCerts(ComponentName admin) {
2277        if (mService != null) {
2278            for (String alias : new TrustedCertificateStore().userAliases()) {
2279                try {
2280                    mService.uninstallCaCert(admin, alias);
2281                } catch (RemoteException re) {
2282                    Log.w(TAG, "Failed talking with device policy service", re);
2283                }
2284            }
2285        }
2286    }
2287
2288    /**
2289     * Returns whether this certificate is installed as a trusted CA.
2290     *
2291     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use
2292     * <code>null</code> if calling from a delegated certificate installer.
2293     * @param certBuffer encoded form of the certificate to look up.
2294     */
2295    public boolean hasCaCertInstalled(ComponentName admin, byte[] certBuffer) {
2296        if (mService != null) {
2297            try {
2298                mService.enforceCanManageCaCerts(admin);
2299                return getCaCertAlias(certBuffer) != null;
2300            } catch (RemoteException re) {
2301                Log.w(TAG, "Failed talking with device policy service", re);
2302            } catch (CertificateException ce) {
2303                Log.w(TAG, "Could not parse certificate", ce);
2304            }
2305        }
2306        return false;
2307    }
2308
2309    /**
2310     * Called by a device or profile owner to install a certificate and private key pair. The
2311     * keypair will be visible to all apps within the profile.
2312     *
2313     * @param who Which {@link DeviceAdminReceiver} this request is associated with. Use
2314     * <code>null</code> if calling from a delegated certificate installer.
2315     * @param privKey The private key to install.
2316     * @param cert The certificate to install.
2317     * @param alias The private key alias under which to install the certificate. If a certificate
2318     * with that alias already exists, it will be overwritten.
2319     * @return {@code true} if the keys were installed, {@code false} otherwise.
2320     */
2321    public boolean installKeyPair(ComponentName who, PrivateKey privKey, Certificate cert,
2322            String alias) {
2323        try {
2324            final byte[] pemCert = Credentials.convertToPem(cert);
2325            final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
2326                    .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
2327            return mService.installKeyPair(who, pkcs8Key, pemCert, alias);
2328        } catch (RemoteException e) {
2329            Log.w(TAG, "Failed talking with device policy service", e);
2330        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
2331            Log.w(TAG, "Failed to obtain private key material", e);
2332        } catch (CertificateException | IOException e) {
2333            Log.w(TAG, "Could not pem-encode certificate", e);
2334        }
2335        return false;
2336    }
2337
2338    /**
2339     * Returns the alias of a given CA certificate in the certificate store, or null if it
2340     * doesn't exist.
2341     */
2342    private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
2343        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
2344        final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
2345                              new ByteArrayInputStream(certBuffer));
2346        return new TrustedCertificateStore().getCertificateAlias(cert);
2347    }
2348
2349    /**
2350     * Called by a profile owner or device owner to grant access to privileged certificate
2351     * manipulation APIs to a third-party certificate installer app. Granted APIs include
2352     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
2353     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
2354     * <p>
2355     * Delegated certificate installer is a per-user state. The delegated access is persistent until
2356     * it is later cleared by calling this method with a null value or uninstallling the certificate
2357     * installer.
2358     *
2359     * @param who Which {@link DeviceAdminReceiver} this request is associated with.
2360     * @param installerPackage The package name of the certificate installer which will be given
2361     * access. If <code>null</code> is given the current package will be cleared.
2362     */
2363    public void setCertInstallerPackage(ComponentName who, String installerPackage)
2364            throws SecurityException {
2365        if (mService != null) {
2366            try {
2367                mService.setCertInstallerPackage(who, installerPackage);
2368            } catch (RemoteException e) {
2369                Log.w(TAG, "Failed talking with device policy service", e);
2370            }
2371        }
2372    }
2373
2374    /**
2375     * Called by a profile owner or device owner to retrieve the certificate installer for the
2376     * current user. null if none is set.
2377     *
2378     * @param who Which {@link DeviceAdminReceiver} this request is associated with.
2379     * @return The package name of the current delegated certificate installer. <code>null</code>
2380     * if none is set.
2381     */
2382    public String getCertInstallerPackage(ComponentName who) throws SecurityException {
2383        if (mService != null) {
2384            try {
2385                return mService.getCertInstallerPackage(who);
2386            } catch (RemoteException e) {
2387                Log.w(TAG, "Failed talking with device policy service", e);
2388            }
2389        }
2390        return null;
2391    }
2392
2393    /**
2394     * Called by an application that is administering the device to disable all cameras
2395     * on the device, for this user. After setting this, no applications running as this user
2396     * will be able to access any cameras on the device.
2397     *
2398     * <p>The calling device admin must have requested
2399     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call
2400     * this method; if it has not, a security exception will be thrown.
2401     *
2402     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2403     * @param disabled Whether or not the camera should be disabled.
2404     */
2405    public void setCameraDisabled(ComponentName admin, boolean disabled) {
2406        if (mService != null) {
2407            try {
2408                mService.setCameraDisabled(admin, disabled);
2409            } catch (RemoteException e) {
2410                Log.w(TAG, "Failed talking with device policy service", e);
2411            }
2412        }
2413    }
2414
2415    /**
2416     * Determine whether or not the device's cameras have been disabled for this user,
2417     * either by the current admin, if specified, or all admins.
2418     * @param admin The name of the admin component to check, or null to check if any admins
2419     * have disabled the camera
2420     */
2421    public boolean getCameraDisabled(ComponentName admin) {
2422        return getCameraDisabled(admin, UserHandle.myUserId());
2423    }
2424
2425    /** @hide per-user version */
2426    public boolean getCameraDisabled(ComponentName admin, int userHandle) {
2427        if (mService != null) {
2428            try {
2429                return mService.getCameraDisabled(admin, userHandle);
2430            } catch (RemoteException e) {
2431                Log.w(TAG, "Failed talking with device policy service", e);
2432            }
2433        }
2434        return false;
2435    }
2436
2437    /**
2438     * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
2439     * screen capture also prevents the content from being shown on display devices that do not have
2440     * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
2441     * secure surfaces and secure displays.
2442     *
2443     * <p>The calling device admin must be a device or profile owner. If it is not, a
2444     * security exception will be thrown.
2445     *
2446     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2447     * @param disabled Whether screen capture is disabled or not.
2448     */
2449    public void setScreenCaptureDisabled(ComponentName admin, boolean disabled) {
2450        if (mService != null) {
2451            try {
2452                mService.setScreenCaptureDisabled(admin, disabled);
2453            } catch (RemoteException e) {
2454                Log.w(TAG, "Failed talking with device policy service", e);
2455            }
2456        }
2457    }
2458
2459    /**
2460     * Determine whether or not screen capture has been disabled by the current
2461     * admin, if specified, or all admins.
2462     * @param admin The name of the admin component to check, or null to check if any admins
2463     * have disabled screen capture.
2464     */
2465    public boolean getScreenCaptureDisabled(ComponentName admin) {
2466        return getScreenCaptureDisabled(admin, UserHandle.myUserId());
2467    }
2468
2469    /** @hide per-user version */
2470    public boolean getScreenCaptureDisabled(ComponentName admin, int userHandle) {
2471        if (mService != null) {
2472            try {
2473                return mService.getScreenCaptureDisabled(admin, userHandle);
2474            } catch (RemoteException e) {
2475                Log.w(TAG, "Failed talking with device policy service", e);
2476            }
2477        }
2478        return false;
2479    }
2480
2481    /**
2482     * Called by a device owner to set whether auto time is required. If auto time is
2483     * required the user cannot set the date and time, but has to use network date and time.
2484     *
2485     * <p>Note: if auto time is required the user can still manually set the time zone.
2486     *
2487     * <p>The calling device admin must be a device owner. If it is not, a security exception will
2488     * be thrown.
2489     *
2490     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2491     * @param required Whether auto time is set required or not.
2492     */
2493    public void setAutoTimeRequired(ComponentName admin, boolean required) {
2494        if (mService != null) {
2495            try {
2496                mService.setAutoTimeRequired(admin, required);
2497            } catch (RemoteException e) {
2498                Log.w(TAG, "Failed talking with device policy service", e);
2499            }
2500        }
2501    }
2502
2503    /**
2504     * @return true if auto time is required.
2505     */
2506    public boolean getAutoTimeRequired() {
2507        if (mService != null) {
2508            try {
2509                return mService.getAutoTimeRequired();
2510            } catch (RemoteException e) {
2511                Log.w(TAG, "Failed talking with device policy service", e);
2512            }
2513        }
2514        return false;
2515    }
2516
2517    /**
2518     * Called by an application that is administering the device to disable keyguard customizations,
2519     * such as widgets. After setting this, keyguard features will be disabled according to the
2520     * provided feature list.
2521     *
2522     * <p>The calling device admin must have requested
2523     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call
2524     * this method; if it has not, a security exception will be thrown.
2525     *
2526     * <p>Calling this from a managed profile will throw a security exception.
2527     *
2528     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2529     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
2530     * {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
2531     * {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}, {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
2532     * {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
2533     */
2534    public void setKeyguardDisabledFeatures(ComponentName admin, int which) {
2535        if (mService != null) {
2536            try {
2537                mService.setKeyguardDisabledFeatures(admin, which);
2538            } catch (RemoteException e) {
2539                Log.w(TAG, "Failed talking with device policy service", e);
2540            }
2541        }
2542    }
2543
2544    /**
2545     * Determine whether or not features have been disabled in keyguard either by the current
2546     * admin, if specified, or all admins.
2547     * @param admin The name of the admin component to check, or null to check if any admins
2548     * have disabled features in keyguard.
2549     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
2550     * for a list.
2551     */
2552    public int getKeyguardDisabledFeatures(ComponentName admin) {
2553        return getKeyguardDisabledFeatures(admin, UserHandle.myUserId());
2554    }
2555
2556    /** @hide per-user version */
2557    public int getKeyguardDisabledFeatures(ComponentName admin, int userHandle) {
2558        if (mService != null) {
2559            try {
2560                return mService.getKeyguardDisabledFeatures(admin, userHandle);
2561            } catch (RemoteException e) {
2562                Log.w(TAG, "Failed talking with device policy service", e);
2563            }
2564        }
2565        return KEYGUARD_DISABLE_FEATURES_NONE;
2566    }
2567
2568    /**
2569     * @hide
2570     */
2571    public void setActiveAdmin(ComponentName policyReceiver, boolean refreshing, int userHandle) {
2572        if (mService != null) {
2573            try {
2574                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
2575            } catch (RemoteException e) {
2576                Log.w(TAG, "Failed talking with device policy service", e);
2577            }
2578        }
2579    }
2580
2581    /**
2582     * @hide
2583     */
2584    public void setActiveAdmin(ComponentName policyReceiver, boolean refreshing) {
2585        setActiveAdmin(policyReceiver, refreshing, UserHandle.myUserId());
2586    }
2587
2588    /**
2589     * Returns the DeviceAdminInfo as defined by the administrator's package info & meta-data
2590     * @hide
2591     */
2592    public DeviceAdminInfo getAdminInfo(ComponentName cn) {
2593        ActivityInfo ai;
2594        try {
2595            ai = mContext.getPackageManager().getReceiverInfo(cn,
2596                    PackageManager.GET_META_DATA);
2597        } catch (PackageManager.NameNotFoundException e) {
2598            Log.w(TAG, "Unable to retrieve device policy " + cn, e);
2599            return null;
2600        }
2601
2602        ResolveInfo ri = new ResolveInfo();
2603        ri.activityInfo = ai;
2604
2605        try {
2606            return new DeviceAdminInfo(mContext, ri);
2607        } catch (XmlPullParserException e) {
2608            Log.w(TAG, "Unable to parse device policy " + cn, e);
2609            return null;
2610        } catch (IOException e) {
2611            Log.w(TAG, "Unable to parse device policy " + cn, e);
2612            return null;
2613        }
2614    }
2615
2616    /**
2617     * @hide
2618     */
2619    public void getRemoveWarning(ComponentName admin, RemoteCallback result) {
2620        if (mService != null) {
2621            try {
2622                mService.getRemoveWarning(admin, result, UserHandle.myUserId());
2623            } catch (RemoteException e) {
2624                Log.w(TAG, "Failed talking with device policy service", e);
2625            }
2626        }
2627    }
2628
2629    /**
2630     * @hide
2631     */
2632    public void setActivePasswordState(int quality, int length, int letters, int uppercase,
2633            int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
2634        if (mService != null) {
2635            try {
2636                mService.setActivePasswordState(quality, length, letters, uppercase, lowercase,
2637                        numbers, symbols, nonletter, userHandle);
2638            } catch (RemoteException e) {
2639                Log.w(TAG, "Failed talking with device policy service", e);
2640            }
2641        }
2642    }
2643
2644    /**
2645     * @hide
2646     */
2647    public void reportFailedPasswordAttempt(int userHandle) {
2648        if (mService != null) {
2649            try {
2650                mService.reportFailedPasswordAttempt(userHandle);
2651            } catch (RemoteException e) {
2652                Log.w(TAG, "Failed talking with device policy service", e);
2653            }
2654        }
2655    }
2656
2657    /**
2658     * @hide
2659     */
2660    public void reportSuccessfulPasswordAttempt(int userHandle) {
2661        if (mService != null) {
2662            try {
2663                mService.reportSuccessfulPasswordAttempt(userHandle);
2664            } catch (RemoteException e) {
2665                Log.w(TAG, "Failed talking with device policy service", e);
2666            }
2667        }
2668    }
2669
2670    /**
2671     * @hide
2672     * Sets the given package as the device owner.
2673     * Same as {@link #setDeviceOwner(String, String)} but without setting a device owner name.
2674     * @param packageName the package name of the application to be registered as the device owner.
2675     * @return whether the package was successfully registered as the device owner.
2676     * @throws IllegalArgumentException if the package name is null or invalid
2677     * @throws IllegalStateException If the preconditions mentioned are not met.
2678     */
2679    public boolean setDeviceOwner(String packageName) throws IllegalArgumentException,
2680            IllegalStateException {
2681        return setDeviceOwner(packageName, null);
2682    }
2683
2684    /**
2685     * @hide
2686     * Sets the given package as the device owner. The package must already be installed. There
2687     * must not already be a device owner.
2688     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
2689     * this method.
2690     * Calling this after the setup phase of the primary user has completed is allowed only if
2691     * the caller is the shell uid, and there are no additional users and no accounts.
2692     * @param packageName the package name of the application to be registered as the device owner.
2693     * @param ownerName the human readable name of the institution that owns this device.
2694     * @return whether the package was successfully registered as the device owner.
2695     * @throws IllegalArgumentException if the package name is null or invalid
2696     * @throws IllegalStateException If the preconditions mentioned are not met.
2697     */
2698    public boolean setDeviceOwner(String packageName, String ownerName)
2699            throws IllegalArgumentException, IllegalStateException {
2700        if (mService != null) {
2701            try {
2702                return mService.setDeviceOwner(packageName, ownerName);
2703            } catch (RemoteException re) {
2704                Log.w(TAG, "Failed to set device owner");
2705            }
2706        }
2707        return false;
2708    }
2709
2710    /**
2711     * Used to determine if a particular package has been registered as a Device Owner app.
2712     * A device owner app is a special device admin that cannot be deactivated by the user, once
2713     * activated as a device admin. It also cannot be uninstalled. To check if a particular
2714     * package is currently registered as the device owner app, pass in the package name from
2715     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
2716     * admin apps that want to check if they are also registered as the device owner app. The
2717     * exact mechanism by which a device admin app is registered as a device owner app is defined by
2718     * the setup process.
2719     * @param packageName the package name of the app, to compare with the registered device owner
2720     * app, if any.
2721     * @return whether or not the package is registered as the device owner app.
2722     */
2723    public boolean isDeviceOwnerApp(String packageName) {
2724        if (mService != null) {
2725            try {
2726                return mService.isDeviceOwner(packageName);
2727            } catch (RemoteException re) {
2728                Log.w(TAG, "Failed to check device owner");
2729            }
2730        }
2731        return false;
2732    }
2733
2734    /**
2735     * @hide
2736     * Redirect to isDeviceOwnerApp.
2737     */
2738    public boolean isDeviceOwner(String packageName) {
2739        return isDeviceOwnerApp(packageName);
2740    }
2741
2742    /**
2743     * Clears the current device owner.  The caller must be the device owner.
2744     *
2745     * This function should be used cautiously as once it is called it cannot
2746     * be undone.  The device owner can only be set as a part of device setup
2747     * before setup completes.
2748     *
2749     * @param packageName The package name of the device owner.
2750     */
2751    public void clearDeviceOwnerApp(String packageName) {
2752        if (mService != null) {
2753            try {
2754                mService.clearDeviceOwner(packageName);
2755            } catch (RemoteException re) {
2756                Log.w(TAG, "Failed to clear device owner");
2757            }
2758        }
2759    }
2760
2761    /** @hide */
2762    @SystemApi
2763    public String getDeviceOwner() {
2764        if (mService != null) {
2765            try {
2766                return mService.getDeviceOwner();
2767            } catch (RemoteException re) {
2768                Log.w(TAG, "Failed to get device owner");
2769            }
2770        }
2771        return null;
2772    }
2773
2774    /** @hide */
2775    public String getDeviceOwnerName() {
2776        if (mService != null) {
2777            try {
2778                return mService.getDeviceOwnerName();
2779            } catch (RemoteException re) {
2780                Log.w(TAG, "Failed to get device owner");
2781            }
2782        }
2783        return null;
2784    }
2785
2786    /**
2787     * Sets the given component as the device initializer. The package must already be installed and
2788     * set as an active device administrator, and there must not be an existing device initializer,
2789     * for this call to succeed. This method can only be called by an app holding the
2790     * MANAGE_DEVICE_ADMINS permission before the device is provisioned or by a device owner app. A
2791     * device initializer app is granted device owner privileges during device initialization and
2792     * profile owner privileges during secondary user initialization.
2793     * @param who Which {@link DeviceAdminReceiver} this request is associated with, or null if not
2794     *        called by the device owner.
2795     * @param initializer Which {@link DeviceAdminReceiver} to make device initializer.
2796     * @param initializerName The user-visible name of the device initializer.
2797     * @return whether the component was successfully registered as the device initializer.
2798     * @throws IllegalArgumentException if the componentname is null or invalid
2799     * @throws IllegalStateException if the caller is not device owner or the device has
2800     *         already been provisioned or a device initializer already exists.
2801     */
2802    public boolean setDeviceInitializer(ComponentName who, ComponentName initializer,
2803            String initializerName) throws IllegalArgumentException, IllegalStateException {
2804        if (mService != null) {
2805            try {
2806                return mService.setDeviceInitializer(who, initializer, initializerName);
2807            } catch (RemoteException re) {
2808                Log.w(TAG, "Failed to set device initializer");
2809            }
2810        }
2811        return false;
2812    }
2813
2814    /**
2815     * Used to determine if a particular package has been registered as the device initializer.
2816     *
2817     * @param packageName the package name of the app, to compare with the registered device
2818     *        initializer app, if any.
2819     * @return whether or not the caller is registered as the device initializer app.
2820     */
2821    public boolean isDeviceInitializerApp(String packageName) {
2822        if (mService != null) {
2823            try {
2824                return mService.isDeviceInitializer(packageName);
2825            } catch (RemoteException re) {
2826                Log.w(TAG, "Failed to check device initializer");
2827            }
2828        }
2829        return false;
2830    }
2831
2832    /**
2833     * Removes the device initializer, so that it will not be invoked on user initialization for any
2834     * subsequently created users. This method can be called by either the device owner or device
2835     * initializer itself. The caller must be an active administrator.
2836     *
2837     * @param who Which {@link DeviceAdminReceiver} this request is associated with.
2838     */
2839    public void clearDeviceInitializerApp(ComponentName who) {
2840        if (mService != null) {
2841            try {
2842                mService.clearDeviceInitializer(who);
2843            } catch (RemoteException re) {
2844                Log.w(TAG, "Failed to clear device initializer");
2845            }
2846        }
2847    }
2848
2849    /**
2850     * @hide
2851     * Gets the device initializer of the system.
2852     *
2853     * @return the package name of the device initializer.
2854     */
2855    @SystemApi
2856    public String getDeviceInitializerApp() {
2857        if (mService != null) {
2858            try {
2859                return mService.getDeviceInitializer();
2860            } catch (RemoteException re) {
2861                Log.w(TAG, "Failed to get device initializer");
2862            }
2863        }
2864        return null;
2865    }
2866
2867    /**
2868     * @hide
2869     * Gets the device initializer component of the system.
2870     *
2871     * @return the component name of the device initializer.
2872     */
2873    @SystemApi
2874    public ComponentName getDeviceInitializerComponent() {
2875        if (mService != null) {
2876            try {
2877                return mService.getDeviceInitializerComponent();
2878            } catch (RemoteException re) {
2879                Log.w(TAG, "Failed to get device initializer");
2880            }
2881        }
2882        return null;
2883    }
2884
2885
2886    /**
2887     * Sets the enabled state of the user. A user should be enabled only once it is ready to
2888     * be used.
2889     *
2890     * <p>Device initializer must call this method to mark the user as functional.
2891     * Only the device initializer agent can call this.
2892     *
2893     * <p>When the user is enabled, if the device initializer is not also the device owner, the
2894     * device initializer will no longer have elevated permissions to call methods in this class.
2895     * Additionally, it will be removed as an active administrator and its
2896     * {@link DeviceAdminReceiver} will be disabled.
2897     *
2898     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2899     * @return whether the user is now enabled.
2900     */
2901    public boolean setUserEnabled(ComponentName admin) {
2902        if (mService != null) {
2903            try {
2904                return mService.setUserEnabled(admin);
2905            } catch (RemoteException e) {
2906                Log.w(TAG, "Failed talking with device policy service", e);
2907            }
2908        }
2909        return false;
2910    }
2911
2912    /**
2913     * @hide
2914     * @deprecated Use #ACTION_SET_PROFILE_OWNER
2915     * Sets the given component as an active admin and registers the package as the profile
2916     * owner for this user. The package must already be installed and there shouldn't be
2917     * an existing profile owner registered for this user. Also, this method must be called
2918     * before the user setup has been completed.
2919     * <p>
2920     * This method can only be called by system apps that hold MANAGE_USERS permission and
2921     * MANAGE_DEVICE_ADMINS permission.
2922     * @param admin The component to register as an active admin and profile owner.
2923     * @param ownerName The user-visible name of the entity that is managing this user.
2924     * @return whether the admin was successfully registered as the profile owner.
2925     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
2926     *         the user has already been set up.
2927     */
2928    @SystemApi
2929    public boolean setActiveProfileOwner(ComponentName admin, @Deprecated String ownerName)
2930            throws IllegalArgumentException {
2931        if (mService != null) {
2932            try {
2933                final int myUserId = UserHandle.myUserId();
2934                mService.setActiveAdmin(admin, false, myUserId);
2935                return mService.setProfileOwner(admin, ownerName, myUserId);
2936            } catch (RemoteException re) {
2937                Log.w(TAG, "Failed to set profile owner " + re);
2938                throw new IllegalArgumentException("Couldn't set profile owner.", re);
2939            }
2940        }
2941        return false;
2942    }
2943
2944    /**
2945     * @hide
2946     * Clears the active profile owner and removes all user restrictions. The caller must
2947     * be from the same package as the active profile owner for this user, otherwise a
2948     * SecurityException will be thrown.
2949     *
2950     * @param admin The component to remove as the profile owner.
2951     * @return
2952     */
2953    @SystemApi
2954    public void clearProfileOwner(ComponentName admin) {
2955        if (mService != null) {
2956            try {
2957                mService.clearProfileOwner(admin);
2958            } catch (RemoteException re) {
2959                Log.w(TAG, "Failed to clear profile owner " + admin + re);
2960            }
2961        }
2962    }
2963
2964    /**
2965     * @hide
2966     * Checks if the user was already setup.
2967     */
2968    public boolean hasUserSetupCompleted() {
2969        if (mService != null) {
2970            try {
2971                return mService.hasUserSetupCompleted();
2972            } catch (RemoteException re) {
2973                Log.w(TAG, "Failed to check if user setup has completed");
2974            }
2975        }
2976        return true;
2977    }
2978
2979    /**
2980     * @hide
2981     * Sets the given component as the profile owner of the given user profile. The package must
2982     * already be installed. There must not already be a profile owner for this user.
2983     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
2984     * this method.
2985     * Calling this after the setup phase of the specified user has completed is allowed only if:
2986     * - the caller is SYSTEM_UID.
2987     * - or the caller is the shell uid, and there are no accounts on the specified user.
2988     * @param admin the component name to be registered as profile owner.
2989     * @param ownerName the human readable name of the organisation associated with this DPM.
2990     * @param userHandle the userId to set the profile owner for.
2991     * @return whether the component was successfully registered as the profile owner.
2992     * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
2993     * preconditions mentioned are not met.
2994     */
2995    public boolean setProfileOwner(ComponentName admin, @Deprecated String ownerName,
2996            int userHandle) throws IllegalArgumentException {
2997        if (admin == null) {
2998            throw new NullPointerException("admin cannot be null");
2999        }
3000        if (mService != null) {
3001            try {
3002                if (ownerName == null) {
3003                    ownerName = "";
3004                }
3005                return mService.setProfileOwner(admin, ownerName, userHandle);
3006            } catch (RemoteException re) {
3007                Log.w(TAG, "Failed to set profile owner", re);
3008                throw new IllegalArgumentException("Couldn't set profile owner.", re);
3009            }
3010        }
3011        return false;
3012    }
3013
3014    /**
3015     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
3016     * be used. Only the profile owner can call this.
3017     *
3018     * @see #isProfileOwnerApp
3019     *
3020     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3021     */
3022    public void setProfileEnabled(ComponentName admin) {
3023        if (mService != null) {
3024            try {
3025                mService.setProfileEnabled(admin);
3026            } catch (RemoteException e) {
3027                Log.w(TAG, "Failed talking with device policy service", e);
3028            }
3029        }
3030    }
3031
3032    /**
3033     * Sets the name of the profile. In the device owner case it sets the name of the user
3034     * which it is called from. Only a profile owner or device owner can call this. If this is
3035     * never called by the profile or device owner, the name will be set to default values.
3036     *
3037     * @see #isProfileOwnerApp
3038     * @see #isDeviceOwnerApp
3039     *
3040     * @param profileName The name of the profile.
3041     */
3042    public void setProfileName(ComponentName who, String profileName) {
3043        if (mService != null) {
3044            try {
3045            mService.setProfileName(who, profileName);
3046        } catch (RemoteException e) {
3047            Log.w(TAG, "Failed talking with device policy service", e);
3048        }
3049    }
3050}
3051
3052    /**
3053     * Used to determine if a particular package is registered as the profile owner for the
3054     * current user. A profile owner is a special device admin that has additional privileges
3055     * within the profile.
3056     *
3057     * @param packageName The package name of the app to compare with the registered profile owner.
3058     * @return Whether or not the package is registered as the profile owner.
3059     */
3060    public boolean isProfileOwnerApp(String packageName) {
3061        if (mService != null) {
3062            try {
3063                ComponentName profileOwner = mService.getProfileOwner(
3064                        Process.myUserHandle().getIdentifier());
3065                return profileOwner != null
3066                        && profileOwner.getPackageName().equals(packageName);
3067            } catch (RemoteException re) {
3068                Log.w(TAG, "Failed to check profile owner");
3069            }
3070        }
3071        return false;
3072    }
3073
3074    /**
3075     * @hide
3076     * @return the packageName of the owner of the given user profile or null if no profile
3077     * owner has been set for that user.
3078     * @throws IllegalArgumentException if the userId is invalid.
3079     */
3080    @SystemApi
3081    public ComponentName getProfileOwner() throws IllegalArgumentException {
3082        return getProfileOwnerAsUser(Process.myUserHandle().getIdentifier());
3083    }
3084
3085    /**
3086     * @see #getProfileOwner()
3087     * @hide
3088     */
3089    public ComponentName getProfileOwnerAsUser(final int userId) throws IllegalArgumentException {
3090        if (mService != null) {
3091            try {
3092                return mService.getProfileOwner(userId);
3093            } catch (RemoteException re) {
3094                Log.w(TAG, "Failed to get profile owner");
3095                throw new IllegalArgumentException(
3096                        "Requested profile owner for invalid userId", re);
3097            }
3098        }
3099        return null;
3100    }
3101
3102    /**
3103     * @hide
3104     * @return the human readable name of the organisation associated with this DPM or null if
3105     *         one is not set.
3106     * @throws IllegalArgumentException if the userId is invalid.
3107     */
3108    public String getProfileOwnerName() throws IllegalArgumentException {
3109        if (mService != null) {
3110            try {
3111                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
3112            } catch (RemoteException re) {
3113                Log.w(TAG, "Failed to get profile owner");
3114                throw new IllegalArgumentException(
3115                        "Requested profile owner for invalid userId", re);
3116            }
3117        }
3118        return null;
3119    }
3120
3121    /**
3122     * @hide
3123     * @param user The user for whom to fetch the profile owner name, if any.
3124     * @return the human readable name of the organisation associated with this profile owner or
3125     *         null if one is not set.
3126     * @throws IllegalArgumentException if the userId is invalid.
3127     */
3128    @SystemApi
3129    public String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
3130        if (mService != null) {
3131            try {
3132                return mService.getProfileOwnerName(userId);
3133            } catch (RemoteException re) {
3134                Log.w(TAG, "Failed to get profile owner");
3135                throw new IllegalArgumentException(
3136                        "Requested profile owner for invalid userId", re);
3137            }
3138        }
3139        return null;
3140    }
3141
3142    /**
3143     * Called by a profile owner or device owner to add a default intent handler activity for
3144     * intents that match a certain intent filter. This activity will remain the default intent
3145     * handler even if the set of potential event handlers for the intent filter changes and if
3146     * the intent preferences are reset.
3147     *
3148     * <p>The default disambiguation mechanism takes over if the activity is not installed
3149     * (anymore). When the activity is (re)installed, it is automatically reset as default
3150     * intent handler for the filter.
3151     *
3152     * <p>The calling device admin must be a profile owner or device owner. If it is not, a
3153     * security exception will be thrown.
3154     *
3155     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3156     * @param filter The IntentFilter for which a default handler is added.
3157     * @param activity The Activity that is added as default intent handler.
3158     */
3159    public void addPersistentPreferredActivity(ComponentName admin, IntentFilter filter,
3160            ComponentName activity) {
3161        if (mService != null) {
3162            try {
3163                mService.addPersistentPreferredActivity(admin, filter, activity);
3164            } catch (RemoteException e) {
3165                Log.w(TAG, "Failed talking with device policy service", e);
3166            }
3167        }
3168    }
3169
3170    /**
3171     * Called by a profile owner or device owner to remove all persistent intent handler preferences
3172     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
3173     *
3174     * <p>The calling device admin must be a profile owner. If it is not, a security
3175     * exception will be thrown.
3176     *
3177     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3178     * @param packageName The name of the package for which preferences are removed.
3179     */
3180    public void clearPackagePersistentPreferredActivities(ComponentName admin,
3181            String packageName) {
3182        if (mService != null) {
3183            try {
3184                mService.clearPackagePersistentPreferredActivities(admin, packageName);
3185            } catch (RemoteException e) {
3186                Log.w(TAG, "Failed talking with device policy service", e);
3187            }
3188        }
3189    }
3190
3191    /**
3192     * Called by a profile or device owner to set the application restrictions for a given target
3193     * application running in the profile.
3194     *
3195     * <p>The provided {@link Bundle} consists of key-value pairs, where the types of values may be
3196     * boolean, int, String, or String[].
3197     *
3198     * <p>The application restrictions are only made visible to the target application and the
3199     * profile or device owner.
3200     *
3201     * <p>If the restrictions are not available yet, but may be applied in the near future,
3202     * the admin can notify the target application of that by adding
3203     * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
3204     *
3205     * <p>The calling device admin must be a profile or device owner; if it is not, a security
3206     * exception will be thrown.
3207     *
3208     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3209     * @param packageName The name of the package to update restricted settings for.
3210     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
3211     * set of active restrictions.
3212     *
3213     * @see UserManager#KEY_RESTRICTIONS_PENDING
3214     */
3215    public void setApplicationRestrictions(ComponentName admin, String packageName,
3216            Bundle settings) {
3217        if (mService != null) {
3218            try {
3219                mService.setApplicationRestrictions(admin, packageName, settings);
3220            } catch (RemoteException e) {
3221                Log.w(TAG, "Failed talking with device policy service", e);
3222            }
3223        }
3224    }
3225
3226    /**
3227     * Sets a list of configuration features to enable for a TrustAgent component. This is meant
3228     * to be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all
3229     * trust agents but those enabled by this function call. If flag
3230     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
3231     *
3232     * <p>The calling device admin must have requested
3233     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call
3234     * this method; if not, a security exception will be thrown.
3235     *
3236     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3237     * @param target Component name of the agent to be enabled.
3238     * @param configuration TrustAgent-specific feature bundle. If null for any admin, agent
3239     * will be strictly disabled according to the state of the
3240     *  {@link #KEYGUARD_DISABLE_TRUST_AGENTS} flag.
3241     * <p>If {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is set and options is not null for all admins,
3242     * then it's up to the TrustAgent itself to aggregate the values from all device admins.
3243     * <p>Consult documentation for the specific TrustAgent to determine legal options parameters.
3244     */
3245    public void setTrustAgentConfiguration(ComponentName admin, ComponentName target,
3246            PersistableBundle configuration) {
3247        if (mService != null) {
3248            try {
3249                mService.setTrustAgentConfiguration(admin, target, configuration);
3250            } catch (RemoteException e) {
3251                Log.w(TAG, "Failed talking with device policy service", e);
3252            }
3253        }
3254    }
3255
3256    /**
3257     * Gets configuration for the given trust agent based on aggregating all calls to
3258     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
3259     * all device admins.
3260     *
3261     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
3262     * this function returns a list of configurations for all admins that declare
3263     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
3264     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
3265     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
3266     * for this {@param agent} or calls it with a null configuration, null is returned.
3267     * @param agent Which component to get enabled features for.
3268     * @return configuration for the given trust agent.
3269     */
3270    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
3271            ComponentName agent) {
3272        return getTrustAgentConfiguration(admin, agent, UserHandle.myUserId());
3273    }
3274
3275    /** @hide per-user version */
3276    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
3277            ComponentName agent, int userHandle) {
3278        if (mService != null) {
3279            try {
3280                return mService.getTrustAgentConfiguration(admin, agent, userHandle);
3281            } catch (RemoteException e) {
3282                Log.w(TAG, "Failed talking with device policy service", e);
3283            }
3284        }
3285        return new ArrayList<PersistableBundle>(); // empty list
3286    }
3287
3288    /**
3289     * Called by a profile owner of a managed profile to set whether caller-Id information from
3290     * the managed profile will be shown in the parent profile, for incoming calls.
3291     *
3292     * <p>The calling device admin must be a profile owner. If it is not, a
3293     * security exception will be thrown.
3294     *
3295     * @param who Which {@link DeviceAdminReceiver} this request is associated with.
3296     * @param disabled If true caller-Id information in the managed profile is not displayed.
3297     */
3298    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
3299        if (mService != null) {
3300            try {
3301                mService.setCrossProfileCallerIdDisabled(who, disabled);
3302            } catch (RemoteException e) {
3303                Log.w(TAG, "Failed talking with device policy service", e);
3304            }
3305        }
3306    }
3307
3308    /**
3309     * Called by a profile owner of a managed profile to determine whether or not caller-Id
3310     * information has been disabled.
3311     *
3312     * <p>The calling device admin must be a profile owner. If it is not, a
3313     * security exception will be thrown.
3314     *
3315     * @param who Which {@link DeviceAdminReceiver} this request is associated with.
3316     */
3317    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
3318        if (mService != null) {
3319            try {
3320                return mService.getCrossProfileCallerIdDisabled(who);
3321            } catch (RemoteException e) {
3322                Log.w(TAG, "Failed talking with device policy service", e);
3323            }
3324        }
3325        return false;
3326    }
3327
3328    /**
3329     * Determine whether or not caller-Id information has been disabled.
3330     *
3331     * @param userHandle The user for whom to check the caller-id permission
3332     * @hide
3333     */
3334    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
3335        if (mService != null) {
3336            try {
3337                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
3338            } catch (RemoteException e) {
3339                Log.w(TAG, "Failed talking with device policy service", e);
3340            }
3341        }
3342        return false;
3343    }
3344
3345    /**
3346     * Start Quick Contact on the managed profile for the current user, if the policy allows.
3347     * @hide
3348     */
3349    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
3350            Intent originalIntent) {
3351        if (mService != null) {
3352            try {
3353                mService.startManagedQuickContact(
3354                        actualLookupKey, actualContactId, originalIntent);
3355            } catch (RemoteException e) {
3356                Log.w(TAG, "Failed talking with device policy service", e);
3357            }
3358        }
3359    }
3360
3361    /**
3362     * Called by a profile owner of a managed profile to set whether bluetooth
3363     * devices can access enterprise contacts.
3364     * <p>
3365     * The calling device admin must be a profile owner. If it is not, a
3366     * security exception will be thrown.
3367     * <p>
3368     * This API works on managed profile only.
3369     *
3370     * @param who Which {@link DeviceAdminReceiver} this request is associated
3371     *            with.
3372     * @param disabled If true, bluetooth devices cannot access enterprise
3373     *            contacts.
3374     */
3375    public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
3376        if (mService != null) {
3377            try {
3378                mService.setBluetoothContactSharingDisabled(who, disabled);
3379            } catch (RemoteException e) {
3380                Log.w(TAG, "Failed talking with device policy service", e);
3381            }
3382        }
3383    }
3384
3385    /**
3386     * Called by a profile owner of a managed profile to determine whether or
3387     * not Bluetooth devices cannot access enterprise contacts.
3388     * <p>
3389     * The calling device admin must be a profile owner. If it is not, a
3390     * security exception will be thrown.
3391     * <p>
3392     * This API works on managed profile only.
3393     *
3394     * @param who Which {@link DeviceAdminReceiver} this request is associated
3395     *            with.
3396     */
3397    public boolean getBluetoothContactSharingDisabled(ComponentName who) {
3398        if (mService != null) {
3399            try {
3400                return mService.getBluetoothContactSharingDisabled(who);
3401            } catch (RemoteException e) {
3402                Log.w(TAG, "Failed talking with device policy service", e);
3403            }
3404        }
3405        return true;
3406    }
3407
3408    /**
3409     * Determine whether or not Bluetooth devices cannot access contacts.
3410     * <p>
3411     * This API works on managed profile UserHandle only.
3412     *
3413     * @param userHandle The user for whom to check the caller-id permission
3414     * @hide
3415     */
3416    public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
3417        if (mService != null) {
3418            try {
3419                return mService.getBluetoothContactSharingDisabledForUser(userHandle
3420                        .getIdentifier());
3421            } catch (RemoteException e) {
3422                Log.w(TAG, "Failed talking with device policy service", e);
3423            }
3424        }
3425        return true;
3426    }
3427
3428    /**
3429     * Called by the profile owner of a managed profile so that some intents sent in the managed
3430     * profile can also be resolved in the parent, or vice versa.
3431     * Only activity intents are supported.
3432     *
3433     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3434     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
3435     * other profile
3436     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
3437     * {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
3438     */
3439    public void addCrossProfileIntentFilter(ComponentName admin, IntentFilter filter, int flags) {
3440        if (mService != null) {
3441            try {
3442                mService.addCrossProfileIntentFilter(admin, filter, flags);
3443            } catch (RemoteException e) {
3444                Log.w(TAG, "Failed talking with device policy service", e);
3445            }
3446        }
3447    }
3448
3449    /**
3450     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
3451     * that go from the managed profile to the parent, or from the parent to the managed profile.
3452     * Only removes those that have been set by the profile owner.
3453     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3454     */
3455    public void clearCrossProfileIntentFilters(ComponentName admin) {
3456        if (mService != null) {
3457            try {
3458                mService.clearCrossProfileIntentFilters(admin);
3459            } catch (RemoteException e) {
3460                Log.w(TAG, "Failed talking with device policy service", e);
3461            }
3462        }
3463    }
3464
3465    /**
3466     * Called by a profile or device owner to set the permitted accessibility services. When
3467     * set by a device owner or profile owner the restriction applies to all profiles of the
3468     * user the device owner or profile owner is an admin for.
3469     *
3470     * By default the user can use any accessiblity service. When zero or more packages have
3471     * been added, accessiblity services that are not in the list and not part of the system
3472     * can not be enabled by the user.
3473     *
3474     * <p> Calling with a null value for the list disables the restriction so that all services
3475     * can be used, calling with an empty list only allows the builtin system's services.
3476     *
3477     * <p> System accesibility services are always available to the user the list can't modify
3478     * this.
3479     *
3480     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3481     * @param packageNames List of accessibility service package names.
3482     *
3483     * @return true if setting the restriction succeeded. It fail if there is
3484     * one or more non-system accessibility services enabled, that are not in the list.
3485     */
3486    public boolean setPermittedAccessibilityServices(ComponentName admin,
3487            List<String> packageNames) {
3488        if (mService != null) {
3489            try {
3490                return mService.setPermittedAccessibilityServices(admin, packageNames);
3491            } catch (RemoteException e) {
3492                Log.w(TAG, "Failed talking with device policy service", e);
3493            }
3494        }
3495        return false;
3496    }
3497
3498    /**
3499     * Returns the list of permitted accessibility services set by this device or profile owner.
3500     *
3501     * <p>An empty list means no accessibility services except system services are allowed.
3502     * Null means all accessibility services are allowed.
3503     *
3504     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3505     * @return List of accessiblity service package names.
3506     */
3507    public List<String> getPermittedAccessibilityServices(ComponentName admin) {
3508        if (mService != null) {
3509            try {
3510                return mService.getPermittedAccessibilityServices(admin);
3511            } catch (RemoteException e) {
3512                Log.w(TAG, "Failed talking with device policy service", e);
3513            }
3514        }
3515        return null;
3516    }
3517
3518    /**
3519     * Returns the list of accessibility services permitted by the device or profiles
3520     * owners of this user.
3521     *
3522     * <p>Null means all accessibility services are allowed, if a non-null list is returned
3523     * it will contain the intersection of the permitted lists for any device or profile
3524     * owners that apply to this user. It will also include any system accessibility services.
3525     *
3526     * @param userId which user to check for.
3527     * @return List of accessiblity service package names.
3528     * @hide
3529     */
3530     @SystemApi
3531     public List<String> getPermittedAccessibilityServices(int userId) {
3532        if (mService != null) {
3533            try {
3534                return mService.getPermittedAccessibilityServicesForUser(userId);
3535            } catch (RemoteException e) {
3536                Log.w(TAG, "Failed talking with device policy service", e);
3537            }
3538        }
3539        return null;
3540     }
3541
3542    /**
3543     * Called by a profile or device owner to set the permitted input methods services. When
3544     * set by a device owner or profile owner the restriction applies to all profiles of the
3545     * user the device owner or profile owner is an admin for.
3546     *
3547     * By default the user can use any input method. When zero or more packages have
3548     * been added, input method that are not in the list and not part of the system
3549     * can not be enabled by the user.
3550     *
3551     * This method will fail if it is called for a admin that is not for the foreground user
3552     * or a profile of the foreground user.
3553     *
3554     * <p> Calling with a null value for the list disables the restriction so that all input methods
3555     * can be used, calling with an empty list disables all but the system's own input methods.
3556     *
3557     * <p> System input methods are always available to the user this method can't modify this.
3558     *
3559     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3560     * @param packageNames List of input method package names.
3561     * @return true if setting the restriction succeeded. It will fail if there are
3562     *     one or more non-system input methods currently enabled that are not in
3563     *     the packageNames list.
3564     */
3565    public boolean setPermittedInputMethods(ComponentName admin, List<String> packageNames) {
3566        if (mService != null) {
3567            try {
3568                return mService.setPermittedInputMethods(admin, packageNames);
3569            } catch (RemoteException e) {
3570                Log.w(TAG, "Failed talking with device policy service", e);
3571            }
3572        }
3573        return false;
3574    }
3575
3576
3577    /**
3578     * Returns the list of permitted input methods set by this device or profile owner.
3579     *
3580     * <p>An empty list means no input methods except system input methods are allowed.
3581     * Null means all input methods are allowed.
3582     *
3583     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3584     * @return List of input method package names.
3585     */
3586    public List<String> getPermittedInputMethods(ComponentName admin) {
3587        if (mService != null) {
3588            try {
3589                return mService.getPermittedInputMethods(admin);
3590            } catch (RemoteException e) {
3591                Log.w(TAG, "Failed talking with device policy service", e);
3592            }
3593        }
3594        return null;
3595    }
3596
3597    /**
3598     * Returns the list of input methods permitted by the device or profiles
3599     * owners of the current user.
3600     *
3601     * <p>Null means all input methods are allowed, if a non-null list is returned
3602     * it will contain the intersection of the permitted lists for any device or profile
3603     * owners that apply to this user. It will also include any system input methods.
3604     *
3605     * @return List of input method package names.
3606     * @hide
3607     */
3608    @SystemApi
3609    public List<String> getPermittedInputMethodsForCurrentUser() {
3610        if (mService != null) {
3611            try {
3612                return mService.getPermittedInputMethodsForCurrentUser();
3613            } catch (RemoteException e) {
3614                Log.w(TAG, "Failed talking with device policy service", e);
3615            }
3616        }
3617        return null;
3618    }
3619
3620    /**
3621     * Called by a device owner to create a user with the specified name. The UserHandle returned
3622     * by this method should not be persisted as user handles are recycled as users are removed and
3623     * created. If you need to persist an identifier for this user, use
3624     * {@link UserManager#getSerialNumberForUser}.
3625     *
3626     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3627     * @param name the user's name
3628     * @see UserHandle
3629     * @return the UserHandle object for the created user, or null if the user could not be created.
3630     */
3631    public UserHandle createUser(ComponentName admin, String name) {
3632        try {
3633            return mService.createUser(admin, name);
3634        } catch (RemoteException re) {
3635            Log.w(TAG, "Could not create a user", re);
3636        }
3637        return null;
3638    }
3639
3640    /**
3641     * Called by a device owner to create a user with the specified name. The UserHandle returned
3642     * by this method should not be persisted as user handles are recycled as users are removed and
3643     * created. If you need to persist an identifier for this user, use
3644     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
3645     * immediately.
3646     *
3647     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
3648     * as registered as an active admin on the new user.  The profile owner package will be
3649     * installed on the new user if it already is installed on the device.
3650     *
3651     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
3652     * profileOwnerComponent when onEnable is called.
3653     *
3654     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3655     * @param name the user's name
3656     * @param ownerName the human readable name of the organisation associated with this DPM.
3657     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
3658     *      the user.
3659     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
3660     *      on the new user.
3661     * @see UserHandle
3662     * @return the UserHandle object for the created user, or null if the user could not be created.
3663     */
3664    public UserHandle createAndInitializeUser(ComponentName admin, String name, String ownerName,
3665            ComponentName profileOwnerComponent, Bundle adminExtras) {
3666        try {
3667            return mService.createAndInitializeUser(admin, name, ownerName, profileOwnerComponent,
3668                    adminExtras);
3669        } catch (RemoteException re) {
3670            Log.w(TAG, "Could not create a user", re);
3671        }
3672        return null;
3673    }
3674
3675    /**
3676     * Called by a device owner to remove a user and all associated data. The primary user can
3677     * not be removed.
3678     *
3679     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3680     * @param userHandle the user to remove.
3681     * @return {@code true} if the user was removed, {@code false} otherwise.
3682     */
3683    public boolean removeUser(ComponentName admin, UserHandle userHandle) {
3684        try {
3685            return mService.removeUser(admin, userHandle);
3686        } catch (RemoteException re) {
3687            Log.w(TAG, "Could not remove user ", re);
3688            return false;
3689        }
3690    }
3691
3692    /**
3693     * Called by a device owner to switch the specified user to the foreground.
3694     *
3695     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3696     * @param userHandle the user to switch to; null will switch to primary.
3697     * @return {@code true} if the switch was successful, {@code false} otherwise.
3698     *
3699     * @see Intent#ACTION_USER_FOREGROUND
3700     */
3701    public boolean switchUser(ComponentName admin, UserHandle userHandle) {
3702        try {
3703            return mService.switchUser(admin, userHandle);
3704        } catch (RemoteException re) {
3705            Log.w(TAG, "Could not switch user ", re);
3706            return false;
3707        }
3708    }
3709
3710    /**
3711     * Called by a profile or device owner to get the application restrictions for a given target
3712     * application running in the profile.
3713     *
3714     * <p>The calling device admin must be a profile or device owner; if it is not, a security
3715     * exception will be thrown.
3716     *
3717     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3718     * @param packageName The name of the package to fetch restricted settings of.
3719     * @return {@link Bundle} of settings corresponding to what was set last time
3720     * {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty {@link Bundle}
3721     * if no restrictions have been set.
3722     */
3723    public Bundle getApplicationRestrictions(ComponentName admin, String packageName) {
3724        if (mService != null) {
3725            try {
3726                return mService.getApplicationRestrictions(admin, packageName);
3727            } catch (RemoteException e) {
3728                Log.w(TAG, "Failed talking with device policy service", e);
3729            }
3730        }
3731        return null;
3732    }
3733
3734    /**
3735     * Called by a profile or device owner to set a user restriction specified by the key.
3736     * <p>
3737     * The calling device admin must be a profile or device owner; if it is not,
3738     * a security exception will be thrown.
3739     *
3740     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3741     *            with.
3742     * @param key The key of the restriction. See the constants in
3743     *            {@link android.os.UserManager} for the list of keys.
3744     */
3745    public void addUserRestriction(ComponentName admin, String key) {
3746        if (mService != null) {
3747            try {
3748                mService.setUserRestriction(admin, key, true);
3749            } catch (RemoteException e) {
3750                Log.w(TAG, "Failed talking with device policy service", e);
3751            }
3752        }
3753    }
3754
3755    /**
3756     * Called by a profile or device owner to clear a user restriction specified by the key.
3757     * <p>
3758     * The calling device admin must be a profile or device owner; if it is not,
3759     * a security exception will be thrown.
3760     *
3761     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3762     *            with.
3763     * @param key The key of the restriction. See the constants in
3764     *            {@link android.os.UserManager} for the list of keys.
3765     */
3766    public void clearUserRestriction(ComponentName admin, String key) {
3767        if (mService != null) {
3768            try {
3769                mService.setUserRestriction(admin, key, false);
3770            } catch (RemoteException e) {
3771                Log.w(TAG, "Failed talking with device policy service", e);
3772            }
3773        }
3774    }
3775
3776    /**
3777     * Called by profile or device owners to hide or unhide packages. When a package is hidden it
3778     * is unavailable for use, but the data and actual package file remain.
3779     *
3780     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3781     * @param packageName The name of the package to hide or unhide.
3782     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
3783     *                 unhidden.
3784     * @return boolean Whether the hidden setting of the package was successfully updated.
3785     */
3786    public boolean setApplicationHidden(ComponentName admin, String packageName,
3787            boolean hidden) {
3788        if (mService != null) {
3789            try {
3790                return mService.setApplicationHidden(admin, packageName, hidden);
3791            } catch (RemoteException e) {
3792                Log.w(TAG, "Failed talking with device policy service", e);
3793            }
3794        }
3795        return false;
3796    }
3797
3798    /**
3799     * Called by profile or device owners to determine if a package is hidden.
3800     *
3801     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3802     * @param packageName The name of the package to retrieve the hidden status of.
3803     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
3804     */
3805    public boolean isApplicationHidden(ComponentName admin, String packageName) {
3806        if (mService != null) {
3807            try {
3808                return mService.isApplicationHidden(admin, packageName);
3809            } catch (RemoteException e) {
3810                Log.w(TAG, "Failed talking with device policy service", e);
3811            }
3812        }
3813        return false;
3814    }
3815
3816    /**
3817     * Called by profile or device owners to re-enable a system app that was disabled by default
3818     * when the user was initialized.
3819     *
3820     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3821     * @param packageName The package to be re-enabled in the current profile.
3822     */
3823    public void enableSystemApp(ComponentName admin, String packageName) {
3824        if (mService != null) {
3825            try {
3826                mService.enableSystemApp(admin, packageName);
3827            } catch (RemoteException e) {
3828                Log.w(TAG, "Failed to install package: " + packageName);
3829            }
3830        }
3831    }
3832
3833    /**
3834     * Called by profile or device owners to re-enable system apps by intent that were disabled
3835     * by default when the user was initialized.
3836     *
3837     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3838     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
3839     *               intent will be re-enabled in the current profile.
3840     * @return int The number of activities that matched the intent and were installed.
3841     */
3842    public int enableSystemApp(ComponentName admin, Intent intent) {
3843        if (mService != null) {
3844            try {
3845                return mService.enableSystemAppWithIntent(admin, intent);
3846            } catch (RemoteException e) {
3847                Log.w(TAG, "Failed to install packages matching filter: " + intent);
3848            }
3849        }
3850        return 0;
3851    }
3852
3853    /**
3854     * Called by a device owner or profile owner to disable account management for a specific type
3855     * of account.
3856     *
3857     * <p>The calling device admin must be a device owner or profile owner. If it is not, a
3858     * security exception will be thrown.
3859     *
3860     * <p>When account management is disabled for an account type, adding or removing an account
3861     * of that type will not be possible.
3862     *
3863     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3864     * @param accountType For which account management is disabled or enabled.
3865     * @param disabled The boolean indicating that account management will be disabled (true) or
3866     * enabled (false).
3867     */
3868    public void setAccountManagementDisabled(ComponentName admin, String accountType,
3869            boolean disabled) {
3870        if (mService != null) {
3871            try {
3872                mService.setAccountManagementDisabled(admin, accountType, disabled);
3873            } catch (RemoteException e) {
3874                Log.w(TAG, "Failed talking with device policy service", e);
3875            }
3876        }
3877    }
3878
3879    /**
3880     * Gets the array of accounts for which account management is disabled by the profile owner.
3881     *
3882     * <p> Account management can be disabled/enabled by calling
3883     * {@link #setAccountManagementDisabled}.
3884     *
3885     * @return a list of account types for which account management has been disabled.
3886     *
3887     * @see #setAccountManagementDisabled
3888     */
3889    public String[] getAccountTypesWithManagementDisabled() {
3890        return getAccountTypesWithManagementDisabledAsUser(UserHandle.myUserId());
3891    }
3892
3893    /**
3894     * @see #getAccountTypesWithManagementDisabled()
3895     * @hide
3896     */
3897    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
3898        if (mService != null) {
3899            try {
3900                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
3901            } catch (RemoteException e) {
3902                Log.w(TAG, "Failed talking with device policy service", e);
3903            }
3904        }
3905
3906        return null;
3907    }
3908
3909    /**
3910     * Sets which packages may enter lock task mode.
3911     *
3912     * <p>Any packages that shares uid with an allowed package will also be allowed
3913     * to activate lock task.
3914     *
3915     * This function can only be called by the device owner.
3916     * @param packages The list of packages allowed to enter lock task mode
3917     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3918     *
3919     * @see Activity#startLockTask()
3920     * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
3921     * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
3922     * @see UserManager#DISALLOW_CREATE_WINDOWS
3923     */
3924    public void setLockTaskPackages(ComponentName admin, String[] packages)
3925            throws SecurityException {
3926        if (mService != null) {
3927            try {
3928                mService.setLockTaskPackages(admin, packages);
3929            } catch (RemoteException e) {
3930                Log.w(TAG, "Failed talking with device policy service", e);
3931            }
3932        }
3933    }
3934
3935    /**
3936     * This function returns the list of packages allowed to start the lock task mode.
3937     *
3938     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3939     * @hide
3940     */
3941    public String[] getLockTaskPackages(ComponentName admin) {
3942        if (mService != null) {
3943            try {
3944                return mService.getLockTaskPackages(admin);
3945            } catch (RemoteException e) {
3946                Log.w(TAG, "Failed talking with device policy service", e);
3947            }
3948        }
3949        return null;
3950    }
3951
3952    /**
3953     * This function lets the caller know whether the given component is allowed to start the
3954     * lock task mode.
3955     * @param pkg The package to check
3956     */
3957    public boolean isLockTaskPermitted(String pkg) {
3958        if (mService != null) {
3959            try {
3960                return mService.isLockTaskPermitted(pkg);
3961            } catch (RemoteException e) {
3962                Log.w(TAG, "Failed talking with device policy service", e);
3963            }
3964        }
3965        return false;
3966    }
3967
3968    /**
3969     * Called by device owners to update {@link Settings.Global} settings. Validation that the value
3970     * of the setting is in the correct form for the setting type should be performed by the caller.
3971     * <p>The settings that can be updated with this method are:
3972     * <ul>
3973     * <li>{@link Settings.Global#ADB_ENABLED}</li>
3974     * <li>{@link Settings.Global#AUTO_TIME}</li>
3975     * <li>{@link Settings.Global#AUTO_TIME_ZONE}</li>
3976     * <li>{@link Settings.Global#BLUETOOTH_ON}
3977     * Changing this setting has not effect as of {@link android.os.Build.VERSION_CODES#MNC}. Use
3978     * {@link android.bluetooth.BluetoothAdapter#enable()} and
3979     * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
3980     * <li>{@link Settings.Global#DATA_ROAMING}</li>
3981     * <li>{@link Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
3982     * <li>{@link Settings.Global#MODE_RINGER}</li>
3983     * <li>{@link Settings.Global#NETWORK_PREFERENCE}</li>
3984     * <li>{@link Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
3985     * <li>{@link Settings.Global#WIFI_ON}
3986     * Changing this setting has not effect as of {@link android.os.Build.VERSION_CODES#MNC}. Use
3987     * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
3988     * <li>{@link Settings.Global#WIFI_SLEEP_POLICY}</li>
3989     * <li>{@link Settings.Global#STAY_ON_WHILE_PLUGGED_IN}
3990     * This setting is only available from {@link android.os.Build.VERSION_CODES#MNC} onwards
3991     * and can only be set if {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
3992     * </ul>
3993     *
3994     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3995     * @param setting The name of the setting to update.
3996     * @param value The value to update the setting to.
3997     */
3998    public void setGlobalSetting(ComponentName admin, String setting, String value) {
3999        if (mService != null) {
4000            try {
4001                mService.setGlobalSetting(admin, setting, value);
4002            } catch (RemoteException e) {
4003                Log.w(TAG, "Failed talking with device policy service", e);
4004            }
4005        }
4006    }
4007
4008    /**
4009     * Called by profile or device owners to update {@link Settings.Secure} settings. Validation
4010     * that the value of the setting is in the correct form for the setting type should be performed
4011     * by the caller.
4012     * <p>The settings that can be updated by a profile or device owner with this method are:
4013     * <ul>
4014     * <li>{@link Settings.Secure#DEFAULT_INPUT_METHOD}</li>
4015     * <li>{@link Settings.Secure#INSTALL_NON_MARKET_APPS}</li>
4016     * <li>{@link Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
4017     * </ul>
4018     * <p>A device owner can additionally update the following settings:
4019     * <ul>
4020     * <li>{@link Settings.Secure#LOCATION_MODE}</li>
4021     * </ul>
4022     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4023     * @param setting The name of the setting to update.
4024     * @param value The value to update the setting to.
4025     */
4026    public void setSecureSetting(ComponentName admin, String setting, String value) {
4027        if (mService != null) {
4028            try {
4029                mService.setSecureSetting(admin, setting, value);
4030            } catch (RemoteException e) {
4031                Log.w(TAG, "Failed talking with device policy service", e);
4032            }
4033        }
4034    }
4035
4036    /**
4037     * Designates a specific service component as the provider for
4038     * making permission requests of a local or remote administrator of the user.
4039     * <p/>
4040     * Only a profile owner can designate the restrictions provider.
4041     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4042     * @param provider The component name of the service that implements
4043     * {@link RestrictionsReceiver}. If this param is null,
4044     * it removes the restrictions provider previously assigned.
4045     */
4046    public void setRestrictionsProvider(ComponentName admin, ComponentName provider) {
4047        if (mService != null) {
4048            try {
4049                mService.setRestrictionsProvider(admin, provider);
4050            } catch (RemoteException re) {
4051                Log.w(TAG, "Failed to set permission provider on device policy service");
4052            }
4053        }
4054    }
4055
4056    /**
4057     * Called by profile or device owners to set the master volume mute on or off.
4058     *
4059     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4060     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
4061     */
4062    public void setMasterVolumeMuted(ComponentName admin, boolean on) {
4063        if (mService != null) {
4064            try {
4065                mService.setMasterVolumeMuted(admin, on);
4066            } catch (RemoteException re) {
4067                Log.w(TAG, "Failed to setMasterMute on device policy service");
4068            }
4069        }
4070    }
4071
4072    /**
4073     * Called by profile or device owners to check whether the master volume mute is on or off.
4074     *
4075     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4076     * @return {@code true} if master volume is muted, {@code false} if it's not.
4077     */
4078    public boolean isMasterVolumeMuted(ComponentName admin) {
4079        if (mService != null) {
4080            try {
4081                return mService.isMasterVolumeMuted(admin);
4082            } catch (RemoteException re) {
4083                Log.w(TAG, "Failed to get isMasterMute on device policy service");
4084            }
4085        }
4086        return false;
4087    }
4088
4089    /**
4090     * Called by profile or device owners to change whether a user can uninstall
4091     * a package.
4092     *
4093     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4094     * @param packageName package to change.
4095     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
4096     */
4097    public void setUninstallBlocked(ComponentName admin, String packageName,
4098            boolean uninstallBlocked) {
4099        if (mService != null) {
4100            try {
4101                mService.setUninstallBlocked(admin, packageName, uninstallBlocked);
4102            } catch (RemoteException re) {
4103                Log.w(TAG, "Failed to call block uninstall on device policy service");
4104            }
4105        }
4106    }
4107
4108    /**
4109     * Check whether the current user has been blocked by device policy from uninstalling a package.
4110     * Requires the caller to be the profile owner if checking a specific admin's policy.
4111     * <p>
4112     * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
4113     * behavior of this API is changed such that passing <code>null</code> as the <code>admin</code>
4114     * parameter will return if any admin has blocked the uninstallation. Before L MR1, passing
4115     * <code>null</code> will cause a NullPointerException to be raised.
4116     *
4117     * @param admin The name of the admin component whose blocking policy will be checked, or null
4118     *            to check if any admin has blocked the uninstallation.
4119     * @param packageName package to check.
4120     * @return true if uninstallation is blocked.
4121     */
4122    public boolean isUninstallBlocked(ComponentName admin, String packageName) {
4123        if (mService != null) {
4124            try {
4125                return mService.isUninstallBlocked(admin, packageName);
4126            } catch (RemoteException re) {
4127                Log.w(TAG, "Failed to call block uninstall on device policy service");
4128            }
4129        }
4130        return false;
4131    }
4132
4133    /**
4134     * Called by the profile owner of a managed profile to enable widget providers from a
4135     * given package to be available in the parent profile. As a result the user will be able to
4136     * add widgets from the white-listed package running under the profile to a widget
4137     * host which runs under the parent profile, for example the home screen. Note that
4138     * a package may have zero or more provider components, where each component
4139     * provides a different widget type.
4140     * <p>
4141     * <strong>Note:</strong> By default no widget provider package is white-listed.
4142     * </p>
4143     *
4144     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4145     * @param packageName The package from which widget providers are white-listed.
4146     * @return Whether the package was added.
4147     *
4148     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
4149     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
4150     */
4151    public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4152        if (mService != null) {
4153            try {
4154                return mService.addCrossProfileWidgetProvider(admin, packageName);
4155            } catch (RemoteException re) {
4156                Log.w(TAG, "Error calling addCrossProfileWidgetProvider", re);
4157            }
4158        }
4159        return false;
4160    }
4161
4162    /**
4163     * Called by the profile owner of a managed profile to disable widget providers from a given
4164     * package to be available in the parent profile. For this method to take effect the
4165     * package should have been added via {@link #addCrossProfileWidgetProvider(
4166     * android.content.ComponentName, String)}.
4167     * <p>
4168     * <strong>Note:</strong> By default no widget provider package is white-listed.
4169     * </p>
4170     *
4171     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4172     * @param packageName The package from which widget providers are no longer
4173     *     white-listed.
4174     * @return Whether the package was removed.
4175     *
4176     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
4177     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
4178     */
4179    public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4180        if (mService != null) {
4181            try {
4182                return mService.removeCrossProfileWidgetProvider(admin, packageName);
4183            } catch (RemoteException re) {
4184                Log.w(TAG, "Error calling removeCrossProfileWidgetProvider", re);
4185            }
4186        }
4187        return false;
4188    }
4189
4190    /**
4191     * Called by the profile owner of a managed profile to query providers from which packages are
4192     * available in the parent profile.
4193     *
4194     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4195     * @return The white-listed package list.
4196     *
4197     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
4198     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
4199     */
4200    public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
4201        if (mService != null) {
4202            try {
4203                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
4204                if (providers != null) {
4205                    return providers;
4206                }
4207            } catch (RemoteException re) {
4208                Log.w(TAG, "Error calling getCrossProfileWidgetProviders", re);
4209            }
4210        }
4211        return Collections.emptyList();
4212    }
4213
4214    /**
4215     * Called by profile or device owners to set the current user's photo.
4216     *
4217     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4218     * @param icon the bitmap to set as the photo.
4219     */
4220    public void setUserIcon(ComponentName admin, Bitmap icon) {
4221        try {
4222            mService.setUserIcon(admin, icon);
4223        } catch (RemoteException re) {
4224            Log.w(TAG, "Could not set the user icon ", re);
4225        }
4226    }
4227
4228    /**
4229     * Called by device initializer to send a provisioning status update to the remote setup device.
4230     *
4231     * @param statusCode a custom status code value as defined by
4232     *    {@link DeviceInitializerStatus#FLAG_STATUS_CUSTOM}.
4233     * @param description custom description of the status code sent
4234     */
4235    public void sendDeviceInitializerStatus(int statusCode, String description) {
4236        try {
4237            mService.sendDeviceInitializerStatus(statusCode, description);
4238        } catch (RemoteException re) {
4239            Log.w(TAG, "Could not send device initializer status", re);
4240        }
4241    }
4242
4243    /**
4244     * Called by device owners to set a local system update policy. When a new policy is set,
4245     * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
4246     *
4247     * @param who Which {@link DeviceAdminReceiver} this request is associated with. All components
4248     * in the device owner package can set system update policies and the most recent policy takes
4249     * effect.
4250     * @param policy the new policy, or null to clear the current policy.
4251     * @see SystemUpdatePolicy
4252     */
4253    public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
4254        if (mService != null) {
4255            try {
4256                mService.setSystemUpdatePolicy(who, policy);
4257            } catch (RemoteException re) {
4258                Log.w(TAG, "Error calling setSystemUpdatePolicy", re);
4259            }
4260        }
4261    }
4262
4263    /**
4264     * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
4265     *
4266     * @return The current policy object, or null if no policy is set.
4267     */
4268    public SystemUpdatePolicy getSystemUpdatePolicy() {
4269        if (mService != null) {
4270            try {
4271                return mService.getSystemUpdatePolicy();
4272            } catch (RemoteException re) {
4273                Log.w(TAG, "Error calling getSystemUpdatePolicy", re);
4274            }
4275        }
4276        return null;
4277    }
4278
4279    /**
4280     * Called by a device owner to disable the keyguard altogether.
4281     *
4282     * <p>Setting the keyguard to disabled has the same effect as choosing "None" as the screen
4283     * lock type. However, this call has no effect if a password, pin or pattern is currently set.
4284     * If a password, pin or pattern is set after the keyguard was disabled, the keyguard stops
4285     * being disabled.
4286     *
4287     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4288     * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
4289     *
4290     * @return {@code false} if attempting to disable the keyguard while a lock password was in
4291     * place. {@code true} otherwise.
4292     */
4293    public boolean setKeyguardDisabled(ComponentName admin, boolean disabled) {
4294        try {
4295            return mService.setKeyguardDisabled(admin, disabled);
4296        } catch (RemoteException re) {
4297            Log.w(TAG, "Failed talking with device policy service", re);
4298            return false;
4299        }
4300    }
4301
4302    /**
4303     * Called by device owner to disable the status bar. Disabling the status bar blocks
4304     * notifications, quick settings and other screen overlays that allow escaping from
4305     * a single use device.
4306     *
4307     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4308     * @param disabled {@code true} disables the status bar, {@code false} reenables it.
4309     *
4310     * @return {@code false} if attempting to disable the status bar failed.
4311     * {@code true} otherwise.
4312     */
4313    public boolean setStatusBarDisabled(ComponentName admin, boolean disabled) {
4314        try {
4315            return mService.setStatusBarDisabled(admin, disabled);
4316        } catch (RemoteException re) {
4317            Log.w(TAG, "Failed talking with device policy service", re);
4318            return false;
4319        }
4320    }
4321
4322    /**
4323     * Callable by the system update service to notify device owners about pending updates.
4324     * The caller must hold {@link android.Manifest.permission#NOTIFY_PENDING_SYSTEM_UPDATE}
4325     * permission.
4326     *
4327     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()} indicating
4328     *        when the current pending update was first available. -1 if no update is available.
4329     * @hide
4330     */
4331    @SystemApi
4332    public void notifyPendingSystemUpdate(long updateReceivedTime) {
4333        if (mService != null) {
4334            try {
4335                mService.notifyPendingSystemUpdate(updateReceivedTime);
4336            } catch (RemoteException re) {
4337                Log.w(TAG, "Could not notify device owner about pending system update", re);
4338            }
4339        }
4340    }
4341
4342    /**
4343     * Called by a device initializer to set the activity to be launched on device boot or after a
4344     * user switch during user setup. This activity will be started regardless of the priority of
4345     * other 'home' activities. Once user setup is complete, the preferred setup activity will be
4346     * ignored.
4347     *
4348     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4349     * @param activity The Activity to be started by default during user setup.
4350     */
4351    public void setPreferredSetupActivity(ComponentName admin, ComponentName activity) {
4352        try {
4353            mService.setPreferredSetupActivity(admin, activity);
4354        } catch (RemoteException re) {
4355            Log.w(TAG, "Failed talking with device policy service", re);
4356        }
4357    }
4358
4359    /**
4360     * Called by profile or device owners to set the default response for future runtime permission
4361     * requests by applications. The policy can allow for normal operation which prompts the
4362     * user to grant a permission, or can allow automatic granting or denying of runtime
4363     * permission requests by an application. This also applies to new permissions declared by app
4364     * updates.
4365     * @param admin Which profile or device owner this request is associated with.
4366     * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
4367     * {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
4368     */
4369    public void setPermissionPolicy(ComponentName admin, int policy) {
4370        try {
4371            mService.setPermissionPolicy(admin, policy);
4372        } catch (RemoteException re) {
4373            Log.w(TAG, "Failed talking with device policy service", re);
4374        }
4375    }
4376
4377    /**
4378     * Returns the current runtime permission policy set by the device or profile owner. The
4379     * default is {@link #PERMISSION_POLICY_PROMPT}.
4380     * @param admin Which profile or device owner this request is associated with.
4381     * @return the current policy for future permission requests.
4382     */
4383    public int getPermissionPolicy(ComponentName admin) {
4384        try {
4385            return mService.getPermissionPolicy(admin);
4386        } catch (RemoteException re) {
4387            return PERMISSION_POLICY_PROMPT;
4388        }
4389    }
4390
4391    /**
4392     * Grants or revokes a runtime permission to a specific application so that the user
4393     * does not have to be prompted. This might affect all permissions in a group that the
4394     * runtime permission belongs to. This method can only be called by a profile or device
4395     * owner.
4396     * @param admin Which profile or device owner this request is associated with.
4397     * @param packageName The application to grant or revoke a permission to.
4398     * @param permission The permission to grant or revoke.
4399     * @param granted Whether or not to grant the permission. If false, all permissions in the
4400     * associated permission group will be denied.
4401     * @return whether the permission was successfully granted or revoked
4402     */
4403    public boolean setPermissionGranted(ComponentName admin, String packageName,
4404            String permission, boolean granted) {
4405        try {
4406            return mService.setPermissionGranted(admin, packageName, permission, granted);
4407        } catch (RemoteException re) {
4408            Log.w(TAG, "Failed talking with device policy service", re);
4409            return false;
4410        }
4411    }
4412}
4413