DevicePolicyManager.java revision a55fc9920117eabae7c0bb7339d8d9f5d3f5a9c1
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.app.Activity;
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
26import android.content.pm.ActivityInfo;
27import android.content.pm.PackageManager;
28import android.content.pm.ResolveInfo;
29import android.content.RestrictionsManager;
30import android.media.AudioService;
31import android.net.ProxyInfo;
32import android.os.Bundle;
33import android.os.Handler;
34import android.os.Process;
35import android.os.RemoteCallback;
36import android.os.RemoteException;
37import android.os.ServiceManager;
38import android.os.UserHandle;
39import android.os.UserManager;
40import android.provider.Settings;
41import android.service.trust.TrustAgentService;
42import android.util.Log;
43
44import com.android.org.conscrypt.TrustedCertificateStore;
45
46import org.xmlpull.v1.XmlPullParserException;
47
48import java.io.ByteArrayInputStream;
49import java.io.IOException;
50import java.net.InetSocketAddress;
51import java.net.Proxy;
52import java.security.cert.CertificateException;
53import java.security.cert.CertificateFactory;
54import java.security.cert.X509Certificate;
55import java.util.List;
56import java.util.Set;
57
58/**
59 * Public interface for managing policies enforced on a device.  Most clients
60 * of this class must have published a {@link DeviceAdminReceiver} that the user
61 * has currently enabled.
62 *
63 * <div class="special reference">
64 * <h3>Developer Guides</h3>
65 * <p>For more information about managing policies for device adminstration, read the
66 * <a href="{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a>
67 * developer guide.</p>
68 * </div>
69 */
70public class DevicePolicyManager {
71    private static String TAG = "DevicePolicyManager";
72
73    private final Context mContext;
74    private final IDevicePolicyManager mService;
75
76    private DevicePolicyManager(Context context, Handler handler) {
77        mContext = context;
78        mService = IDevicePolicyManager.Stub.asInterface(
79                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
80    }
81
82    /** @hide */
83    public static DevicePolicyManager create(Context context, Handler handler) {
84        DevicePolicyManager me = new DevicePolicyManager(context, handler);
85        return me.mService != null ? me : null;
86    }
87
88    /**
89     * Activity action: Used to indicate that the receiving activity is being started as part of the
90     * managed profile provisioning flow. This intent is typically sent to a mobile device
91     * management application (mdm) after the first part of the provisioning process is complete in
92     * the expectation that this app will (after optionally showing it's own UI) ultimately call
93     * {@link #ACTION_PROVISION_MANAGED_PROFILE} to complete the creation of the managed profile.
94     *
95     * <p> The intent may contain the extras {@link #EXTRA_PROVISIONING_TOKEN} and
96     * {@link #EXTRA_PROVISIONING_EMAIL_ADDRESS}.
97     */
98    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
99    public static final String ACTION_SEND_PROVISIONING_VALUES
100        = "android.app.action.ACTION_SEND_PROVISIONING_VALUES";
101
102    /**
103     * Activity action: Starts the provisioning flow which sets up a managed profile.
104     *
105     * <p>A managed profile allows data separation for example for the usage of a
106     * device as a personal and corporate device. The user which provisioning is started from and
107     * the managed profile share a launcher.
108     *
109     * <p>This intent will typically be sent by a mobile device management application (mdm).
110     * Provisioning adds a managed profile and sets the mdm as the profile owner who has full
111     * control over the profile
112     *
113     * <p>This intent must contain the extras {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}
114     * {@link #EXTRA_PROVISIONING_DEFAULT_MANAGED_PROFILE_NAME} and {@link #EXTRA_DEVICE_ADMIN}.
115     *
116     * <p> When managed provisioning has completed, an intent of the type
117     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcasted to the
118     * managed profile.
119     *
120     * <p> If provisioning fails, the managedProfile is removed so the device returns to its
121     * previous state.
122     *
123     * <p>Input: Nothing.</p>
124     * <p>Output: Nothing</p>
125     */
126    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
127    public static final String ACTION_PROVISION_MANAGED_PROFILE
128        = "android.app.action.ACTION_PROVISION_MANAGED_PROFILE";
129
130    /**
131     * A broadcast intent with this action can be sent to ManagedProvisionning to specify that the
132     * user has already consented to the creation of the managed profile.
133     * The intent must contain the extras
134     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} and
135     * {@link #EXTRA_PROVISIONING_TOKEN}
136     * @hide
137     */
138    public static final String ACTION_PROVISIONING_USER_HAS_CONSENTED
139        = "android.app.action.ACTION_PROVISIONING_USER_HAS_CONSENTED";
140
141    /**
142     * A String extra holding the package name of the mobile device management application that
143     * will be set as the profile owner or device owner.
144     *
145     * <p>If an application starts provisioning directly via an intent with action
146     * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
147     * application that started provisioning. The package will be set as profile owner in that case.
148     *
149     * <p>This package is set as device owner when device owner provisioning is started by an Nfc
150     * message containing an Nfc record with MIME type {@link #PROVISIONING_NFC_MIME_TYPE}.
151     */
152    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
153        = "android.app.extra.deviceAdminPackageName";
154
155    /**
156     * An int extra used to identify that during the current setup process the user has already
157     * consented to setting up a managed profile. This is typically received by
158     * a mobile device management application when it is started with
159     * {@link #ACTION_SEND_PROVISIONING_VALUES} and passed on in an intent
160     * {@link #ACTION_PROVISION_MANAGED_PROFILE} which starts the setup of the managed profile. The
161     * token indicates that steps asking for user consent can be skipped as the user has previously
162     * consented.
163     */
164    public static final String EXTRA_PROVISIONING_TOKEN
165        = "android.app.extra.token";
166
167    /**
168     * A String extra holding the default name of the profile that is created during managed profile
169     * provisioning.
170     *
171     * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}
172     */
173    public static final String EXTRA_PROVISIONING_DEFAULT_MANAGED_PROFILE_NAME
174        = "android.app.extra.defaultManagedProfileName";
175
176    /**
177     * A String extra holding the email address of the profile that is created during managed
178     * profile provisioning. This is typically received by a mobile management application when it
179     * is started with {@link #ACTION_SEND_PROVISIONING_VALUES} and passed on in an intent
180     * {@link #ACTION_PROVISION_MANAGED_PROFILE} which starts the setup of the managed profile. It
181     * is eventually passed on in an intent
182     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}.
183     */
184    public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
185        = "android.app.extra.ManagedProfileEmailAddress";
186
187    /**
188     * A String extra holding the time zone {@link android.app.AlarmManager} that the device
189     * will be set to.
190     *
191     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
192     * provisioning via an Nfc bump.
193     */
194    public static final String EXTRA_PROVISIONING_TIME_ZONE
195        = "android.app.extra.timeZone";
196
197    /**
198     * A Long extra holding the local time {@link android.app.AlarmManager} that the device
199     * will be set to.
200     *
201     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
202     * provisioning via an Nfc bump.
203     */
204    public static final String EXTRA_PROVISIONING_LOCAL_TIME
205        = "android.app.extra.localTime";
206
207    /**
208     * A String extra holding the {@link java.util.Locale} that the device will be set to.
209     * Format: xx_yy, where xx is the language code, and yy the country code.
210     *
211     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
212     * provisioning via an Nfc bump.
213     */
214    public static final String EXTRA_PROVISIONING_LOCALE
215        = "android.app.extra.locale";
216
217    /**
218     * A String extra holding the ssid of the wifi network that should be used during nfc device
219     * owner provisioning for downloading the mobile device management application.
220     *
221     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
222     * provisioning via an Nfc bump.
223     */
224    public static final String EXTRA_PROVISIONING_WIFI_SSID
225        = "android.app.extra.wifiSsid";
226
227    /**
228     * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
229     * is hidden or not.
230     *
231     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
232     * provisioning via an Nfc bump.
233     */
234    public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
235        = "android.app.extra.wifiHidden";
236
237    /**
238     * A String extra indicating the security type of the wifi network in
239     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
240     *
241     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
242     * provisioning via an Nfc bump.
243     */
244    public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
245        = "android.app.extra.wifiSecurityType";
246
247    /**
248     * A String extra holding the password of the wifi network in
249     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
250     *
251     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
252     * provisioning via an Nfc bump.
253     */
254    public static final String EXTRA_PROVISIONING_WIFI_PASSWORD
255        = "android.app.extra.wifiPassword";
256
257    /**
258     * A String extra holding the proxy host for the wifi network in
259     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
260     *
261     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
262     * provisioning via an Nfc bump.
263     */
264    public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
265        = "android.app.extra.wifiProxyHost";
266
267    /**
268     * An int extra holding the proxy port for the wifi network in
269     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
270     *
271     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
272     * provisioning via an Nfc bump.
273     */
274    public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
275        = "android.app.extra.wifiProxyPort";
276
277    /**
278     * A String extra holding the proxy bypass for the wifi network in
279     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
280     *
281     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
282     * provisioning via an Nfc bump.
283     */
284    public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
285        = "android.app.extra.wifiProxyBypassHosts";
286
287    /**
288     * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
289     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
290     *
291     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
292     * provisioning via an Nfc bump.
293     */
294    public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
295        = "android.app.extra.wifiPacUrl";
296
297    /**
298     * A String extra holding a url that specifies the download location of the device admin
299     * package. When not provided it is assumed that the device admin package is already installed.
300     *
301     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
302     * provisioning via an Nfc bump.
303     */
304    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
305        = "android.app.extra.deviceAdminPackageDownloadLocation";
306
307    /**
308     * A String extra holding the SHA-1 checksum of the file at download location specified in
309     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}. If this doesn't match
310     * the file at the download location an error will be shown to the user and the user will be
311     * asked to factory reset the device.
312     *
313     * <p>Use in an Nfc record with {@link #PROVISIONING_NFC_MIME_TYPE} that starts device owner
314     * provisioning via an Nfc bump.
315     */
316    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
317        = "android.app.extra.deviceAdminPackageChecksum";
318
319    /**
320     * This MIME type is used for starting the Device Owner provisioning.
321     *
322     * <p>During device owner provisioning a device admin app is set as the owner of the device.
323     * A device owner has full control over the device. The device owner can not be modified by the
324     * user and the only way of resetting the device is if the device owner app calls a factory
325     * reset.
326     *
327     * <p> A typical use case would be a device that is owned by a company, but used by either an
328     * employee or client.
329     *
330     * <p> The Nfc message should be send to an unprovisioned device.
331     *
332     * <p>The Nfc record must contain a serialized {@link java.util.Properties} object which
333     * contains the following properties:
334     * <ul>
335     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
336     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}</li>
337     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}</li>
338     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
339     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
340     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
341     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
342     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
343     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
344     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
345     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
346     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
347     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
348     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li></ul>
349     *
350     * <p> When device owner provisioning has completed, an intent of the type
351     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcasted to the
352     * device owner.
353     *
354     * <p>
355     * If provisioning fails, the device is factory reset.
356     *
357     * <p>Input: Nothing.</p>
358     * <p>Output: Nothing</p>
359     */
360    public static final String PROVISIONING_NFC_MIME_TYPE
361        = "application/com.android.managedprovisioning";
362
363    /**
364     * Activity action: ask the user to add a new device administrator to the system.
365     * The desired policy is the ComponentName of the policy in the
366     * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
367     * bring the user through adding the device administrator to the system (or
368     * allowing them to reject it).
369     *
370     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
371     * field to provide the user with additional explanation (in addition
372     * to your component's description) about what is being added.
373     *
374     * <p>If your administrator is already active, this will ordinarily return immediately (without
375     * user intervention).  However, if your administrator has been updated and is requesting
376     * additional uses-policy flags, the user will be presented with the new list.  New policies
377     * will not be available to the updated administrator until the user has accepted the new list.
378     */
379    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
380    public static final String ACTION_ADD_DEVICE_ADMIN
381            = "android.app.action.ADD_DEVICE_ADMIN";
382
383    /**
384     * Activity action: send when any policy admin changes a policy.
385     * This is generally used to find out when a new policy is in effect.
386     *
387     * @hide
388     */
389    public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
390            = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
391
392    /**
393     * The ComponentName of the administrator component.
394     *
395     * @see #ACTION_ADD_DEVICE_ADMIN
396     */
397    public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
398
399    /**
400     * An optional CharSequence providing additional explanation for why the
401     * admin is being added.
402     *
403     * @see #ACTION_ADD_DEVICE_ADMIN
404     */
405    public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
406
407    /**
408     * Activity action: have the user enter a new password. This activity should
409     * be launched after using {@link #setPasswordQuality(ComponentName, int)},
410     * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
411     * enter a new password that meets the current requirements. You can use
412     * {@link #isActivePasswordSufficient()} to determine whether you need to
413     * have the user select a new password in order to meet the current
414     * constraints. Upon being resumed from this activity, you can check the new
415     * password characteristics to see if they are sufficient.
416     */
417    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
418    public static final String ACTION_SET_NEW_PASSWORD
419            = "android.app.action.SET_NEW_PASSWORD";
420    /**
421     * Flag used by {@link #addCrossProfileIntentFilter} to allow access of certain intents from a
422     * managed profile to its parent.
423     */
424    public static int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
425
426    /**
427     * Flag used by {@link #addCrossProfileIntentFilter} to allow access of certain intents from the
428     * parent to its managed profile.
429     */
430    public static int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
431
432    /**
433     * Return true if the given administrator component is currently
434     * active (enabled) in the system.
435     */
436    public boolean isAdminActive(ComponentName who) {
437        if (mService != null) {
438            try {
439                return mService.isAdminActive(who, UserHandle.myUserId());
440            } catch (RemoteException e) {
441                Log.w(TAG, "Failed talking with device policy service", e);
442            }
443        }
444        return false;
445    }
446
447    /**
448     * Return a list of all currently active device administrator's component
449     * names.  Note that if there are no administrators than null may be
450     * returned.
451     */
452    public List<ComponentName> getActiveAdmins() {
453        if (mService != null) {
454            try {
455                return mService.getActiveAdmins(UserHandle.myUserId());
456            } catch (RemoteException e) {
457                Log.w(TAG, "Failed talking with device policy service", e);
458            }
459        }
460        return null;
461    }
462
463    /**
464     * Used by package administration code to determine if a package can be stopped
465     * or uninstalled.
466     * @hide
467     */
468    public boolean packageHasActiveAdmins(String packageName) {
469        if (mService != null) {
470            try {
471                return mService.packageHasActiveAdmins(packageName, UserHandle.myUserId());
472            } catch (RemoteException e) {
473                Log.w(TAG, "Failed talking with device policy service", e);
474            }
475        }
476        return false;
477    }
478
479    /**
480     * Remove a current administration component.  This can only be called
481     * by the application that owns the administration component; if you
482     * try to remove someone else's component, a security exception will be
483     * thrown.
484     */
485    public void removeActiveAdmin(ComponentName who) {
486        if (mService != null) {
487            try {
488                mService.removeActiveAdmin(who, UserHandle.myUserId());
489            } catch (RemoteException e) {
490                Log.w(TAG, "Failed talking with device policy service", e);
491            }
492        }
493    }
494
495    /**
496     * Returns true if an administrator has been granted a particular device policy.  This can
497     * be used to check if the administrator was activated under an earlier set of policies,
498     * but requires additional policies after an upgrade.
499     *
500     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  Must be
501     * an active administrator, or an exception will be thrown.
502     * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
503     */
504    public boolean hasGrantedPolicy(ComponentName admin, int usesPolicy) {
505        if (mService != null) {
506            try {
507                return mService.hasGrantedPolicy(admin, usesPolicy, UserHandle.myUserId());
508            } catch (RemoteException e) {
509                Log.w(TAG, "Failed talking with device policy service", e);
510            }
511        }
512        return false;
513    }
514
515    /**
516     * Constant for {@link #setPasswordQuality}: the policy has no requirements
517     * for the password.  Note that quality constants are ordered so that higher
518     * values are more restrictive.
519     */
520    public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
521
522    /**
523     * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
524     * recognition technology.  This implies technologies that can recognize the identity of
525     * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
526     * Note that quality constants are ordered so that higher values are more restrictive.
527     */
528    public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
529
530    /**
531     * Constant for {@link #setPasswordQuality}: the policy requires some kind
532     * of password, but doesn't care what it is.  Note that quality constants
533     * are ordered so that higher values are more restrictive.
534     */
535    public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
536
537    /**
538     * Constant for {@link #setPasswordQuality}: the user must have entered a
539     * password containing at least numeric characters.  Note that quality
540     * constants are ordered so that higher values are more restrictive.
541     */
542    public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
543
544    /**
545     * Constant for {@link #setPasswordQuality}: the user must have entered a
546     * password containing at least alphabetic (or other symbol) characters.
547     * Note that quality constants are ordered so that higher values are more
548     * restrictive.
549     */
550    public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
551
552    /**
553     * Constant for {@link #setPasswordQuality}: the user must have entered a
554     * password containing at least <em>both></em> numeric <em>and</em>
555     * alphabetic (or other symbol) characters.  Note that quality constants are
556     * ordered so that higher values are more restrictive.
557     */
558    public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
559
560    /**
561     * Constant for {@link #setPasswordQuality}: the user must have entered a
562     * password containing at least a letter, a numerical digit and a special
563     * symbol, by default. With this password quality, passwords can be
564     * restricted to contain various sets of characters, like at least an
565     * uppercase letter, etc. These are specified using various methods,
566     * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
567     * that quality constants are ordered so that higher values are more
568     * restrictive.
569     */
570    public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
571
572    /**
573     * Called by an application that is administering the device to set the
574     * password restrictions it is imposing.  After setting this, the user
575     * will not be able to enter a new password that is not at least as
576     * restrictive as what has been set.  Note that the current password
577     * will remain until the user has set a new one, so the change does not
578     * take place immediately.  To prompt the user for a new password, use
579     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value.
580     *
581     * <p>Quality constants are ordered so that higher values are more restrictive;
582     * thus the highest requested quality constant (between the policy set here,
583     * the user's preference, and any other considerations) is the one that
584     * is in effect.
585     *
586     * <p>The calling device admin must have requested
587     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
588     * this method; if it has not, a security exception will be thrown.
589     *
590     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
591     * @param quality The new desired quality.  One of
592     * {@link #PASSWORD_QUALITY_UNSPECIFIED}, {@link #PASSWORD_QUALITY_SOMETHING},
593     * {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_ALPHABETIC},
594     * {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
595     */
596    public void setPasswordQuality(ComponentName admin, int quality) {
597        if (mService != null) {
598            try {
599                mService.setPasswordQuality(admin, quality, UserHandle.myUserId());
600            } catch (RemoteException e) {
601                Log.w(TAG, "Failed talking with device policy service", e);
602            }
603        }
604    }
605
606    /**
607     * Retrieve the current minimum password quality for all admins of this user
608     * and its profiles or a particular one.
609     * @param admin The name of the admin component to check, or null to aggregate
610     * all admins.
611     */
612    public int getPasswordQuality(ComponentName admin) {
613        return getPasswordQuality(admin, UserHandle.myUserId());
614    }
615
616    /** @hide per-user version */
617    public int getPasswordQuality(ComponentName admin, int userHandle) {
618        if (mService != null) {
619            try {
620                return mService.getPasswordQuality(admin, userHandle);
621            } catch (RemoteException e) {
622                Log.w(TAG, "Failed talking with device policy service", e);
623            }
624        }
625        return PASSWORD_QUALITY_UNSPECIFIED;
626    }
627
628    /**
629     * Called by an application that is administering the device to set the
630     * minimum allowed password length.  After setting this, the user
631     * will not be able to enter a new password that is not at least as
632     * restrictive as what has been set.  Note that the current password
633     * will remain until the user has set a new one, so the change does not
634     * take place immediately.  To prompt the user for a new password, use
635     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value.  This
636     * constraint is only imposed if the administrator has also requested either
637     * {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_ALPHABETIC}
638     * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX}
639     * with {@link #setPasswordQuality}.
640     *
641     * <p>The calling device admin must have requested
642     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
643     * this method; if it has not, a security exception will be thrown.
644     *
645     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
646     * @param length The new desired minimum password length.  A value of 0
647     * means there is no restriction.
648     */
649    public void setPasswordMinimumLength(ComponentName admin, int length) {
650        if (mService != null) {
651            try {
652                mService.setPasswordMinimumLength(admin, length, UserHandle.myUserId());
653            } catch (RemoteException e) {
654                Log.w(TAG, "Failed talking with device policy service", e);
655            }
656        }
657    }
658
659    /**
660     * Retrieve the current minimum password length for all admins of this
661     * user and its profiles or a particular one.
662     * @param admin The name of the admin component to check, or null to aggregate
663     * all admins.
664     */
665    public int getPasswordMinimumLength(ComponentName admin) {
666        return getPasswordMinimumLength(admin, UserHandle.myUserId());
667    }
668
669    /** @hide per-user version */
670    public int getPasswordMinimumLength(ComponentName admin, int userHandle) {
671        if (mService != null) {
672            try {
673                return mService.getPasswordMinimumLength(admin, userHandle);
674            } catch (RemoteException e) {
675                Log.w(TAG, "Failed talking with device policy service", e);
676            }
677        }
678        return 0;
679    }
680
681    /**
682     * Called by an application that is administering the device to set the
683     * minimum number of upper case letters required in the password. After
684     * setting this, the user will not be able to enter a new password that is
685     * not at least as restrictive as what has been set. Note that the current
686     * password will remain until the user has set a new one, so the change does
687     * not take place immediately. To prompt the user for a new password, use
688     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
689     * constraint is only imposed if the administrator has also requested
690     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
691     * default value is 0.
692     * <p>
693     * The calling device admin must have requested
694     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
695     * this method; if it has not, a security exception will be thrown.
696     *
697     * @param admin Which {@link DeviceAdminReceiver} this request is associated
698     *            with.
699     * @param length The new desired minimum number of upper case letters
700     *            required in the password. A value of 0 means there is no
701     *            restriction.
702     */
703    public void setPasswordMinimumUpperCase(ComponentName admin, int length) {
704        if (mService != null) {
705            try {
706                mService.setPasswordMinimumUpperCase(admin, length, UserHandle.myUserId());
707            } catch (RemoteException e) {
708                Log.w(TAG, "Failed talking with device policy service", e);
709            }
710        }
711    }
712
713    /**
714     * Retrieve the current number of upper case letters required in the
715     * password for all admins of this user and its profiles or a particular one.
716     * This is the same value as set by
717     * {#link {@link #setPasswordMinimumUpperCase(ComponentName, int)}
718     * and only applies when the password quality is
719     * {@link #PASSWORD_QUALITY_COMPLEX}.
720     *
721     * @param admin The name of the admin component to check, or null to
722     *            aggregate all admins.
723     * @return The minimum number of upper case letters required in the
724     *         password.
725     */
726    public int getPasswordMinimumUpperCase(ComponentName admin) {
727        return getPasswordMinimumUpperCase(admin, UserHandle.myUserId());
728    }
729
730    /** @hide per-user version */
731    public int getPasswordMinimumUpperCase(ComponentName admin, int userHandle) {
732        if (mService != null) {
733            try {
734                return mService.getPasswordMinimumUpperCase(admin, userHandle);
735            } catch (RemoteException e) {
736                Log.w(TAG, "Failed talking with device policy service", e);
737            }
738        }
739        return 0;
740    }
741
742    /**
743     * Called by an application that is administering the device to set the
744     * minimum number of lower case letters required in the password. After
745     * setting this, the user will not be able to enter a new password that is
746     * not at least as restrictive as what has been set. Note that the current
747     * password will remain until the user has set a new one, so the change does
748     * not take place immediately. To prompt the user for a new password, use
749     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
750     * constraint is only imposed if the administrator has also requested
751     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
752     * default value is 0.
753     * <p>
754     * The calling device admin must have requested
755     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
756     * this method; if it has not, a security exception will be thrown.
757     *
758     * @param admin Which {@link DeviceAdminReceiver} this request is associated
759     *            with.
760     * @param length The new desired minimum number of lower case letters
761     *            required in the password. A value of 0 means there is no
762     *            restriction.
763     */
764    public void setPasswordMinimumLowerCase(ComponentName admin, int length) {
765        if (mService != null) {
766            try {
767                mService.setPasswordMinimumLowerCase(admin, length, UserHandle.myUserId());
768            } catch (RemoteException e) {
769                Log.w(TAG, "Failed talking with device policy service", e);
770            }
771        }
772    }
773
774    /**
775     * Retrieve the current number of lower case letters required in the
776     * password for all admins of this user and its profiles or a particular one.
777     * This is the same value as set by
778     * {#link {@link #setPasswordMinimumLowerCase(ComponentName, int)}
779     * and only applies when the password quality is
780     * {@link #PASSWORD_QUALITY_COMPLEX}.
781     *
782     * @param admin The name of the admin component to check, or null to
783     *            aggregate all admins.
784     * @return The minimum number of lower case letters required in the
785     *         password.
786     */
787    public int getPasswordMinimumLowerCase(ComponentName admin) {
788        return getPasswordMinimumLowerCase(admin, UserHandle.myUserId());
789    }
790
791    /** @hide per-user version */
792    public int getPasswordMinimumLowerCase(ComponentName admin, int userHandle) {
793        if (mService != null) {
794            try {
795                return mService.getPasswordMinimumLowerCase(admin, userHandle);
796            } catch (RemoteException e) {
797                Log.w(TAG, "Failed talking with device policy service", e);
798            }
799        }
800        return 0;
801    }
802
803    /**
804     * Called by an application that is administering the device to set the
805     * minimum number of letters required in the password. After setting this,
806     * the user will not be able to enter a new password that is not at least as
807     * restrictive as what has been set. Note that the current password will
808     * remain until the user has set a new one, so the change does not take
809     * place immediately. To prompt the user for a new password, use
810     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
811     * constraint is only imposed if the administrator has also requested
812     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
813     * default value is 1.
814     * <p>
815     * The calling device admin must have requested
816     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
817     * this method; if it has not, a security exception will be thrown.
818     *
819     * @param admin Which {@link DeviceAdminReceiver} this request is associated
820     *            with.
821     * @param length The new desired minimum number of letters required in the
822     *            password. A value of 0 means there is no restriction.
823     */
824    public void setPasswordMinimumLetters(ComponentName admin, int length) {
825        if (mService != null) {
826            try {
827                mService.setPasswordMinimumLetters(admin, length, UserHandle.myUserId());
828            } catch (RemoteException e) {
829                Log.w(TAG, "Failed talking with device policy service", e);
830            }
831        }
832    }
833
834    /**
835     * Retrieve the current number of letters required in the password for all
836     * admins or a particular one. This is the same value as
837     * set by {#link {@link #setPasswordMinimumLetters(ComponentName, int)}
838     * and only applies when the password quality is
839     * {@link #PASSWORD_QUALITY_COMPLEX}.
840     *
841     * @param admin The name of the admin component to check, or null to
842     *            aggregate all admins.
843     * @return The minimum number of letters required in the password.
844     */
845    public int getPasswordMinimumLetters(ComponentName admin) {
846        return getPasswordMinimumLetters(admin, UserHandle.myUserId());
847    }
848
849    /** @hide per-user version */
850    public int getPasswordMinimumLetters(ComponentName admin, int userHandle) {
851        if (mService != null) {
852            try {
853                return mService.getPasswordMinimumLetters(admin, userHandle);
854            } catch (RemoteException e) {
855                Log.w(TAG, "Failed talking with device policy service", e);
856            }
857        }
858        return 0;
859    }
860
861    /**
862     * Called by an application that is administering the device to set the
863     * minimum number of numerical digits required in the password. After
864     * setting this, the user will not be able to enter a new password that is
865     * not at least as restrictive as what has been set. Note that the current
866     * password will remain until the user has set a new one, so the change does
867     * not take place immediately. To prompt the user for a new password, use
868     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
869     * constraint is only imposed if the administrator has also requested
870     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
871     * default value is 1.
872     * <p>
873     * The calling device admin must have requested
874     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
875     * this method; if it has not, a security exception will be thrown.
876     *
877     * @param admin Which {@link DeviceAdminReceiver} this request is associated
878     *            with.
879     * @param length The new desired minimum number of numerical digits required
880     *            in the password. A value of 0 means there is no restriction.
881     */
882    public void setPasswordMinimumNumeric(ComponentName admin, int length) {
883        if (mService != null) {
884            try {
885                mService.setPasswordMinimumNumeric(admin, length, UserHandle.myUserId());
886            } catch (RemoteException e) {
887                Log.w(TAG, "Failed talking with device policy service", e);
888            }
889        }
890    }
891
892    /**
893     * Retrieve the current number of numerical digits required in the password
894     * for all admins of this user and its profiles or a particular one.
895     * This is the same value as set by
896     * {#link {@link #setPasswordMinimumNumeric(ComponentName, int)}
897     * and only applies when the password quality is
898     * {@link #PASSWORD_QUALITY_COMPLEX}.
899     *
900     * @param admin The name of the admin component to check, or null to
901     *            aggregate all admins.
902     * @return The minimum number of numerical digits required in the password.
903     */
904    public int getPasswordMinimumNumeric(ComponentName admin) {
905        return getPasswordMinimumNumeric(admin, UserHandle.myUserId());
906    }
907
908    /** @hide per-user version */
909    public int getPasswordMinimumNumeric(ComponentName admin, int userHandle) {
910        if (mService != null) {
911            try {
912                return mService.getPasswordMinimumNumeric(admin, userHandle);
913            } catch (RemoteException e) {
914                Log.w(TAG, "Failed talking with device policy service", e);
915            }
916        }
917        return 0;
918    }
919
920    /**
921     * Called by an application that is administering the device to set the
922     * minimum number of symbols required in the password. After setting this,
923     * the user will not be able to enter a new password that is not at least as
924     * restrictive as what has been set. Note that the current password will
925     * remain until the user has set a new one, so the change does not take
926     * place immediately. To prompt the user for a new password, use
927     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
928     * constraint is only imposed if the administrator has also requested
929     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
930     * default value is 1.
931     * <p>
932     * The calling device admin must have requested
933     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
934     * this method; if it has not, a security exception will be thrown.
935     *
936     * @param admin Which {@link DeviceAdminReceiver} this request is associated
937     *            with.
938     * @param length The new desired minimum number of symbols required in the
939     *            password. A value of 0 means there is no restriction.
940     */
941    public void setPasswordMinimumSymbols(ComponentName admin, int length) {
942        if (mService != null) {
943            try {
944                mService.setPasswordMinimumSymbols(admin, length, UserHandle.myUserId());
945            } catch (RemoteException e) {
946                Log.w(TAG, "Failed talking with device policy service", e);
947            }
948        }
949    }
950
951    /**
952     * Retrieve the current number of symbols required in the password for all
953     * admins or a particular one. This is the same value as
954     * set by {#link {@link #setPasswordMinimumSymbols(ComponentName, int)}
955     * and only applies when the password quality is
956     * {@link #PASSWORD_QUALITY_COMPLEX}.
957     *
958     * @param admin The name of the admin component to check, or null to
959     *            aggregate all admins.
960     * @return The minimum number of symbols required in the password.
961     */
962    public int getPasswordMinimumSymbols(ComponentName admin) {
963        return getPasswordMinimumSymbols(admin, UserHandle.myUserId());
964    }
965
966    /** @hide per-user version */
967    public int getPasswordMinimumSymbols(ComponentName admin, int userHandle) {
968        if (mService != null) {
969            try {
970                return mService.getPasswordMinimumSymbols(admin, userHandle);
971            } catch (RemoteException e) {
972                Log.w(TAG, "Failed talking with device policy service", e);
973            }
974        }
975        return 0;
976    }
977
978    /**
979     * Called by an application that is administering the device to set the
980     * minimum number of non-letter characters (numerical digits or symbols)
981     * required in the password. After setting this, the user will not be able
982     * to enter a new password that is not at least as restrictive as what has
983     * been set. Note that the current password will remain until the user has
984     * set a new one, so the change does not take place immediately. To prompt
985     * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} after
986     * setting this value. This constraint is only imposed if the administrator
987     * has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
988     * {@link #setPasswordQuality}. The default value is 0.
989     * <p>
990     * The calling device admin must have requested
991     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
992     * this method; if it has not, a security exception will be thrown.
993     *
994     * @param admin Which {@link DeviceAdminReceiver} this request is associated
995     *            with.
996     * @param length The new desired minimum number of letters required in the
997     *            password. A value of 0 means there is no restriction.
998     */
999    public void setPasswordMinimumNonLetter(ComponentName admin, int length) {
1000        if (mService != null) {
1001            try {
1002                mService.setPasswordMinimumNonLetter(admin, length, UserHandle.myUserId());
1003            } catch (RemoteException e) {
1004                Log.w(TAG, "Failed talking with device policy service", e);
1005            }
1006        }
1007    }
1008
1009    /**
1010     * Retrieve the current number of non-letter characters required in the
1011     * password for all admins of this user and its profiles or a particular one.
1012     * This is the same value as set by
1013     * {#link {@link #setPasswordMinimumNonLetter(ComponentName, int)}
1014     * and only applies when the password quality is
1015     * {@link #PASSWORD_QUALITY_COMPLEX}.
1016     *
1017     * @param admin The name of the admin component to check, or null to
1018     *            aggregate all admins.
1019     * @return The minimum number of letters required in the password.
1020     */
1021    public int getPasswordMinimumNonLetter(ComponentName admin) {
1022        return getPasswordMinimumNonLetter(admin, UserHandle.myUserId());
1023    }
1024
1025    /** @hide per-user version */
1026    public int getPasswordMinimumNonLetter(ComponentName admin, int userHandle) {
1027        if (mService != null) {
1028            try {
1029                return mService.getPasswordMinimumNonLetter(admin, userHandle);
1030            } catch (RemoteException e) {
1031                Log.w(TAG, "Failed talking with device policy service", e);
1032            }
1033        }
1034        return 0;
1035    }
1036
1037  /**
1038   * Called by an application that is administering the device to set the length
1039   * of the password history. After setting this, the user will not be able to
1040   * enter a new password that is the same as any password in the history. Note
1041   * that the current password will remain until the user has set a new one, so
1042   * the change does not take place immediately. To prompt the user for a new
1043   * password, use {@link #ACTION_SET_NEW_PASSWORD} after setting this value.
1044   * This constraint is only imposed if the administrator has also requested
1045   * either {@link #PASSWORD_QUALITY_NUMERIC},
1046   * {@link #PASSWORD_QUALITY_ALPHABETIC}, or
1047   * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
1048   *
1049   * <p>
1050   * The calling device admin must have requested
1051   * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this
1052   * method; if it has not, a security exception will be thrown.
1053   *
1054   * @param admin Which {@link DeviceAdminReceiver} this request is associated
1055   *        with.
1056   * @param length The new desired length of password history. A value of 0
1057   *        means there is no restriction.
1058   */
1059    public void setPasswordHistoryLength(ComponentName admin, int length) {
1060        if (mService != null) {
1061            try {
1062                mService.setPasswordHistoryLength(admin, length, UserHandle.myUserId());
1063            } catch (RemoteException e) {
1064                Log.w(TAG, "Failed talking with device policy service", e);
1065            }
1066        }
1067    }
1068
1069    /**
1070     * Called by a device admin to set the password expiration timeout. Calling this method
1071     * will restart the countdown for password expiration for the given admin, as will changing
1072     * the device password (for all admins).
1073     *
1074     * <p>The provided timeout is the time delta in ms and will be added to the current time.
1075     * For example, to have the password expire 5 days from now, timeout would be
1076     * 5 * 86400 * 1000 = 432000000 ms for timeout.
1077     *
1078     * <p>To disable password expiration, a value of 0 may be used for timeout.
1079     *
1080     * <p>The calling device admin must have requested
1081     * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this
1082     * method; if it has not, a security exception will be thrown.
1083     *
1084     * <p> Note that setting the password will automatically reset the expiration time for all
1085     * active admins. Active admins do not need to explicitly call this method in that case.
1086     *
1087     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1088     * @param timeout The limit (in ms) that a password can remain in effect. A value of 0
1089     *        means there is no restriction (unlimited).
1090     */
1091    public void setPasswordExpirationTimeout(ComponentName admin, long timeout) {
1092        if (mService != null) {
1093            try {
1094                mService.setPasswordExpirationTimeout(admin, timeout, UserHandle.myUserId());
1095            } catch (RemoteException e) {
1096                Log.w(TAG, "Failed talking with device policy service", e);
1097            }
1098        }
1099    }
1100
1101    /**
1102     * Get the password expiration timeout for the given admin. The expiration timeout is the
1103     * recurring expiration timeout provided in the call to
1104     * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
1105     * aggregate of all policy administrators if admin is null.
1106     *
1107     * @param admin The name of the admin component to check, or null to aggregate all admins.
1108     * @return The timeout for the given admin or the minimum of all timeouts
1109     */
1110    public long getPasswordExpirationTimeout(ComponentName admin) {
1111        if (mService != null) {
1112            try {
1113                return mService.getPasswordExpirationTimeout(admin, UserHandle.myUserId());
1114            } catch (RemoteException e) {
1115                Log.w(TAG, "Failed talking with device policy service", e);
1116            }
1117        }
1118        return 0;
1119    }
1120
1121    /**
1122     * Get the current password expiration time for the given admin or an aggregate of
1123     * all admins of this user and its profiles if admin is null. If the password is
1124     * expired, this will return the time since the password expired as a negative number.
1125     * If admin is null, then a composite of all expiration timeouts is returned
1126     * - which will be the minimum of all timeouts.
1127     *
1128     * @param admin The name of the admin component to check, or null to aggregate all admins.
1129     * @return The password expiration time, in ms.
1130     */
1131    public long getPasswordExpiration(ComponentName admin) {
1132        if (mService != null) {
1133            try {
1134                return mService.getPasswordExpiration(admin, UserHandle.myUserId());
1135            } catch (RemoteException e) {
1136                Log.w(TAG, "Failed talking with device policy service", e);
1137            }
1138        }
1139        return 0;
1140    }
1141
1142    /**
1143     * Retrieve the current password history length for all admins of this
1144     * user and its profiles or a particular one.
1145     * @param admin The name of the admin component to check, or null to aggregate
1146     * all admins.
1147     * @return The length of the password history
1148     */
1149    public int getPasswordHistoryLength(ComponentName admin) {
1150        return getPasswordHistoryLength(admin, UserHandle.myUserId());
1151    }
1152
1153    /** @hide per-user version */
1154    public int getPasswordHistoryLength(ComponentName admin, int userHandle) {
1155        if (mService != null) {
1156            try {
1157                return mService.getPasswordHistoryLength(admin, userHandle);
1158            } catch (RemoteException e) {
1159                Log.w(TAG, "Failed talking with device policy service", e);
1160            }
1161        }
1162        return 0;
1163    }
1164
1165    /**
1166     * Return the maximum password length that the device supports for a
1167     * particular password quality.
1168     * @param quality The quality being interrogated.
1169     * @return Returns the maximum length that the user can enter.
1170     */
1171    public int getPasswordMaximumLength(int quality) {
1172        // Kind-of arbitrary.
1173        return 16;
1174    }
1175
1176    /**
1177     * Determine whether the current password the user has set is sufficient
1178     * to meet the policy requirements (quality, minimum length) that have been
1179     * requested by the admins of this user and its profiles.
1180     *
1181     * <p>The calling device admin must have requested
1182     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1183     * this method; if it has not, a security exception will be thrown.
1184     *
1185     * @return Returns true if the password meets the current requirements, else false.
1186     */
1187    public boolean isActivePasswordSufficient() {
1188        if (mService != null) {
1189            try {
1190                return mService.isActivePasswordSufficient(UserHandle.myUserId());
1191            } catch (RemoteException e) {
1192                Log.w(TAG, "Failed talking with device policy service", e);
1193            }
1194        }
1195        return false;
1196    }
1197
1198    /**
1199     * Retrieve the number of times the user has failed at entering a
1200     * password since that last successful password entry.
1201     *
1202     * <p>The calling device admin must have requested
1203     * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call
1204     * this method; if it has not, a security exception will be thrown.
1205     */
1206    public int getCurrentFailedPasswordAttempts() {
1207        if (mService != null) {
1208            try {
1209                return mService.getCurrentFailedPasswordAttempts(UserHandle.myUserId());
1210            } catch (RemoteException e) {
1211                Log.w(TAG, "Failed talking with device policy service", e);
1212            }
1213        }
1214        return -1;
1215    }
1216
1217    /**
1218     * Setting this to a value greater than zero enables a built-in policy
1219     * that will perform a device wipe after too many incorrect
1220     * device-unlock passwords have been entered.  This built-in policy combines
1221     * watching for failed passwords and wiping the device, and requires
1222     * that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
1223     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
1224     *
1225     * <p>To implement any other policy (e.g. wiping data for a particular
1226     * application only, erasing or revoking credentials, or reporting the
1227     * failure to a server), you should implement
1228     * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)}
1229     * instead.  Do not use this API, because if the maximum count is reached,
1230     * the device will be wiped immediately, and your callback will not be invoked.
1231     *
1232     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1233     * @param num The number of failed password attempts at which point the
1234     * device will wipe its data.
1235     */
1236    public void setMaximumFailedPasswordsForWipe(ComponentName admin, int num) {
1237        if (mService != null) {
1238            try {
1239                mService.setMaximumFailedPasswordsForWipe(admin, num, UserHandle.myUserId());
1240            } catch (RemoteException e) {
1241                Log.w(TAG, "Failed talking with device policy service", e);
1242            }
1243        }
1244    }
1245
1246    /**
1247     * Retrieve the current maximum number of login attempts that are allowed
1248     * before the device wipes itself, for all admins of this user and its profiles
1249     * or a particular one.
1250     * @param admin The name of the admin component to check, or null to aggregate
1251     * all admins.
1252     */
1253    public int getMaximumFailedPasswordsForWipe(ComponentName admin) {
1254        return getMaximumFailedPasswordsForWipe(admin, UserHandle.myUserId());
1255    }
1256
1257    /** @hide per-user version */
1258    public int getMaximumFailedPasswordsForWipe(ComponentName admin, int userHandle) {
1259        if (mService != null) {
1260            try {
1261                return mService.getMaximumFailedPasswordsForWipe(admin, userHandle);
1262            } catch (RemoteException e) {
1263                Log.w(TAG, "Failed talking with device policy service", e);
1264            }
1265        }
1266        return 0;
1267    }
1268
1269    /**
1270     * Flag for {@link #resetPassword}: don't allow other admins to change
1271     * the password again until the user has entered it.
1272     */
1273    public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
1274
1275    /**
1276     * Force a new device unlock password (the password needed to access the
1277     * entire device, not for individual accounts) on the user.  This takes
1278     * effect immediately.
1279     * The given password must be sufficient for the
1280     * current password quality and length constraints as returned by
1281     * {@link #getPasswordQuality(ComponentName)} and
1282     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet
1283     * these constraints, then it will be rejected and false returned.  Note
1284     * that the password may be a stronger quality (containing alphanumeric
1285     * characters when the requested quality is only numeric), in which case
1286     * the currently active quality will be increased to match.
1287     *
1288     * <p>The calling device admin must have requested
1289     * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call
1290     * this method; if it has not, a security exception will be thrown.
1291     *
1292     * Can not be called from a managed profile.
1293     *
1294     * @param password The new password for the user.
1295     * @param flags May be 0 or {@link #RESET_PASSWORD_REQUIRE_ENTRY}.
1296     * @return Returns true if the password was applied, or false if it is
1297     * not acceptable for the current constraints.
1298     */
1299    public boolean resetPassword(String password, int flags) {
1300        if (mService != null) {
1301            try {
1302                return mService.resetPassword(password, flags, UserHandle.myUserId());
1303            } catch (RemoteException e) {
1304                Log.w(TAG, "Failed talking with device policy service", e);
1305            }
1306        }
1307        return false;
1308    }
1309
1310    /**
1311     * Called by an application that is administering the device to set the
1312     * maximum time for user activity until the device will lock.  This limits
1313     * the length that the user can set.  It takes effect immediately.
1314     *
1315     * <p>The calling device admin must have requested
1316     * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} to be able to call
1317     * this method; if it has not, a security exception will be thrown.
1318     *
1319     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1320     * @param timeMs The new desired maximum time to lock in milliseconds.
1321     * A value of 0 means there is no restriction.
1322     */
1323    public void setMaximumTimeToLock(ComponentName admin, long timeMs) {
1324        if (mService != null) {
1325            try {
1326                mService.setMaximumTimeToLock(admin, timeMs, UserHandle.myUserId());
1327            } catch (RemoteException e) {
1328                Log.w(TAG, "Failed talking with device policy service", e);
1329            }
1330        }
1331    }
1332
1333    /**
1334     * Retrieve the current maximum time to unlock for all admins of this user
1335     * and its profiles or a particular one.
1336     * @param admin The name of the admin component to check, or null to aggregate
1337     * all admins.
1338     */
1339    public long getMaximumTimeToLock(ComponentName admin) {
1340        return getMaximumTimeToLock(admin, UserHandle.myUserId());
1341    }
1342
1343    /** @hide per-user version */
1344    public long getMaximumTimeToLock(ComponentName admin, int userHandle) {
1345        if (mService != null) {
1346            try {
1347                return mService.getMaximumTimeToLock(admin, userHandle);
1348            } catch (RemoteException e) {
1349                Log.w(TAG, "Failed talking with device policy service", e);
1350            }
1351        }
1352        return 0;
1353    }
1354
1355    /**
1356     * Make the device lock immediately, as if the lock screen timeout has
1357     * expired at the point of this call.
1358     *
1359     * <p>The calling device admin must have requested
1360     * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} to be able to call
1361     * this method; if it has not, a security exception will be thrown.
1362     */
1363    public void lockNow() {
1364        if (mService != null) {
1365            try {
1366                mService.lockNow();
1367            } catch (RemoteException e) {
1368                Log.w(TAG, "Failed talking with device policy service", e);
1369            }
1370        }
1371    }
1372
1373    /**
1374     * Flag for {@link #wipeData(int)}: also erase the device's external
1375     * storage.
1376     */
1377    public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
1378
1379    /**
1380     * Ask the user date be wiped.  This will cause the device to reboot,
1381     * erasing all user data while next booting up.  External storage such
1382     * as SD cards will be also erased if the flag {@link #WIPE_EXTERNAL_STORAGE}
1383     * is set.
1384     *
1385     * <p>The calling device admin must have requested
1386     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to be able to call
1387     * this method; if it has not, a security exception will be thrown.
1388     *
1389     * @param flags Bit mask of additional options: currently 0 and
1390     *              {@link #WIPE_EXTERNAL_STORAGE} are supported.
1391     */
1392    public void wipeData(int flags) {
1393        if (mService != null) {
1394            try {
1395                mService.wipeData(flags, UserHandle.myUserId());
1396            } catch (RemoteException e) {
1397                Log.w(TAG, "Failed talking with device policy service", e);
1398            }
1399        }
1400    }
1401
1402    /**
1403     * Called by an application that is administering the device to set the
1404     * global proxy and exclusion list.
1405     * <p>
1406     * The calling device admin must have requested
1407     * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
1408     * this method; if it has not, a security exception will be thrown.
1409     * Only the first device admin can set the proxy. If a second admin attempts
1410     * to set the proxy, the {@link ComponentName} of the admin originally setting the
1411     * proxy will be returned. If successful in setting the proxy, null will
1412     * be returned.
1413     * The method can be called repeatedly by the device admin alrady setting the
1414     * proxy to update the proxy and exclusion list.
1415     *
1416     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1417     *            with.
1418     * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
1419     *            Pass Proxy.NO_PROXY to reset the proxy.
1420     * @param exclusionList a list of domains to be excluded from the global proxy.
1421     * @return returns null if the proxy was successfully set, or a {@link ComponentName}
1422     *            of the device admin that sets thew proxy otherwise.
1423     * @hide
1424     */
1425    public ComponentName setGlobalProxy(ComponentName admin, Proxy proxySpec,
1426            List<String> exclusionList ) {
1427        if (proxySpec == null) {
1428            throw new NullPointerException();
1429        }
1430        if (mService != null) {
1431            try {
1432                String hostSpec;
1433                String exclSpec;
1434                if (proxySpec.equals(Proxy.NO_PROXY)) {
1435                    hostSpec = null;
1436                    exclSpec = null;
1437                } else {
1438                    if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
1439                        throw new IllegalArgumentException();
1440                    }
1441                    InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
1442                    String hostName = sa.getHostName();
1443                    int port = sa.getPort();
1444                    StringBuilder hostBuilder = new StringBuilder();
1445                    hostSpec = hostBuilder.append(hostName)
1446                        .append(":").append(Integer.toString(port)).toString();
1447                    if (exclusionList == null) {
1448                        exclSpec = "";
1449                    } else {
1450                        StringBuilder listBuilder = new StringBuilder();
1451                        boolean firstDomain = true;
1452                        for (String exclDomain : exclusionList) {
1453                            if (!firstDomain) {
1454                                listBuilder = listBuilder.append(",");
1455                            } else {
1456                                firstDomain = false;
1457                            }
1458                            listBuilder = listBuilder.append(exclDomain.trim());
1459                        }
1460                        exclSpec = listBuilder.toString();
1461                    }
1462                    if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
1463                            != android.net.Proxy.PROXY_VALID)
1464                        throw new IllegalArgumentException();
1465                }
1466                return mService.setGlobalProxy(admin, hostSpec, exclSpec, UserHandle.myUserId());
1467            } catch (RemoteException e) {
1468                Log.w(TAG, "Failed talking with device policy service", e);
1469            }
1470        }
1471        return null;
1472    }
1473
1474    /**
1475     * Set a network-independent global HTTP proxy.  This is not normally what you want
1476     * for typical HTTP proxies - they are generally network dependent.  However if you're
1477     * doing something unusual like general internal filtering this may be useful.  On
1478     * a private network where the proxy is not accessible, you may break HTTP using this.
1479     *
1480     * <p>This method requires the caller to be the device owner.
1481     *
1482     * <p>This proxy is only a recommendation and it is possible that some apps will ignore it.
1483     * @see ProxyInfo
1484     *
1485     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1486     *            with.
1487     * @param proxyInfo The a {@link ProxyInfo} object defining the new global
1488     *        HTTP proxy.  A {@code null} value will clear the global HTTP proxy.
1489     */
1490    public void setRecommendedGlobalProxy(ComponentName admin, ProxyInfo proxyInfo) {
1491        if (mService != null) {
1492            try {
1493                mService.setRecommendedGlobalProxy(admin, proxyInfo);
1494            } catch (RemoteException e) {
1495                Log.w(TAG, "Failed talking with device policy service", e);
1496            }
1497        }
1498    }
1499
1500    /**
1501     * Returns the component name setting the global proxy.
1502     * @return ComponentName object of the device admin that set the global proxy, or
1503     *            null if no admin has set the proxy.
1504     * @hide
1505     */
1506    public ComponentName getGlobalProxyAdmin() {
1507        if (mService != null) {
1508            try {
1509                return mService.getGlobalProxyAdmin(UserHandle.myUserId());
1510            } catch (RemoteException e) {
1511                Log.w(TAG, "Failed talking with device policy service", e);
1512            }
1513        }
1514        return null;
1515    }
1516
1517    /**
1518     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
1519     * indicating that encryption is not supported.
1520     */
1521    public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
1522
1523    /**
1524     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
1525     * indicating that encryption is supported, but is not currently active.
1526     */
1527    public static final int ENCRYPTION_STATUS_INACTIVE = 1;
1528
1529    /**
1530     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
1531     * indicating that encryption is not currently active, but is currently
1532     * being activated.  This is only reported by devices that support
1533     * encryption of data and only when the storage is currently
1534     * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
1535     * to become encrypted will never return this value.
1536     */
1537    public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
1538
1539    /**
1540     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
1541     * indicating that encryption is active.
1542     */
1543    public static final int ENCRYPTION_STATUS_ACTIVE = 3;
1544
1545    /**
1546     * Activity action: begin the process of encrypting data on the device.  This activity should
1547     * be launched after using {@link #setStorageEncryption} to request encryption be activated.
1548     * After resuming from this activity, use {@link #getStorageEncryption}
1549     * to check encryption status.  However, on some devices this activity may never return, as
1550     * it may trigger a reboot and in some cases a complete data wipe of the device.
1551     */
1552    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1553    public static final String ACTION_START_ENCRYPTION
1554            = "android.app.action.START_ENCRYPTION";
1555
1556    /**
1557     * Widgets are enabled in keyguard
1558     */
1559    public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
1560
1561    /**
1562     * Disable all keyguard widgets. Has no effect.
1563     */
1564    public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
1565
1566    /**
1567     * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
1568     */
1569    public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
1570
1571    /**
1572     * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
1573     */
1574    public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
1575
1576    /**
1577     * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
1578     */
1579    public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
1580
1581    /**
1582     * Ignore {@link TrustAgentService} state on secure keyguard screens
1583     * (e.g. PIN/Pattern/Password).
1584     */
1585    public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
1586
1587    /**
1588     * Disable all current and future keyguard customizations.
1589     */
1590    public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
1591
1592    /**
1593     * Called by an application that is administering the device to
1594     * request that the storage system be encrypted.
1595     *
1596     * <p>When multiple device administrators attempt to control device
1597     * encryption, the most secure, supported setting will always be
1598     * used.  If any device administrator requests device encryption,
1599     * it will be enabled;  Conversely, if a device administrator
1600     * attempts to disable device encryption while another
1601     * device administrator has enabled it, the call to disable will
1602     * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
1603     *
1604     * <p>This policy controls encryption of the secure (application data) storage area.  Data
1605     * written to other storage areas may or may not be encrypted, and this policy does not require
1606     * or control the encryption of any other storage areas.
1607     * There is one exception:  If {@link android.os.Environment#isExternalStorageEmulated()} is
1608     * {@code true}, then the directory returned by
1609     * {@link android.os.Environment#getExternalStorageDirectory()} must be written to disk
1610     * within the encrypted storage area.
1611     *
1612     * <p>Important Note:  On some devices, it is possible to encrypt storage without requiring
1613     * the user to create a device PIN or Password.  In this case, the storage is encrypted, but
1614     * the encryption key may not be fully secured.  For maximum security, the administrator should
1615     * also require (and check for) a pattern, PIN, or password.
1616     *
1617     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1618     * @param encrypt true to request encryption, false to release any previous request
1619     * @return the new request status (for all active admins) - will be one of
1620     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, or
1621     * {@link #ENCRYPTION_STATUS_ACTIVE}.  This is the value of the requests;  Use
1622     * {@link #getStorageEncryptionStatus()} to query the actual device state.
1623     */
1624    public int setStorageEncryption(ComponentName admin, boolean encrypt) {
1625        if (mService != null) {
1626            try {
1627                return mService.setStorageEncryption(admin, encrypt, UserHandle.myUserId());
1628            } catch (RemoteException e) {
1629                Log.w(TAG, "Failed talking with device policy service", e);
1630            }
1631        }
1632        return ENCRYPTION_STATUS_UNSUPPORTED;
1633    }
1634
1635    /**
1636     * Called by an application that is administering the device to
1637     * determine the requested setting for secure storage.
1638     *
1639     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
1640     * this will return the requested encryption setting as an aggregate of all active
1641     * administrators.
1642     * @return true if the admin(s) are requesting encryption, false if not.
1643     */
1644    public boolean getStorageEncryption(ComponentName admin) {
1645        if (mService != null) {
1646            try {
1647                return mService.getStorageEncryption(admin, UserHandle.myUserId());
1648            } catch (RemoteException e) {
1649                Log.w(TAG, "Failed talking with device policy service", e);
1650            }
1651        }
1652        return false;
1653    }
1654
1655    /**
1656     * Called by an application that is administering the device to
1657     * determine the current encryption status of the device.
1658     *
1659     * Depending on the returned status code, the caller may proceed in different
1660     * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
1661     * storage system does not support encryption.  If the
1662     * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
1663     * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
1664     * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING} or
1665     * {@link #ENCRYPTION_STATUS_ACTIVE}, no further action is required.
1666     *
1667     * @return current status of encryption.  The value will be one of
1668     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
1669     * {@link #ENCRYPTION_STATUS_ACTIVATING}, or{@link #ENCRYPTION_STATUS_ACTIVE}.
1670     */
1671    public int getStorageEncryptionStatus() {
1672        return getStorageEncryptionStatus(UserHandle.myUserId());
1673    }
1674
1675    /** @hide per-user version */
1676    public int getStorageEncryptionStatus(int userHandle) {
1677        if (mService != null) {
1678            try {
1679                return mService.getStorageEncryptionStatus(userHandle);
1680            } catch (RemoteException e) {
1681                Log.w(TAG, "Failed talking with device policy service", e);
1682            }
1683        }
1684        return ENCRYPTION_STATUS_UNSUPPORTED;
1685    }
1686
1687    /**
1688     * Installs the given certificate as a User CA.
1689     *
1690     * @return false if the certBuffer cannot be parsed or installation is
1691     *         interrupted, otherwise true
1692     */
1693    public boolean installCaCert(ComponentName who, byte[] certBuffer) {
1694        if (mService != null) {
1695            try {
1696                return mService.installCaCert(who, certBuffer);
1697            } catch (RemoteException e) {
1698                Log.w(TAG, "Failed talking with device policy service", e);
1699            }
1700        }
1701        return false;
1702    }
1703
1704    /**
1705     * Uninstalls the given certificate from the list of User CAs, if present.
1706     */
1707    public void uninstallCaCert(ComponentName who, byte[] certBuffer) {
1708        if (mService != null) {
1709            try {
1710                final String alias = getCaCertAlias(certBuffer);
1711                mService.uninstallCaCert(who, alias);
1712            } catch (CertificateException e) {
1713                Log.w(TAG, "Unable to parse certificate", e);
1714            } catch (RemoteException e) {
1715                Log.w(TAG, "Failed talking with device policy service", e);
1716            }
1717        }
1718    }
1719
1720    /**
1721     * Returns whether there are any user-installed CA certificates.
1722     */
1723    public boolean hasAnyCaCertsInstalled() {
1724        TrustedCertificateStore certStore = new TrustedCertificateStore();
1725        Set<String> aliases = certStore.userAliases();
1726        return aliases != null && !aliases.isEmpty();
1727    }
1728
1729    /**
1730     * Returns whether this certificate has been installed as a User CA.
1731     */
1732    public boolean hasCaCertInstalled(byte[] certBuffer) {
1733        try {
1734            return getCaCertAlias(certBuffer) != null;
1735        } catch (CertificateException ce) {
1736            Log.w(TAG, "Could not parse certificate", ce);
1737        }
1738        return false;
1739    }
1740
1741    /**
1742     * Returns the alias of a given CA certificate in the certificate store, or null if it
1743     * doesn't exist.
1744     */
1745    private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
1746        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
1747        final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
1748                              new ByteArrayInputStream(certBuffer));
1749        return new TrustedCertificateStore().getCertificateAlias(cert);
1750    }
1751
1752    /**
1753     * Called by an application that is administering the device to disable all cameras
1754     * on the device.  After setting this, no applications will be able to access any cameras
1755     * on the device.
1756     *
1757     * <p>The calling device admin must have requested
1758     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call
1759     * this method; if it has not, a security exception will be thrown.
1760     *
1761     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1762     * @param disabled Whether or not the camera should be disabled.
1763     */
1764    public void setCameraDisabled(ComponentName admin, boolean disabled) {
1765        if (mService != null) {
1766            try {
1767                mService.setCameraDisabled(admin, disabled, UserHandle.myUserId());
1768            } catch (RemoteException e) {
1769                Log.w(TAG, "Failed talking with device policy service", e);
1770            }
1771        }
1772    }
1773
1774    /**
1775     * Determine whether or not the device's cameras have been disabled either by the current
1776     * admin, if specified, or all admins.
1777     * @param admin The name of the admin component to check, or null to check if any admins
1778     * have disabled the camera
1779     */
1780    public boolean getCameraDisabled(ComponentName admin) {
1781        return getCameraDisabled(admin, UserHandle.myUserId());
1782    }
1783
1784    /** @hide per-user version */
1785    public boolean getCameraDisabled(ComponentName admin, int userHandle) {
1786        if (mService != null) {
1787            try {
1788                return mService.getCameraDisabled(admin, userHandle);
1789            } catch (RemoteException e) {
1790                Log.w(TAG, "Failed talking with device policy service", e);
1791            }
1792        }
1793        return false;
1794    }
1795
1796    /**
1797     * Called by an application that is administering the device to disable keyguard customizations,
1798     * such as widgets. After setting this, keyguard features will be disabled according to the
1799     * provided feature list.
1800     *
1801     * <p>The calling device admin must have requested
1802     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call
1803     * this method; if it has not, a security exception will be thrown.
1804     *
1805     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1806     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
1807     * {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
1808     * {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}, {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
1809     * {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
1810     */
1811    public void setKeyguardDisabledFeatures(ComponentName admin, int which) {
1812        if (mService != null) {
1813            try {
1814                mService.setKeyguardDisabledFeatures(admin, which, UserHandle.myUserId());
1815            } catch (RemoteException e) {
1816                Log.w(TAG, "Failed talking with device policy service", e);
1817            }
1818        }
1819    }
1820
1821    /**
1822     * Determine whether or not features have been disabled in keyguard either by the current
1823     * admin, if specified, or all admins.
1824     * @param admin The name of the admin component to check, or null to check if any admins
1825     * have disabled features in keyguard.
1826     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
1827     * for a list.
1828     */
1829    public int getKeyguardDisabledFeatures(ComponentName admin) {
1830        return getKeyguardDisabledFeatures(admin, UserHandle.myUserId());
1831    }
1832
1833    /** @hide per-user version */
1834    public int getKeyguardDisabledFeatures(ComponentName admin, int userHandle) {
1835        if (mService != null) {
1836            try {
1837                return mService.getKeyguardDisabledFeatures(admin, userHandle);
1838            } catch (RemoteException e) {
1839                Log.w(TAG, "Failed talking with device policy service", e);
1840            }
1841        }
1842        return KEYGUARD_DISABLE_FEATURES_NONE;
1843    }
1844
1845    /**
1846     * @hide
1847     */
1848    public void setActiveAdmin(ComponentName policyReceiver, boolean refreshing, int userHandle) {
1849        if (mService != null) {
1850            try {
1851                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
1852            } catch (RemoteException e) {
1853                Log.w(TAG, "Failed talking with device policy service", e);
1854            }
1855        }
1856    }
1857
1858    /**
1859     * @hide
1860     */
1861    public void setActiveAdmin(ComponentName policyReceiver, boolean refreshing) {
1862        setActiveAdmin(policyReceiver, refreshing, UserHandle.myUserId());
1863    }
1864
1865    /**
1866     * Returns the DeviceAdminInfo as defined by the administrator's package info & meta-data
1867     * @hide
1868     */
1869    public DeviceAdminInfo getAdminInfo(ComponentName cn) {
1870        ActivityInfo ai;
1871        try {
1872            ai = mContext.getPackageManager().getReceiverInfo(cn,
1873                    PackageManager.GET_META_DATA);
1874        } catch (PackageManager.NameNotFoundException e) {
1875            Log.w(TAG, "Unable to retrieve device policy " + cn, e);
1876            return null;
1877        }
1878
1879        ResolveInfo ri = new ResolveInfo();
1880        ri.activityInfo = ai;
1881
1882        try {
1883            return new DeviceAdminInfo(mContext, ri);
1884        } catch (XmlPullParserException e) {
1885            Log.w(TAG, "Unable to parse device policy " + cn, e);
1886            return null;
1887        } catch (IOException e) {
1888            Log.w(TAG, "Unable to parse device policy " + cn, e);
1889            return null;
1890        }
1891    }
1892
1893    /**
1894     * @hide
1895     */
1896    public void getRemoveWarning(ComponentName admin, RemoteCallback result) {
1897        if (mService != null) {
1898            try {
1899                mService.getRemoveWarning(admin, result, UserHandle.myUserId());
1900            } catch (RemoteException e) {
1901                Log.w(TAG, "Failed talking with device policy service", e);
1902            }
1903        }
1904    }
1905
1906    /**
1907     * @hide
1908     */
1909    public void setActivePasswordState(int quality, int length, int letters, int uppercase,
1910            int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
1911        if (mService != null) {
1912            try {
1913                mService.setActivePasswordState(quality, length, letters, uppercase, lowercase,
1914                        numbers, symbols, nonletter, userHandle);
1915            } catch (RemoteException e) {
1916                Log.w(TAG, "Failed talking with device policy service", e);
1917            }
1918        }
1919    }
1920
1921    /**
1922     * @hide
1923     */
1924    public void reportFailedPasswordAttempt(int userHandle) {
1925        if (mService != null) {
1926            try {
1927                mService.reportFailedPasswordAttempt(userHandle);
1928            } catch (RemoteException e) {
1929                Log.w(TAG, "Failed talking with device policy service", e);
1930            }
1931        }
1932    }
1933
1934    /**
1935     * @hide
1936     */
1937    public void reportSuccessfulPasswordAttempt(int userHandle) {
1938        if (mService != null) {
1939            try {
1940                mService.reportSuccessfulPasswordAttempt(userHandle);
1941            } catch (RemoteException e) {
1942                Log.w(TAG, "Failed talking with device policy service", e);
1943            }
1944        }
1945    }
1946
1947    /**
1948     * @hide
1949     * Sets the given package as the device owner. The package must already be installed and there
1950     * shouldn't be an existing device owner registered, for this call to succeed. Also, this
1951     * method must be called before the device is provisioned.
1952     * @param packageName the package name of the application to be registered as the device owner.
1953     * @return whether the package was successfully registered as the device owner.
1954     * @throws IllegalArgumentException if the package name is null or invalid
1955     * @throws IllegalStateException if a device owner is already registered or the device has
1956     *         already been provisioned.
1957     */
1958    public boolean setDeviceOwner(String packageName) throws IllegalArgumentException,
1959            IllegalStateException {
1960        return setDeviceOwner(packageName, null);
1961    }
1962
1963    /**
1964     * @hide
1965     * Sets the given package as the device owner. The package must already be installed and there
1966     * shouldn't be an existing device owner registered, for this call to succeed. Also, this
1967     * method must be called before the device is provisioned.
1968     * @param packageName the package name of the application to be registered as the device owner.
1969     * @param ownerName the human readable name of the institution that owns this device.
1970     * @return whether the package was successfully registered as the device owner.
1971     * @throws IllegalArgumentException if the package name is null or invalid
1972     * @throws IllegalStateException if a device owner is already registered or the device has
1973     *         already been provisioned.
1974     */
1975    public boolean setDeviceOwner(String packageName, String ownerName)
1976            throws IllegalArgumentException, IllegalStateException {
1977        if (mService != null) {
1978            try {
1979                return mService.setDeviceOwner(packageName, ownerName);
1980            } catch (RemoteException re) {
1981                Log.w(TAG, "Failed to set device owner");
1982            }
1983        }
1984        return false;
1985    }
1986
1987
1988    /**
1989     * Used to determine if a particular package has been registered as a Device Owner app.
1990     * A device owner app is a special device admin that cannot be deactivated by the user, once
1991     * activated as a device admin. It also cannot be uninstalled. To check if a particular
1992     * package is currently registered as the device owner app, pass in the package name from
1993     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
1994     * admin apps that want to check if they are also registered as the device owner app. The
1995     * exact mechanism by which a device admin app is registered as a device owner app is defined by
1996     * the setup process.
1997     * @param packageName the package name of the app, to compare with the registered device owner
1998     * app, if any.
1999     * @return whether or not the package is registered as the device owner app.
2000     */
2001    public boolean isDeviceOwnerApp(String packageName) {
2002        if (mService != null) {
2003            try {
2004                return mService.isDeviceOwner(packageName);
2005            } catch (RemoteException re) {
2006                Log.w(TAG, "Failed to check device owner");
2007            }
2008        }
2009        return false;
2010    }
2011
2012    /**
2013     * @hide
2014     * Redirect to isDeviceOwnerApp.
2015     */
2016    public boolean isDeviceOwner(String packageName) {
2017        return isDeviceOwnerApp(packageName);
2018    }
2019
2020    /**
2021     * Clears the current device owner.  The caller must be the device owner.
2022     *
2023     * This function should be used cautiously as once it is called it cannot
2024     * be undone.  The device owner can only be set as a part of device setup
2025     * before setup completes.
2026     *
2027     * @param packageName The package name of the device owner.
2028     */
2029    public void clearDeviceOwnerApp(String packageName) {
2030        if (mService != null) {
2031            try {
2032                mService.clearDeviceOwner(packageName);
2033            } catch (RemoteException re) {
2034                Log.w(TAG, "Failed to clear device owner");
2035            }
2036        }
2037    }
2038
2039    /** @hide */
2040    public String getDeviceOwner() {
2041        if (mService != null) {
2042            try {
2043                return mService.getDeviceOwner();
2044            } catch (RemoteException re) {
2045                Log.w(TAG, "Failed to get device owner");
2046            }
2047        }
2048        return null;
2049    }
2050
2051    /** @hide */
2052    public String getDeviceOwnerName() {
2053        if (mService != null) {
2054            try {
2055                return mService.getDeviceOwnerName();
2056            } catch (RemoteException re) {
2057                Log.w(TAG, "Failed to get device owner");
2058            }
2059        }
2060        return null;
2061    }
2062
2063    /**
2064     * @hide
2065     * Sets the given package as the profile owner of the given user profile. The package must
2066     * already be installed and there shouldn't be an existing profile owner registered for this
2067     * user. Also, this method must be called before the user has been used for the first time.
2068     * @param packageName the package name of the application to be registered as profile owner.
2069     * @param ownerName the human readable name of the organisation associated with this DPM.
2070     * @param userHandle the userId to set the profile owner for.
2071     * @return whether the package was successfully registered as the profile owner.
2072     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
2073     *         the user has already been set up.
2074     */
2075    public boolean setProfileOwner(String packageName, String ownerName, int userHandle)
2076            throws IllegalArgumentException {
2077        if (mService != null) {
2078            try {
2079                return mService.setProfileOwner(packageName, ownerName, userHandle);
2080            } catch (RemoteException re) {
2081                Log.w(TAG, "Failed to set profile owner", re);
2082                throw new IllegalArgumentException("Couldn't set profile owner.", re);
2083            }
2084        }
2085        return false;
2086    }
2087
2088    /**
2089     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
2090     * be used. Only the profile owner can call this.
2091     *
2092     * @see #isProfileOwnerApp
2093     *
2094     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2095     */
2096    public void setProfileEnabled(ComponentName admin) {
2097        if (mService != null) {
2098            try {
2099                mService.setProfileEnabled(admin);
2100            } catch (RemoteException e) {
2101                Log.w(TAG, "Failed talking with device policy service", e);
2102            }
2103        }
2104    }
2105
2106    /**
2107     * Sets the name of the Managed profile. In the device owner case it sets the name of the user
2108     * which it is called from. Only the profile owner or device owner can call this. If this is
2109     * never called by the profile or device owner, the name will be set to default values.
2110     *
2111     * @see #isProfileOwnerApp
2112     * @see #isDeviceOwnerApp
2113     *
2114     * @param profileName The name of the profile.
2115     */
2116    public void setProfileName(ComponentName who, String profileName) {
2117        if (mService != null) {
2118            try {
2119            mService.setProfileName(who, profileName);
2120        } catch (RemoteException e) {
2121            Log.w(TAG, "Failed talking with device policy service", e);
2122        }
2123    }
2124}
2125
2126    /**
2127     * Used to determine if a particular package is registered as the Profile Owner for the
2128     * current user. A profile owner is a special device admin that has additional privileges
2129     * within the managed profile.
2130     *
2131     * @param packageName The package name of the app to compare with the registered profile owner.
2132     * @return Whether or not the package is registered as the profile owner.
2133     */
2134    public boolean isProfileOwnerApp(String packageName) {
2135        if (mService != null) {
2136            try {
2137                String profileOwnerPackage = mService.getProfileOwner(
2138                        Process.myUserHandle().getIdentifier());
2139                return profileOwnerPackage != null && profileOwnerPackage.equals(packageName);
2140            } catch (RemoteException re) {
2141                Log.w(TAG, "Failed to check profile owner");
2142            }
2143        }
2144        return false;
2145    }
2146
2147    /**
2148     * @hide
2149     * @return the packageName of the owner of the given user profile or null if no profile
2150     * owner has been set for that user.
2151     * @throws IllegalArgumentException if the userId is invalid.
2152     */
2153    public String getProfileOwner() throws IllegalArgumentException {
2154        if (mService != null) {
2155            try {
2156                return mService.getProfileOwner(Process.myUserHandle().getIdentifier());
2157            } catch (RemoteException re) {
2158                Log.w(TAG, "Failed to get profile owner");
2159                throw new IllegalArgumentException(
2160                        "Requested profile owner for invalid userId", re);
2161            }
2162        }
2163        return null;
2164    }
2165
2166    /**
2167     * @hide
2168     * @return the human readable name of the organisation associated with this DPM or null if
2169     *         one is not set.
2170     * @throws IllegalArgumentException if the userId is invalid.
2171     */
2172    public String getProfileOwnerName() throws IllegalArgumentException {
2173        if (mService != null) {
2174            try {
2175                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
2176            } catch (RemoteException re) {
2177                Log.w(TAG, "Failed to get profile owner");
2178                throw new IllegalArgumentException(
2179                        "Requested profile owner for invalid userId", re);
2180            }
2181        }
2182        return null;
2183    }
2184
2185    /**
2186     * Called by a profile owner or device owner to add a default intent handler activity for
2187     * intents that match a certain intent filter. This activity will remain the default intent
2188     * handler even if the set of potential event handlers for the intent filter changes and if
2189     * the intent preferences are reset.
2190     *
2191     * <p>The default disambiguation mechanism takes over if the activity is not installed
2192     * (anymore). When the activity is (re)installed, it is automatically reset as default
2193     * intent handler for the filter.
2194     *
2195     * <p>The calling device admin must be a profile owner or device owner. If it is not, a
2196     * security exception will be thrown.
2197     *
2198     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2199     * @param filter The IntentFilter for which a default handler is added.
2200     * @param activity The Activity that is added as default intent handler.
2201     */
2202    public void addPersistentPreferredActivity(ComponentName admin, IntentFilter filter,
2203            ComponentName activity) {
2204        if (mService != null) {
2205            try {
2206                mService.addPersistentPreferredActivity(admin, filter, activity);
2207            } catch (RemoteException e) {
2208                Log.w(TAG, "Failed talking with device policy service", e);
2209            }
2210        }
2211    }
2212
2213    /**
2214     * Called by a profile owner or device owner to remove all persistent intent handler preferences
2215     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
2216     *
2217     * <p>The calling device admin must be a profile owner. If it is not, a security
2218     * exception will be thrown.
2219     *
2220     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2221     * @param packageName The name of the package for which preferences are removed.
2222     */
2223    public void clearPackagePersistentPreferredActivities(ComponentName admin,
2224            String packageName) {
2225        if (mService != null) {
2226            try {
2227                mService.clearPackagePersistentPreferredActivities(admin, packageName);
2228            } catch (RemoteException e) {
2229                Log.w(TAG, "Failed talking with device policy service", e);
2230            }
2231        }
2232    }
2233
2234    /**
2235     * Called by a profile or device owner to set the application restrictions for a given target
2236     * application running in the managed profile.
2237     *
2238     * <p>The provided {@link Bundle} consists of key-value pairs, where the types of values may be
2239     * {@link Boolean}, {@link String}, or {@link String}[]. The recommended format for key strings
2240     * is "com.example.packagename/example-setting" to avoid naming conflicts with library
2241     * components such as {@link android.webkit.WebView}.
2242     *
2243     * <p>The application restrictions are only made visible to the target application and the
2244     * profile or device owner.
2245     *
2246     * <p>The calling device admin must be a profile or device owner; if it is not, a security
2247     * exception will be thrown.
2248     *
2249     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2250     * @param packageName The name of the package to update restricted settings for.
2251     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
2252     * set of active restrictions.
2253     */
2254    public void setApplicationRestrictions(ComponentName admin, String packageName,
2255            Bundle settings) {
2256        if (mService != null) {
2257            try {
2258                mService.setApplicationRestrictions(admin, packageName, settings);
2259            } catch (RemoteException e) {
2260                Log.w(TAG, "Failed talking with device policy service", e);
2261            }
2262        }
2263    }
2264
2265    /**
2266     * Called by the profile owner so that some intents sent in the managed profile can also be
2267     * resolved in the parent, or vice versa.
2268     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2269     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
2270     * other profile
2271     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
2272     * {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
2273     */
2274    public void addCrossProfileIntentFilter(ComponentName admin, IntentFilter filter, int flags) {
2275        if (mService != null) {
2276            try {
2277                mService.addCrossProfileIntentFilter(admin, filter, flags);
2278            } catch (RemoteException e) {
2279                Log.w(TAG, "Failed talking with device policy service", e);
2280            }
2281        }
2282    }
2283
2284    /**
2285     * Called by a profile owner to remove the cross-profile intent filters from the managed profile
2286     * and from the parent.
2287     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2288     */
2289    public void clearCrossProfileIntentFilters(ComponentName admin) {
2290        if (mService != null) {
2291            try {
2292                mService.clearCrossProfileIntentFilters(admin);
2293            } catch (RemoteException e) {
2294                Log.w(TAG, "Failed talking with device policy service", e);
2295            }
2296        }
2297    }
2298
2299    /**
2300     * Called by a device owner to create a user with the specified name. The UserHandle returned
2301     * by this method should not be persisted as user handles are recycled as users are removed and
2302     * created. If you need to persist an identifier for this user, use
2303     * {@link UserManager#getSerialNumberForUser}.
2304     *
2305     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2306     * @param name the user's name
2307     * @see UserHandle
2308     * @return the UserHandle object for the created user, or null if the user could not be created.
2309     */
2310    public UserHandle createUser(ComponentName admin, String name) {
2311        try {
2312            return mService.createUser(admin, name);
2313        } catch (RemoteException re) {
2314            Log.w(TAG, "Could not create a user", re);
2315        }
2316        return null;
2317    }
2318
2319    /**
2320     * Called by a device owner to create a user with the specified name. The UserHandle returned
2321     * by this method should not be persisted as user handles are recycled as users are removed and
2322     * created. If you need to persist an identifier for this user, use
2323     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
2324     * immediately.
2325     *
2326     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
2327     * as registered as an active admin on the new user.  The profile owner package will be
2328     * installed on the new user if it already is installed on the device.
2329     *
2330     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
2331     * profileOwnerComponent when onEnable is called.
2332     *
2333     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2334     * @param name the user's name
2335     * @param ownerName the human readable name of the organisation associated with this DPM.
2336     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
2337     *      the user.
2338     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
2339     *      on the new user.
2340     * @see UserHandle
2341     * @return the UserHandle object for the created user, or null if the user could not be created.
2342     */
2343    public UserHandle createAndInitializeUser(ComponentName admin, String name, String ownerName,
2344            ComponentName profileOwnerComponent, Bundle adminExtras) {
2345        try {
2346            return mService.createAndInitializeUser(admin, name, ownerName, profileOwnerComponent,
2347                    adminExtras);
2348        } catch (RemoteException re) {
2349            Log.w(TAG, "Could not create a user", re);
2350        }
2351        return null;
2352    }
2353
2354    /**
2355     * Called by a device owner to remove a user and all associated data. The primary user can
2356     * not be removed.
2357     *
2358     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2359     * @param userHandle the user to remove.
2360     * @return {@code true} if the user was removed, {@code false} otherwise.
2361     */
2362    public boolean removeUser(ComponentName admin, UserHandle userHandle) {
2363        try {
2364            return mService.removeUser(admin, userHandle);
2365        } catch (RemoteException re) {
2366            Log.w(TAG, "Could not remove user ", re);
2367            return false;
2368        }
2369    }
2370
2371    /**
2372     * Called by a profile or device owner to get the application restrictions for a given target
2373     * application running in the managed profile.
2374     *
2375     * <p>The calling device admin must be a profile or device owner; if it is not, a security
2376     * exception will be thrown.
2377     *
2378     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2379     * @param packageName The name of the package to fetch restricted settings of.
2380     * @return {@link Bundle} of settings corresponding to what was set last time
2381     * {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty {@link Bundle}
2382     * if no restrictions have been set.
2383     */
2384    public Bundle getApplicationRestrictions(ComponentName admin, String packageName) {
2385        if (mService != null) {
2386            try {
2387                return mService.getApplicationRestrictions(admin, packageName);
2388            } catch (RemoteException e) {
2389                Log.w(TAG, "Failed talking with device policy service", e);
2390            }
2391        }
2392        return null;
2393    }
2394
2395    /**
2396     * Called by a profile or device owner to set a user restriction specified
2397     * by the key.
2398     * <p>
2399     * The calling device admin must be a profile or device owner; if it is not,
2400     * a security exception will be thrown.
2401     *
2402     * @param admin Which {@link DeviceAdminReceiver} this request is associated
2403     *            with.
2404     * @param key The key of the restriction. See the constants in
2405     *            {@link android.os.UserManager} for the list of keys.
2406     */
2407    public void addUserRestriction(ComponentName admin, String key) {
2408        if (mService != null) {
2409            try {
2410                mService.setUserRestriction(admin, key, true);
2411            } catch (RemoteException e) {
2412                Log.w(TAG, "Failed talking with device policy service", e);
2413            }
2414        }
2415    }
2416
2417    /**
2418     * Called by a profile or device owner to clear a user restriction specified
2419     * by the key.
2420     * <p>
2421     * The calling device admin must be a profile or device owner; if it is not,
2422     * a security exception will be thrown.
2423     *
2424     * @param admin Which {@link DeviceAdminReceiver} this request is associated
2425     *            with.
2426     * @param key The key of the restriction. See the constants in
2427     *            {@link android.os.UserManager} for the list of keys.
2428     */
2429    public void clearUserRestriction(ComponentName admin, String key) {
2430        if (mService != null) {
2431            try {
2432                mService.setUserRestriction(admin, key, false);
2433            } catch (RemoteException e) {
2434                Log.w(TAG, "Failed talking with device policy service", e);
2435            }
2436        }
2437    }
2438
2439    /**
2440     * Called by device or profile owner to block or unblock packages. When a package is blocked it
2441     * is unavailable for use, but the data and actual package file remain.
2442     *
2443     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2444     * @param packageName The name of the package to block or unblock.
2445     * @param blocked {@code true} if the package should be blocked, {@code false} if it should be
2446     *                 unblocked.
2447     * @return boolean Whether the blocked setting of the package was successfully updated.
2448     */
2449    public boolean setApplicationBlocked(ComponentName admin, String packageName,
2450            boolean blocked) {
2451        if (mService != null) {
2452            try {
2453                return mService.setApplicationBlocked(admin, packageName, blocked);
2454            } catch (RemoteException e) {
2455                Log.w(TAG, "Failed talking with device policy service", e);
2456            }
2457        }
2458        return false;
2459    }
2460
2461    /**
2462     * Called by profile or device owner to block or unblock currently installed packages. This
2463     * should only be called by a profile or device owner running within a managed profile.
2464     *
2465     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2466     * @param intent An intent matching the app(s) to be updated. All apps that resolve for this
2467     *               intent will be updated in the current profile.
2468     * @param blocked {@code true} if the packages should be blocked, {@code false} if they should
2469     *                 be unblocked.
2470     * @return int The number of activities that matched the intent and were updated.
2471     */
2472    public int setApplicationsBlocked(ComponentName admin, Intent intent, boolean blocked) {
2473        if (mService != null) {
2474            try {
2475                return mService.setApplicationsBlocked(admin, intent, blocked);
2476            } catch (RemoteException e) {
2477                Log.w(TAG, "Failed talking with device policy service", e);
2478            }
2479        }
2480        return 0;
2481    }
2482
2483    /**
2484     * Called by device or profile owner to determine if a package is blocked.
2485     *
2486     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2487     * @param packageName The name of the package to retrieve the blocked status of.
2488     * @return boolean {@code true} if the package is blocked, {@code false} otherwise.
2489     */
2490    public boolean isApplicationBlocked(ComponentName admin, String packageName) {
2491        if (mService != null) {
2492            try {
2493                return mService.isApplicationBlocked(admin, packageName);
2494            } catch (RemoteException e) {
2495                Log.w(TAG, "Failed talking with device policy service", e);
2496            }
2497        }
2498        return false;
2499    }
2500
2501    /**
2502     * Called by a profile owner to disable account management for a specific type of account.
2503     *
2504     * <p>The calling device admin must be a profile owner. If it is not, a
2505     * security exception will be thrown.
2506     *
2507     * <p>When account management is disabled for an account type, adding or removing an account
2508     * of that type will not be possible.
2509     *
2510     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2511     * @param accountType For which account management is disabled or enabled.
2512     * @param disabled The boolean indicating that account management will be disabled (true) or
2513     * enabled (false).
2514     */
2515    public void setAccountManagementDisabled(ComponentName admin, String accountType,
2516            boolean disabled) {
2517        if (mService != null) {
2518            try {
2519                mService.setAccountManagementDisabled(admin, accountType, disabled);
2520            } catch (RemoteException e) {
2521                Log.w(TAG, "Failed talking with device policy service", e);
2522            }
2523        }
2524    }
2525
2526    /**
2527     * Gets the array of accounts for which account management is disabled by the profile owner.
2528     *
2529     * <p> Account management can be disabled/enabled by calling
2530     * {@link #setAccountManagementDisabled}.
2531     *
2532     * @return a list of account types for which account management has been disabled.
2533     *
2534     * @see #setAccountManagementDisabled
2535     */
2536    public String[] getAccountTypesWithManagementDisabled() {
2537        if (mService != null) {
2538            try {
2539                return mService.getAccountTypesWithManagementDisabled();
2540            } catch (RemoteException e) {
2541                Log.w(TAG, "Failed talking with device policy service", e);
2542            }
2543        }
2544
2545        return null;
2546    }
2547
2548    /**
2549     * Sets which packages may enter lock task mode.
2550     *
2551     * <p>Any packages that shares uid with an allowed package will also be allowed
2552     * to activate lock task.
2553     *
2554     * This function can only be called by the device owner.
2555     * @param packages The list of packages allowed to enter lock task mode
2556     *
2557     * @see Activity#startLockTask()
2558     */
2559    public void setLockTaskPackages(String[] packages) throws SecurityException {
2560        if (mService != null) {
2561            try {
2562                mService.setLockTaskPackages(packages);
2563            } catch (RemoteException e) {
2564                Log.w(TAG, "Failed talking with device policy service", e);
2565            }
2566        }
2567    }
2568
2569    /**
2570     * This function returns the list of packages allowed to start the lock task mode.
2571     * @hide
2572     */
2573    public String[] getLockTaskPackages() {
2574        if (mService != null) {
2575            try {
2576                return mService.getLockTaskPackages();
2577            } catch (RemoteException e) {
2578                Log.w(TAG, "Failed talking with device policy service", e);
2579            }
2580        }
2581        return null;
2582    }
2583
2584    /**
2585     * This function lets the caller know whether the given component is allowed to start the
2586     * lock task mode.
2587     * @param pkg The package to check
2588     */
2589    public boolean isLockTaskPermitted(String pkg) {
2590        if (mService != null) {
2591            try {
2592                return mService.isLockTaskPermitted(pkg);
2593            } catch (RemoteException e) {
2594                Log.w(TAG, "Failed talking with device policy service", e);
2595            }
2596        }
2597        return false;
2598    }
2599
2600    /**
2601     * Called by device owners to update {@link Settings.Global} settings. Validation that the value
2602     * of the setting is in the correct form for the setting type should be performed by the caller.
2603     *
2604     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2605     * @param setting The name of the setting to update.
2606     * @param value The value to update the setting to.
2607     */
2608    public void setGlobalSetting(ComponentName admin, String setting, String value) {
2609        if (mService != null) {
2610            try {
2611                mService.setGlobalSetting(admin, setting, value);
2612            } catch (RemoteException e) {
2613                Log.w(TAG, "Failed talking with device policy service", e);
2614            }
2615        }
2616    }
2617
2618    /**
2619     * Called by profile or device owners to update {@link Settings.Secure} settings. Validation
2620     * that the value of the setting is in the correct form for the setting type should be performed
2621     * by the caller.
2622     *
2623     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2624     * @param setting The name of the setting to update.
2625     * @param value The value to update the setting to.
2626     */
2627    public void setSecureSetting(ComponentName admin, String setting, String value) {
2628        if (mService != null) {
2629            try {
2630                mService.setSecureSetting(admin, setting, value);
2631            } catch (RemoteException e) {
2632                Log.w(TAG, "Failed talking with device policy service", e);
2633            }
2634        }
2635    }
2636
2637    /**
2638     * Designates a specific broadcast receiver component as the provider for
2639     * making permission requests of a local or remote administrator of the user.
2640     * <p/>
2641     * Only a profile owner can designate the restrictions provider.
2642     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2643     * @param receiver The component name of a BroadcastReceiver that handles the
2644     * {@link RestrictionsManager#ACTION_REQUEST_PERMISSION} intent. If this param is null,
2645     * it removes the restrictions provider previously assigned.
2646     */
2647    public void setRestrictionsProvider(ComponentName admin, ComponentName receiver) {
2648        if (mService != null) {
2649            try {
2650                mService.setRestrictionsProvider(admin, receiver);
2651            } catch (RemoteException re) {
2652                Log.w(TAG, "Failed to set permission provider on device policy service");
2653            }
2654        }
2655    }
2656
2657    /**
2658     * Called by profile or device owners to set the master volume mute on or off.
2659     *
2660     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2661     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
2662     */
2663    public void setMasterVolumeMuted(ComponentName admin, boolean on) {
2664        if (mService != null) {
2665            try {
2666                mService.setMasterVolumeMuted(admin, on);
2667            } catch (RemoteException re) {
2668                Log.w(TAG, "Failed to setMasterMute on device policy service");
2669            }
2670        }
2671    }
2672
2673    /**
2674     * Called by profile or device owners to check whether the master volume mute is on or off.
2675     *
2676     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2677     * @return {@code true} if master volume is muted, {@code false} if it's not.
2678     */
2679    public boolean isMasterVolumeMuted(ComponentName admin) {
2680        if (mService != null) {
2681            try {
2682                return mService.isMasterVolumeMuted(admin);
2683            } catch (RemoteException re) {
2684                Log.w(TAG, "Failed to get isMasterMute on device policy service");
2685            }
2686        }
2687        return false;
2688    }
2689}
2690