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