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