Home | History | Annotate | Download | only in admin
      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 
     17 package android.app.admin;
     18 
     19 import org.xmlpull.v1.XmlPullParserException;
     20 
     21 import android.annotation.SdkConstant;
     22 import android.annotation.SdkConstant.SdkConstantType;
     23 import android.content.ComponentName;
     24 import android.content.Context;
     25 import android.content.pm.ActivityInfo;
     26 import android.content.pm.PackageManager;
     27 import android.content.pm.ResolveInfo;
     28 import android.os.Handler;
     29 import android.os.RemoteCallback;
     30 import android.os.RemoteException;
     31 import android.os.ServiceManager;
     32 import android.os.UserHandle;
     33 import android.util.Log;
     34 
     35 import com.android.org.conscrypt.TrustedCertificateStore;
     36 
     37 import java.io.ByteArrayInputStream;
     38 import java.io.IOException;
     39 import java.net.InetSocketAddress;
     40 import java.net.Proxy;
     41 import java.security.cert.CertificateException;
     42 import java.security.cert.CertificateFactory;
     43 import java.security.cert.X509Certificate;
     44 import java.util.List;
     45 import java.util.Set;
     46 
     47 /**
     48  * Public interface for managing policies enforced on a device.  Most clients
     49  * of this class must have published a {@link DeviceAdminReceiver} that the user
     50  * has currently enabled.
     51  *
     52  * <div class="special reference">
     53  * <h3>Developer Guides</h3>
     54  * <p>For more information about managing policies for device adminstration, read the
     55  * <a href="{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a>
     56  * developer guide.</p>
     57  * </div>
     58  */
     59 public class DevicePolicyManager {
     60     private static String TAG = "DevicePolicyManager";
     61 
     62     private final Context mContext;
     63     private final IDevicePolicyManager mService;
     64 
     65     private DevicePolicyManager(Context context, Handler handler) {
     66         mContext = context;
     67         mService = IDevicePolicyManager.Stub.asInterface(
     68                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
     69     }
     70 
     71     /** @hide */
     72     public static DevicePolicyManager create(Context context, Handler handler) {
     73         DevicePolicyManager me = new DevicePolicyManager(context, handler);
     74         return me.mService != null ? me : null;
     75     }
     76 
     77     /**
     78      * Activity action: ask the user to add a new device administrator to the system.
     79      * The desired policy is the ComponentName of the policy in the
     80      * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
     81      * bring the user through adding the device administrator to the system (or
     82      * allowing them to reject it).
     83      *
     84      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
     85      * field to provide the user with additional explanation (in addition
     86      * to your component's description) about what is being added.
     87      *
     88      * <p>If your administrator is already active, this will ordinarily return immediately (without
     89      * user intervention).  However, if your administrator has been updated and is requesting
     90      * additional uses-policy flags, the user will be presented with the new list.  New policies
     91      * will not be available to the updated administrator until the user has accepted the new list.
     92      */
     93     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
     94     public static final String ACTION_ADD_DEVICE_ADMIN
     95             = "android.app.action.ADD_DEVICE_ADMIN";
     96 
     97     /**
     98      * Activity action: send when any policy admin changes a policy.
     99      * This is generally used to find out when a new policy is in effect.
    100      *
    101      * @hide
    102      */
    103     public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
    104             = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
    105 
    106     /**
    107      * The ComponentName of the administrator component.
    108      *
    109      * @see #ACTION_ADD_DEVICE_ADMIN
    110      */
    111     public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
    112 
    113     /**
    114      * An optional CharSequence providing additional explanation for why the
    115      * admin is being added.
    116      *
    117      * @see #ACTION_ADD_DEVICE_ADMIN
    118      */
    119     public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
    120 
    121     /**
    122      * Activity action: have the user enter a new password. This activity should
    123      * be launched after using {@link #setPasswordQuality(ComponentName, int)},
    124      * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
    125      * enter a new password that meets the current requirements. You can use
    126      * {@link #isActivePasswordSufficient()} to determine whether you need to
    127      * have the user select a new password in order to meet the current
    128      * constraints. Upon being resumed from this activity, you can check the new
    129      * password characteristics to see if they are sufficient.
    130      */
    131     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
    132     public static final String ACTION_SET_NEW_PASSWORD
    133             = "android.app.action.SET_NEW_PASSWORD";
    134 
    135     /**
    136      * Return true if the given administrator component is currently
    137      * active (enabled) in the system.
    138      */
    139     public boolean isAdminActive(ComponentName who) {
    140         if (mService != null) {
    141             try {
    142                 return mService.isAdminActive(who, UserHandle.myUserId());
    143             } catch (RemoteException e) {
    144                 Log.w(TAG, "Failed talking with device policy service", e);
    145             }
    146         }
    147         return false;
    148     }
    149 
    150     /**
    151      * Return a list of all currently active device administrator's component
    152      * names.  Note that if there are no administrators than null may be
    153      * returned.
    154      */
    155     public List<ComponentName> getActiveAdmins() {
    156         if (mService != null) {
    157             try {
    158                 return mService.getActiveAdmins(UserHandle.myUserId());
    159             } catch (RemoteException e) {
    160                 Log.w(TAG, "Failed talking with device policy service", e);
    161             }
    162         }
    163         return null;
    164     }
    165 
    166     /**
    167      * Used by package administration code to determine if a package can be stopped
    168      * or uninstalled.
    169      * @hide
    170      */
    171     public boolean packageHasActiveAdmins(String packageName) {
    172         if (mService != null) {
    173             try {
    174                 return mService.packageHasActiveAdmins(packageName, UserHandle.myUserId());
    175             } catch (RemoteException e) {
    176                 Log.w(TAG, "Failed talking with device policy service", e);
    177             }
    178         }
    179         return false;
    180     }
    181 
    182     /**
    183      * Remove a current administration component.  This can only be called
    184      * by the application that owns the administration component; if you
    185      * try to remove someone else's component, a security exception will be
    186      * thrown.
    187      */
    188     public void removeActiveAdmin(ComponentName who) {
    189         if (mService != null) {
    190             try {
    191                 mService.removeActiveAdmin(who, UserHandle.myUserId());
    192             } catch (RemoteException e) {
    193                 Log.w(TAG, "Failed talking with device policy service", e);
    194             }
    195         }
    196     }
    197 
    198     /**
    199      * Returns true if an administrator has been granted a particular device policy.  This can
    200      * be used to check if the administrator was activated under an earlier set of policies,
    201      * but requires additional policies after an upgrade.
    202      *
    203      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  Must be
    204      * an active administrator, or an exception will be thrown.
    205      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
    206      */
    207     public boolean hasGrantedPolicy(ComponentName admin, int usesPolicy) {
    208         if (mService != null) {
    209             try {
    210                 return mService.hasGrantedPolicy(admin, usesPolicy, UserHandle.myUserId());
    211             } catch (RemoteException e) {
    212                 Log.w(TAG, "Failed talking with device policy service", e);
    213             }
    214         }
    215         return false;
    216     }
    217 
    218     /**
    219      * Constant for {@link #setPasswordQuality}: the policy has no requirements
    220      * for the password.  Note that quality constants are ordered so that higher
    221      * values are more restrictive.
    222      */
    223     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
    224 
    225     /**
    226      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
    227      * recognition technology.  This implies technologies that can recognize the identity of
    228      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
    229      * Note that quality constants are ordered so that higher values are more restrictive.
    230      */
    231     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
    232 
    233     /**
    234      * Constant for {@link #setPasswordQuality}: the policy requires some kind
    235      * of password, but doesn't care what it is.  Note that quality constants
    236      * are ordered so that higher values are more restrictive.
    237      */
    238     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
    239 
    240     /**
    241      * Constant for {@link #setPasswordQuality}: the user must have entered a
    242      * password containing at least numeric characters.  Note that quality
    243      * constants are ordered so that higher values are more restrictive.
    244      */
    245     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
    246 
    247     /**
    248      * Constant for {@link #setPasswordQuality}: the user must have entered a
    249      * password containing at least alphabetic (or other symbol) characters.
    250      * Note that quality constants are ordered so that higher values are more
    251      * restrictive.
    252      */
    253     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
    254 
    255     /**
    256      * Constant for {@link #setPasswordQuality}: the user must have entered a
    257      * password containing at least <em>both></em> numeric <em>and</em>
    258      * alphabetic (or other symbol) characters.  Note that quality constants are
    259      * ordered so that higher values are more restrictive.
    260      */
    261     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
    262 
    263     /**
    264      * Constant for {@link #setPasswordQuality}: the user must have entered a
    265      * password containing at least a letter, a numerical digit and a special
    266      * symbol, by default. With this password quality, passwords can be
    267      * restricted to contain various sets of characters, like at least an
    268      * uppercase letter, etc. These are specified using various methods,
    269      * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
    270      * that quality constants are ordered so that higher values are more
    271      * restrictive.
    272      */
    273     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
    274 
    275     /**
    276      * Called by an application that is administering the device to set the
    277      * password restrictions it is imposing.  After setting this, the user
    278      * will not be able to enter a new password that is not at least as
    279      * restrictive as what has been set.  Note that the current password
    280      * will remain until the user has set a new one, so the change does not
    281      * take place immediately.  To prompt the user for a new password, use
    282      * {@link #ACTION_SET_NEW_PASSWORD} after setting this value.
    283      *
    284      * <p>Quality constants are ordered so that higher values are more restrictive;
    285      * thus the highest requested quality constant (between the policy set here,
    286      * the user's preference, and any other considerations) is the one that
    287      * is in effect.
    288      *
    289      * <p>The calling device admin must have requested
    290      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
    291      * this method; if it has not, a security exception will be thrown.
    292      *
    293      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
    294      * @param quality The new desired quality.  One of
    295      * {@link #PASSWORD_QUALITY_UNSPECIFIED}, {@link #PASSWORD_QUALITY_SOMETHING},
    296      * {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_ALPHABETIC},
    297      * {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
    298      */
    299     public void setPasswordQuality(ComponentName admin, int quality) {
    300         if (mService != null) {
    301             try {
    302                 mService.setPasswordQuality(admin, quality, UserHandle.myUserId());
    303             } catch (RemoteException e) {
    304                 Log.w(TAG, "Failed talking with device policy service", e);
    305             }
    306         }
    307     }
    308 
    309     /**
    310      * Retrieve the current minimum password quality for all admins
    311      * or a particular one.
    312      * @param admin The name of the admin component to check, or null to aggregate
    313      * all admins.
    314      */
    315     public int getPasswordQuality(ComponentName admin) {
    316         return getPasswordQuality(admin, UserHandle.myUserId());
    317     }
    318 
    319     /** @hide per-user version */
    320     public int getPasswordQuality(ComponentName admin, int userHandle) {
    321         if (mService != null) {
    322             try {
    323                 return mService.getPasswordQuality(admin, userHandle);
    324             } catch (RemoteException e) {
    325                 Log.w(TAG, "Failed talking with device policy service", e);
    326             }
    327         }
    328         return PASSWORD_QUALITY_UNSPECIFIED;
    329     }
    330 
    331     /**
    332      * Called by an application that is administering the device to set the
    333      * minimum allowed password length.  After setting this, the user
    334      * will not be able to enter a new password that is not at least as
    335      * restrictive as what has been set.  Note that the current password
    336      * will remain until the user has set a new one, so the change does not
    337      * take place immediately.  To prompt the user for a new password, use
    338      * {@link #ACTION_SET_NEW_PASSWORD} after setting this value.  This
    339      * constraint is only imposed if the administrator has also requested either
    340      * {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_ALPHABETIC}
    341      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX}
    342      * with {@link #setPasswordQuality}.
    343      *
    344      * <p>The calling device admin must have requested
    345      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
    346      * this method; if it has not, a security exception will be thrown.
    347      *
    348      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
    349      * @param length The new desired minimum password length.  A value of 0
    350      * means there is no restriction.
    351      */
    352     public void setPasswordMinimumLength(ComponentName admin, int length) {
    353         if (mService != null) {
    354             try {
    355                 mService.setPasswordMinimumLength(admin, length, UserHandle.myUserId());
    356             } catch (RemoteException e) {
    357                 Log.w(TAG, "Failed talking with device policy service", e);
    358             }
    359         }
    360     }
    361 
    362     /**
    363      * Retrieve the current minimum password length for all admins
    364      * or a particular one.
    365      * @param admin The name of the admin component to check, or null to aggregate
    366      * all admins.
    367      */
    368     public int getPasswordMinimumLength(ComponentName admin) {
    369         return getPasswordMinimumLength(admin, UserHandle.myUserId());
    370     }
    371 
    372     /** @hide per-user version */
    373     public int getPasswordMinimumLength(ComponentName admin, int userHandle) {
    374         if (mService != null) {
    375             try {
    376                 return mService.getPasswordMinimumLength(admin, userHandle);
    377             } catch (RemoteException e) {
    378                 Log.w(TAG, "Failed talking with device policy service", e);
    379             }
    380         }
    381         return 0;
    382     }
    383 
    384     /**
    385      * Called by an application that is administering the device to set the
    386      * minimum number of upper case letters required in the password. After
    387      * setting this, the user will not be able to enter a new password that is
    388      * not at least as restrictive as what has been set. Note that the current
    389      * password will remain until the user has set a new one, so the change does
    390      * not take place immediately. To prompt the user for a new password, use
    391      * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
    392      * constraint is only imposed if the administrator has also requested
    393      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
    394      * default value is 0.
    395      * <p>
    396      * The calling device admin must have requested
    397      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
    398      * this method; if it has not, a security exception will be thrown.
    399      *
    400      * @param admin Which {@link DeviceAdminReceiver} this request is associated
    401      *            with.
    402      * @param length The new desired minimum number of upper case letters
    403      *            required in the password. A value of 0 means there is no
    404      *            restriction.
    405      */
    406     public void setPasswordMinimumUpperCase(ComponentName admin, int length) {
    407         if (mService != null) {
    408             try {
    409                 mService.setPasswordMinimumUpperCase(admin, length, UserHandle.myUserId());
    410             } catch (RemoteException e) {
    411                 Log.w(TAG, "Failed talking with device policy service", e);
    412             }
    413         }
    414     }
    415 
    416     /**
    417      * Retrieve the current number of upper case letters required in the
    418      * password for all admins or a particular one. This is the same value as
    419      * set by {#link {@link #setPasswordMinimumUpperCase(ComponentName, int)}
    420      * and only applies when the password quality is
    421      * {@link #PASSWORD_QUALITY_COMPLEX}.
    422      *
    423      * @param admin The name of the admin component to check, or null to
    424      *            aggregate all admins.
    425      * @return The minimum number of upper case letters required in the
    426      *         password.
    427      */
    428     public int getPasswordMinimumUpperCase(ComponentName admin) {
    429         return getPasswordMinimumUpperCase(admin, UserHandle.myUserId());
    430     }
    431 
    432     /** @hide per-user version */
    433     public int getPasswordMinimumUpperCase(ComponentName admin, int userHandle) {
    434         if (mService != null) {
    435             try {
    436                 return mService.getPasswordMinimumUpperCase(admin, userHandle);
    437             } catch (RemoteException e) {
    438                 Log.w(TAG, "Failed talking with device policy service", e);
    439             }
    440         }
    441         return 0;
    442     }
    443 
    444     /**
    445      * Called by an application that is administering the device to set the
    446      * minimum number of lower case letters required in the password. After
    447      * setting this, the user will not be able to enter a new password that is
    448      * not at least as restrictive as what has been set. Note that the current
    449      * password will remain until the user has set a new one, so the change does
    450      * not take place immediately. To prompt the user for a new password, use
    451      * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
    452      * constraint is only imposed if the administrator has also requested
    453      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
    454      * default value is 0.
    455      * <p>
    456      * The calling device admin must have requested
    457      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
    458      * this method; if it has not, a security exception will be thrown.
    459      *
    460      * @param admin Which {@link DeviceAdminReceiver} this request is associated
    461      *            with.
    462      * @param length The new desired minimum number of lower case letters
    463      *            required in the password. A value of 0 means there is no
    464      *            restriction.
    465      */
    466     public void setPasswordMinimumLowerCase(ComponentName admin, int length) {
    467         if (mService != null) {
    468             try {
    469                 mService.setPasswordMinimumLowerCase(admin, length, UserHandle.myUserId());
    470             } catch (RemoteException e) {
    471                 Log.w(TAG, "Failed talking with device policy service", e);
    472             }
    473         }
    474     }
    475 
    476     /**
    477      * Retrieve the current number of lower case letters required in the
    478      * password for all admins or a particular one. This is the same value as
    479      * set by {#link {@link #setPasswordMinimumLowerCase(ComponentName, int)}
    480      * and only applies when the password quality is
    481      * {@link #PASSWORD_QUALITY_COMPLEX}.
    482      *
    483      * @param admin The name of the admin component to check, or null to
    484      *            aggregate all admins.
    485      * @return The minimum number of lower case letters required in the
    486      *         password.
    487      */
    488     public int getPasswordMinimumLowerCase(ComponentName admin) {
    489         return getPasswordMinimumLowerCase(admin, UserHandle.myUserId());
    490     }
    491 
    492     /** @hide per-user version */
    493     public int getPasswordMinimumLowerCase(ComponentName admin, int userHandle) {
    494         if (mService != null) {
    495             try {
    496                 return mService.getPasswordMinimumLowerCase(admin, userHandle);
    497             } catch (RemoteException e) {
    498                 Log.w(TAG, "Failed talking with device policy service", e);
    499             }
    500         }
    501         return 0;
    502     }
    503 
    504     /**
    505      * Called by an application that is administering the device to set the
    506      * minimum number of letters required in the password. After setting this,
    507      * the user will not be able to enter a new password that is not at least as
    508      * restrictive as what has been set. Note that the current password will
    509      * remain until the user has set a new one, so the change does not take
    510      * place immediately. To prompt the user for a new password, use
    511      * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
    512      * constraint is only imposed if the administrator has also requested
    513      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
    514      * default value is 1.
    515      * <p>
    516      * The calling device admin must have requested
    517      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
    518      * this method; if it has not, a security exception will be thrown.
    519      *
    520      * @param admin Which {@link DeviceAdminReceiver} this request is associated
    521      *            with.
    522      * @param length The new desired minimum number of letters required in the
    523      *            password. A value of 0 means there is no restriction.
    524      */
    525     public void setPasswordMinimumLetters(ComponentName admin, int length) {
    526         if (mService != null) {
    527             try {
    528                 mService.setPasswordMinimumLetters(admin, length, UserHandle.myUserId());
    529             } catch (RemoteException e) {
    530                 Log.w(TAG, "Failed talking with device policy service", e);
    531             }
    532         }
    533     }
    534 
    535     /**
    536      * Retrieve the current number of letters required in the password for all
    537      * admins or a particular one. This is the same value as
    538      * set by {#link {@link #setPasswordMinimumLetters(ComponentName, int)}
    539      * and only applies when the password quality is
    540      * {@link #PASSWORD_QUALITY_COMPLEX}.
    541      *
    542      * @param admin The name of the admin component to check, or null to
    543      *            aggregate all admins.
    544      * @return The minimum number of letters required in the password.
    545      */
    546     public int getPasswordMinimumLetters(ComponentName admin) {
    547         return getPasswordMinimumLetters(admin, UserHandle.myUserId());
    548     }
    549 
    550     /** @hide per-user version */
    551     public int getPasswordMinimumLetters(ComponentName admin, int userHandle) {
    552         if (mService != null) {
    553             try {
    554                 return mService.getPasswordMinimumLetters(admin, userHandle);
    555             } catch (RemoteException e) {
    556                 Log.w(TAG, "Failed talking with device policy service", e);
    557             }
    558         }
    559         return 0;
    560     }
    561 
    562     /**
    563      * Called by an application that is administering the device to set the
    564      * minimum number of numerical digits required in the password. After
    565      * setting this, the user will not be able to enter a new password that is
    566      * not at least as restrictive as what has been set. Note that the current
    567      * password will remain until the user has set a new one, so the change does
    568      * not take place immediately. To prompt the user for a new password, use
    569      * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
    570      * constraint is only imposed if the administrator has also requested
    571      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
    572      * default value is 1.
    573      * <p>
    574      * The calling device admin must have requested
    575      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
    576      * this method; if it has not, a security exception will be thrown.
    577      *
    578      * @param admin Which {@link DeviceAdminReceiver} this request is associated
    579      *            with.
    580      * @param length The new desired minimum number of numerical digits required
    581      *            in the password. A value of 0 means there is no restriction.
    582      */
    583     public void setPasswordMinimumNumeric(ComponentName admin, int length) {
    584         if (mService != null) {
    585             try {
    586                 mService.setPasswordMinimumNumeric(admin, length, UserHandle.myUserId());
    587             } catch (RemoteException e) {
    588                 Log.w(TAG, "Failed talking with device policy service", e);
    589             }
    590         }
    591     }
    592 
    593     /**
    594      * Retrieve the current number of numerical digits required in the password
    595      * for all admins or a particular one. This is the same value as
    596      * set by {#link {@link #setPasswordMinimumNumeric(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 numerical digits required in the password.
    603      */
    604     public int getPasswordMinimumNumeric(ComponentName admin) {
    605         return getPasswordMinimumNumeric(admin, UserHandle.myUserId());
    606     }
    607 
    608     /** @hide per-user version */
    609     public int getPasswordMinimumNumeric(ComponentName admin, int userHandle) {
    610         if (mService != null) {
    611             try {
    612                 return mService.getPasswordMinimumNumeric(admin, userHandle);
    613             } catch (RemoteException e) {
    614                 Log.w(TAG, "Failed talking with device policy service", e);
    615             }
    616         }
    617         return 0;
    618     }
    619 
    620     /**
    621      * Called by an application that is administering the device to set the
    622      * minimum number of symbols required in the password. After setting this,
    623      * the user will not be able to enter a new password that is not at least as
    624      * restrictive as what has been set. Note that the current password will
    625      * remain until the user has set a new one, so the change does not take
    626      * place immediately. To prompt the user for a new password, use
    627      * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
    628      * constraint is only imposed if the administrator has also requested
    629      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
    630      * default value is 1.
    631      * <p>
    632      * The calling device admin must have requested
    633      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
    634      * this method; if it has not, a security exception will be thrown.
    635      *
    636      * @param admin Which {@link DeviceAdminReceiver} this request is associated
    637      *            with.
    638      * @param length The new desired minimum number of symbols required in the
    639      *            password. A value of 0 means there is no restriction.
    640      */
    641     public void setPasswordMinimumSymbols(ComponentName admin, int length) {
    642         if (mService != null) {
    643             try {
    644                 mService.setPasswordMinimumSymbols(admin, length, UserHandle.myUserId());
    645             } catch (RemoteException e) {
    646                 Log.w(TAG, "Failed talking with device policy service", e);
    647             }
    648         }
    649     }
    650 
    651     /**
    652      * Retrieve the current number of symbols required in the password for all
    653      * admins or a particular one. This is the same value as
    654      * set by {#link {@link #setPasswordMinimumSymbols(ComponentName, int)}
    655      * and only applies when the password quality is
    656      * {@link #PASSWORD_QUALITY_COMPLEX}.
    657      *
    658      * @param admin The name of the admin component to check, or null to
    659      *            aggregate all admins.
    660      * @return The minimum number of symbols required in the password.
    661      */
    662     public int getPasswordMinimumSymbols(ComponentName admin) {
    663         return getPasswordMinimumSymbols(admin, UserHandle.myUserId());
    664     }
    665 
    666     /** @hide per-user version */
    667     public int getPasswordMinimumSymbols(ComponentName admin, int userHandle) {
    668         if (mService != null) {
    669             try {
    670                 return mService.getPasswordMinimumSymbols(admin, userHandle);
    671             } catch (RemoteException e) {
    672                 Log.w(TAG, "Failed talking with device policy service", e);
    673             }
    674         }
    675         return 0;
    676     }
    677 
    678     /**
    679      * Called by an application that is administering the device to set the
    680      * minimum number of non-letter characters (numerical digits or symbols)
    681      * required in the password. After setting this, the user will not be able
    682      * to enter a new password that is not at least as restrictive as what has
    683      * been set. Note that the current password will remain until the user has
    684      * set a new one, so the change does not take place immediately. To prompt
    685      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} after
    686      * setting this value. This constraint is only imposed if the administrator
    687      * has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
    688      * {@link #setPasswordQuality}. The default value is 0.
    689      * <p>
    690      * The calling device admin must have requested
    691      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
    692      * this method; if it has not, a security exception will be thrown.
    693      *
    694      * @param admin Which {@link DeviceAdminReceiver} this request is associated
    695      *            with.
    696      * @param length The new desired minimum number of letters required in the
    697      *            password. A value of 0 means there is no restriction.
    698      */
    699     public void setPasswordMinimumNonLetter(ComponentName admin, int length) {
    700         if (mService != null) {
    701             try {
    702                 mService.setPasswordMinimumNonLetter(admin, length, UserHandle.myUserId());
    703             } catch (RemoteException e) {
    704                 Log.w(TAG, "Failed talking with device policy service", e);
    705             }
    706         }
    707     }
    708 
    709     /**
    710      * Retrieve the current number of non-letter characters required in the
    711      * password for all admins or a particular one. This is the same value as
    712      * set by {#link {@link #setPasswordMinimumNonLetter(ComponentName, int)}
    713      * and only applies when the password quality is
    714      * {@link #PASSWORD_QUALITY_COMPLEX}.
    715      *
    716      * @param admin The name of the admin component to check, or null to
    717      *            aggregate all admins.
    718      * @return The minimum number of letters required in the password.
    719      */
    720     public int getPasswordMinimumNonLetter(ComponentName admin) {
    721         return getPasswordMinimumNonLetter(admin, UserHandle.myUserId());
    722     }
    723 
    724     /** @hide per-user version */
    725     public int getPasswordMinimumNonLetter(ComponentName admin, int userHandle) {
    726         if (mService != null) {
    727             try {
    728                 return mService.getPasswordMinimumNonLetter(admin, userHandle);
    729             } catch (RemoteException e) {
    730                 Log.w(TAG, "Failed talking with device policy service", e);
    731             }
    732         }
    733         return 0;
    734     }
    735 
    736   /**
    737    * Called by an application that is administering the device to set the length
    738    * of the password history. After setting this, the user will not be able to
    739    * enter a new password that is the same as any password in the history. Note
    740    * that the current password will remain until the user has set a new one, so
    741    * the change does not take place immediately. To prompt the user for a new
    742    * password, use {@link #ACTION_SET_NEW_PASSWORD} after setting this value.
    743    * This constraint is only imposed if the administrator has also requested
    744    * either {@link #PASSWORD_QUALITY_NUMERIC},
    745    * {@link #PASSWORD_QUALITY_ALPHABETIC}, or
    746    * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
    747    *
    748    * <p>
    749    * The calling device admin must have requested
    750    * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this
    751    * method; if it has not, a security exception will be thrown.
    752    *
    753    * @param admin Which {@link DeviceAdminReceiver} this request is associated
    754    *        with.
    755    * @param length The new desired length of password history. A value of 0
    756    *        means there is no restriction.
    757    */
    758     public void setPasswordHistoryLength(ComponentName admin, int length) {
    759         if (mService != null) {
    760             try {
    761                 mService.setPasswordHistoryLength(admin, length, UserHandle.myUserId());
    762             } catch (RemoteException e) {
    763                 Log.w(TAG, "Failed talking with device policy service", e);
    764             }
    765         }
    766     }
    767 
    768     /**
    769      * Called by a device admin to set the password expiration timeout. Calling this method
    770      * will restart the countdown for password expiration for the given admin, as will changing
    771      * the device password (for all admins).
    772      *
    773      * <p>The provided timeout is the time delta in ms and will be added to the current time.
    774      * For example, to have the password expire 5 days from now, timeout would be
    775      * 5 * 86400 * 1000 = 432000000 ms for timeout.
    776      *
    777      * <p>To disable password expiration, a value of 0 may be used for timeout.
    778      *
    779      * <p>The calling device admin must have requested
    780      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this
    781      * method; if it has not, a security exception will be thrown.
    782      *
    783      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
    784      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0
    785      *        means there is no restriction (unlimited).
    786      */
    787     public void setPasswordExpirationTimeout(ComponentName admin, long timeout) {
    788         if (mService != null) {
    789             try {
    790                 mService.setPasswordExpirationTimeout(admin, timeout, UserHandle.myUserId());
    791             } catch (RemoteException e) {
    792                 Log.w(TAG, "Failed talking with device policy service", e);
    793             }
    794         }
    795     }
    796 
    797     /**
    798      * Get the password expiration timeout for the given admin. The expiration timeout is the
    799      * recurring expiration timeout provided in the call to
    800      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
    801      * aggregate of all policy administrators if admin is null.
    802      *
    803      * @param admin The name of the admin component to check, or null to aggregate all admins.
    804      * @return The timeout for the given admin or the minimum of all timeouts
    805      */
    806     public long getPasswordExpirationTimeout(ComponentName admin) {
    807         if (mService != null) {
    808             try {
    809                 return mService.getPasswordExpirationTimeout(admin, UserHandle.myUserId());
    810             } catch (RemoteException e) {
    811                 Log.w(TAG, "Failed talking with device policy service", e);
    812             }
    813         }
    814         return 0;
    815     }
    816 
    817     /**
    818      * Get the current password expiration time for the given admin or an aggregate of
    819      * all admins if admin is null. If the password is expired, this will return the time since
    820      * the password expired as a negative number.  If admin is null, then a composite of all
    821      * expiration timeouts is returned - which will be the minimum of all timeouts.
    822      *
    823      * @param admin The name of the admin component to check, or null to aggregate all admins.
    824      * @return The password expiration time, in ms.
    825      */
    826     public long getPasswordExpiration(ComponentName admin) {
    827         if (mService != null) {
    828             try {
    829                 return mService.getPasswordExpiration(admin, UserHandle.myUserId());
    830             } catch (RemoteException e) {
    831                 Log.w(TAG, "Failed talking with device policy service", e);
    832             }
    833         }
    834         return 0;
    835     }
    836 
    837     /**
    838      * Retrieve the current password history length for all admins
    839      * or a particular one.
    840      * @param admin The name of the admin component to check, or null to aggregate
    841      * all admins.
    842      * @return The length of the password history
    843      */
    844     public int getPasswordHistoryLength(ComponentName admin) {
    845         return getPasswordHistoryLength(admin, UserHandle.myUserId());
    846     }
    847 
    848     /** @hide per-user version */
    849     public int getPasswordHistoryLength(ComponentName admin, int userHandle) {
    850         if (mService != null) {
    851             try {
    852                 return mService.getPasswordHistoryLength(admin, userHandle);
    853             } catch (RemoteException e) {
    854                 Log.w(TAG, "Failed talking with device policy service", e);
    855             }
    856         }
    857         return 0;
    858     }
    859 
    860     /**
    861      * Return the maximum password length that the device supports for a
    862      * particular password quality.
    863      * @param quality The quality being interrogated.
    864      * @return Returns the maximum length that the user can enter.
    865      */
    866     public int getPasswordMaximumLength(int quality) {
    867         // Kind-of arbitrary.
    868         return 16;
    869     }
    870 
    871     /**
    872      * Determine whether the current password the user has set is sufficient
    873      * to meet the policy requirements (quality, minimum length) that have been
    874      * requested.
    875      *
    876      * <p>The calling device admin must have requested
    877      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
    878      * this method; if it has not, a security exception will be thrown.
    879      *
    880      * @return Returns true if the password meets the current requirements,
    881      * else false.
    882      */
    883     public boolean isActivePasswordSufficient() {
    884         if (mService != null) {
    885             try {
    886                 return mService.isActivePasswordSufficient(UserHandle.myUserId());
    887             } catch (RemoteException e) {
    888                 Log.w(TAG, "Failed talking with device policy service", e);
    889             }
    890         }
    891         return false;
    892     }
    893 
    894     /**
    895      * Retrieve the number of times the user has failed at entering a
    896      * password since that last successful password entry.
    897      *
    898      * <p>The calling device admin must have requested
    899      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call
    900      * this method; if it has not, a security exception will be thrown.
    901      */
    902     public int getCurrentFailedPasswordAttempts() {
    903         if (mService != null) {
    904             try {
    905                 return mService.getCurrentFailedPasswordAttempts(UserHandle.myUserId());
    906             } catch (RemoteException e) {
    907                 Log.w(TAG, "Failed talking with device policy service", e);
    908             }
    909         }
    910         return -1;
    911     }
    912 
    913     /**
    914      * Setting this to a value greater than zero enables a built-in policy
    915      * that will perform a device wipe after too many incorrect
    916      * device-unlock passwords have been entered.  This built-in policy combines
    917      * watching for failed passwords and wiping the device, and requires
    918      * that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
    919      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
    920      *
    921      * <p>To implement any other policy (e.g. wiping data for a particular
    922      * application only, erasing or revoking credentials, or reporting the
    923      * failure to a server), you should implement
    924      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)}
    925      * instead.  Do not use this API, because if the maximum count is reached,
    926      * the device will be wiped immediately, and your callback will not be invoked.
    927      *
    928      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
    929      * @param num The number of failed password attempts at which point the
    930      * device will wipe its data.
    931      */
    932     public void setMaximumFailedPasswordsForWipe(ComponentName admin, int num) {
    933         if (mService != null) {
    934             try {
    935                 mService.setMaximumFailedPasswordsForWipe(admin, num, UserHandle.myUserId());
    936             } catch (RemoteException e) {
    937                 Log.w(TAG, "Failed talking with device policy service", e);
    938             }
    939         }
    940     }
    941 
    942     /**
    943      * Retrieve the current maximum number of login attempts that are allowed
    944      * before the device wipes itself, for all admins
    945      * or a particular one.
    946      * @param admin The name of the admin component to check, or null to aggregate
    947      * all admins.
    948      */
    949     public int getMaximumFailedPasswordsForWipe(ComponentName admin) {
    950         return getMaximumFailedPasswordsForWipe(admin, UserHandle.myUserId());
    951     }
    952 
    953     /** @hide per-user version */
    954     public int getMaximumFailedPasswordsForWipe(ComponentName admin, int userHandle) {
    955         if (mService != null) {
    956             try {
    957                 return mService.getMaximumFailedPasswordsForWipe(admin, userHandle);
    958             } catch (RemoteException e) {
    959                 Log.w(TAG, "Failed talking with device policy service", e);
    960             }
    961         }
    962         return 0;
    963     }
    964 
    965     /**
    966      * Flag for {@link #resetPassword}: don't allow other admins to change
    967      * the password again until the user has entered it.
    968      */
    969     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
    970 
    971     /**
    972      * Force a new device unlock password (the password needed to access the
    973      * entire device, not for individual accounts) on the user.  This takes
    974      * effect immediately.
    975      * The given password must be sufficient for the
    976      * current password quality and length constraints as returned by
    977      * {@link #getPasswordQuality(ComponentName)} and
    978      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet
    979      * these constraints, then it will be rejected and false returned.  Note
    980      * that the password may be a stronger quality (containing alphanumeric
    981      * characters when the requested quality is only numeric), in which case
    982      * the currently active quality will be increased to match.
    983      *
    984      * <p>The calling device admin must have requested
    985      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call
    986      * this method; if it has not, a security exception will be thrown.
    987      *
    988      * @param password The new password for the user.
    989      * @param flags May be 0 or {@link #RESET_PASSWORD_REQUIRE_ENTRY}.
    990      * @return Returns true if the password was applied, or false if it is
    991      * not acceptable for the current constraints.
    992      */
    993     public boolean resetPassword(String password, int flags) {
    994         if (mService != null) {
    995             try {
    996                 return mService.resetPassword(password, flags, UserHandle.myUserId());
    997             } catch (RemoteException e) {
    998                 Log.w(TAG, "Failed talking with device policy service", e);
    999             }
   1000         }
   1001         return false;
   1002     }
   1003 
   1004     /**
   1005      * Called by an application that is administering the device to set the
   1006      * maximum time for user activity until the device will lock.  This limits
   1007      * the length that the user can set.  It takes effect immediately.
   1008      *
   1009      * <p>The calling device admin must have requested
   1010      * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} to be able to call
   1011      * this method; if it has not, a security exception will be thrown.
   1012      *
   1013      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
   1014      * @param timeMs The new desired maximum time to lock in milliseconds.
   1015      * A value of 0 means there is no restriction.
   1016      */
   1017     public void setMaximumTimeToLock(ComponentName admin, long timeMs) {
   1018         if (mService != null) {
   1019             try {
   1020                 mService.setMaximumTimeToLock(admin, timeMs, UserHandle.myUserId());
   1021             } catch (RemoteException e) {
   1022                 Log.w(TAG, "Failed talking with device policy service", e);
   1023             }
   1024         }
   1025     }
   1026 
   1027     /**
   1028      * Retrieve the current maximum time to unlock for all admins
   1029      * or a particular one.
   1030      * @param admin The name of the admin component to check, or null to aggregate
   1031      * all admins.
   1032      */
   1033     public long getMaximumTimeToLock(ComponentName admin) {
   1034         return getMaximumTimeToLock(admin, UserHandle.myUserId());
   1035     }
   1036 
   1037     /** @hide per-user version */
   1038     public long getMaximumTimeToLock(ComponentName admin, int userHandle) {
   1039         if (mService != null) {
   1040             try {
   1041                 return mService.getMaximumTimeToLock(admin, userHandle);
   1042             } catch (RemoteException e) {
   1043                 Log.w(TAG, "Failed talking with device policy service", e);
   1044             }
   1045         }
   1046         return 0;
   1047     }
   1048 
   1049     /**
   1050      * Make the device lock immediately, as if the lock screen timeout has
   1051      * expired at the point of this call.
   1052      *
   1053      * <p>The calling device admin must have requested
   1054      * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} to be able to call
   1055      * this method; if it has not, a security exception will be thrown.
   1056      */
   1057     public void lockNow() {
   1058         if (mService != null) {
   1059             try {
   1060                 mService.lockNow();
   1061             } catch (RemoteException e) {
   1062                 Log.w(TAG, "Failed talking with device policy service", e);
   1063             }
   1064         }
   1065     }
   1066 
   1067     /**
   1068      * Flag for {@link #wipeData(int)}: also erase the device's external
   1069      * storage.
   1070      */
   1071     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
   1072 
   1073     /**
   1074      * Ask the user date be wiped.  This will cause the device to reboot,
   1075      * erasing all user data while next booting up.  External storage such
   1076      * as SD cards will be also erased if the flag {@link #WIPE_EXTERNAL_STORAGE}
   1077      * is set.
   1078      *
   1079      * <p>The calling device admin must have requested
   1080      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to be able to call
   1081      * this method; if it has not, a security exception will be thrown.
   1082      *
   1083      * @param flags Bit mask of additional options: currently 0 and
   1084      *              {@link #WIPE_EXTERNAL_STORAGE} are supported.
   1085      */
   1086     public void wipeData(int flags) {
   1087         if (mService != null) {
   1088             try {
   1089                 mService.wipeData(flags, UserHandle.myUserId());
   1090             } catch (RemoteException e) {
   1091                 Log.w(TAG, "Failed talking with device policy service", e);
   1092             }
   1093         }
   1094     }
   1095 
   1096     /**
   1097      * Called by an application that is administering the device to set the
   1098      * global proxy and exclusion list.
   1099      * <p>
   1100      * The calling device admin must have requested
   1101      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
   1102      * this method; if it has not, a security exception will be thrown.
   1103      * Only the first device admin can set the proxy. If a second admin attempts
   1104      * to set the proxy, the {@link ComponentName} of the admin originally setting the
   1105      * proxy will be returned. If successful in setting the proxy, null will
   1106      * be returned.
   1107      * The method can be called repeatedly by the device admin alrady setting the
   1108      * proxy to update the proxy and exclusion list.
   1109      *
   1110      * @param admin Which {@link DeviceAdminReceiver} this request is associated
   1111      *            with.
   1112      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
   1113      *            Pass Proxy.NO_PROXY to reset the proxy.
   1114      * @param exclusionList a list of domains to be excluded from the global proxy.
   1115      * @return returns null if the proxy was successfully set, or a {@link ComponentName}
   1116      *            of the device admin that sets thew proxy otherwise.
   1117      * @hide
   1118      */
   1119     public ComponentName setGlobalProxy(ComponentName admin, Proxy proxySpec,
   1120             List<String> exclusionList ) {
   1121         if (proxySpec == null) {
   1122             throw new NullPointerException();
   1123         }
   1124         if (mService != null) {
   1125             try {
   1126                 String hostSpec;
   1127                 String exclSpec;
   1128                 if (proxySpec.equals(Proxy.NO_PROXY)) {
   1129                     hostSpec = null;
   1130                     exclSpec = null;
   1131                 } else {
   1132                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
   1133                         throw new IllegalArgumentException();
   1134                     }
   1135                     InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
   1136                     String hostName = sa.getHostName();
   1137                     int port = sa.getPort();
   1138                     StringBuilder hostBuilder = new StringBuilder();
   1139                     hostSpec = hostBuilder.append(hostName)
   1140                         .append(":").append(Integer.toString(port)).toString();
   1141                     if (exclusionList == null) {
   1142                         exclSpec = "";
   1143                     } else {
   1144                         StringBuilder listBuilder = new StringBuilder();
   1145                         boolean firstDomain = true;
   1146                         for (String exclDomain : exclusionList) {
   1147                             if (!firstDomain) {
   1148                                 listBuilder = listBuilder.append(",");
   1149                             } else {
   1150                                 firstDomain = false;
   1151                             }
   1152                             listBuilder = listBuilder.append(exclDomain.trim());
   1153                         }
   1154                         exclSpec = listBuilder.toString();
   1155                     }
   1156                     android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec);
   1157                 }
   1158                 return mService.setGlobalProxy(admin, hostSpec, exclSpec, UserHandle.myUserId());
   1159             } catch (RemoteException e) {
   1160                 Log.w(TAG, "Failed talking with device policy service", e);
   1161             }
   1162         }
   1163         return null;
   1164     }
   1165 
   1166     /**
   1167      * Returns the component name setting the global proxy.
   1168      * @return ComponentName object of the device admin that set the global proxy, or
   1169      *            null if no admin has set the proxy.
   1170      * @hide
   1171      */
   1172     public ComponentName getGlobalProxyAdmin() {
   1173         if (mService != null) {
   1174             try {
   1175                 return mService.getGlobalProxyAdmin(UserHandle.myUserId());
   1176             } catch (RemoteException e) {
   1177                 Log.w(TAG, "Failed talking with device policy service", e);
   1178             }
   1179         }
   1180         return null;
   1181     }
   1182 
   1183     /**
   1184      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
   1185      * indicating that encryption is not supported.
   1186      */
   1187     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
   1188 
   1189     /**
   1190      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
   1191      * indicating that encryption is supported, but is not currently active.
   1192      */
   1193     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
   1194 
   1195     /**
   1196      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
   1197      * indicating that encryption is not currently active, but is currently
   1198      * being activated.  This is only reported by devices that support
   1199      * encryption of data and only when the storage is currently
   1200      * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
   1201      * to become encrypted will never return this value.
   1202      */
   1203     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
   1204 
   1205     /**
   1206      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
   1207      * indicating that encryption is active.
   1208      */
   1209     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
   1210 
   1211     /**
   1212      * Activity action: begin the process of encrypting data on the device.  This activity should
   1213      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
   1214      * After resuming from this activity, use {@link #getStorageEncryption}
   1215      * to check encryption status.  However, on some devices this activity may never return, as
   1216      * it may trigger a reboot and in some cases a complete data wipe of the device.
   1217      */
   1218     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
   1219     public static final String ACTION_START_ENCRYPTION
   1220             = "android.app.action.START_ENCRYPTION";
   1221 
   1222     /**
   1223      * Widgets are enabled in keyguard
   1224      */
   1225     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
   1226 
   1227     /**
   1228      * Disable all keyguard widgets
   1229      */
   1230     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
   1231 
   1232     /**
   1233      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
   1234      */
   1235     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
   1236 
   1237     /**
   1238      * Disable all current and future keyguard customizations.
   1239      */
   1240     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
   1241 
   1242     /**
   1243      * Called by an application that is administering the device to
   1244      * request that the storage system be encrypted.
   1245      *
   1246      * <p>When multiple device administrators attempt to control device
   1247      * encryption, the most secure, supported setting will always be
   1248      * used.  If any device administrator requests device encryption,
   1249      * it will be enabled;  Conversely, if a device administrator
   1250      * attempts to disable device encryption while another
   1251      * device administrator has enabled it, the call to disable will
   1252      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
   1253      *
   1254      * <p>This policy controls encryption of the secure (application data) storage area.  Data
   1255      * written to other storage areas may or may not be encrypted, and this policy does not require
   1256      * or control the encryption of any other storage areas.
   1257      * There is one exception:  If {@link android.os.Environment#isExternalStorageEmulated()} is
   1258      * {@code true}, then the directory returned by
   1259      * {@link android.os.Environment#getExternalStorageDirectory()} must be written to disk
   1260      * within the encrypted storage area.
   1261      *
   1262      * <p>Important Note:  On some devices, it is possible to encrypt storage without requiring
   1263      * the user to create a device PIN or Password.  In this case, the storage is encrypted, but
   1264      * the encryption key may not be fully secured.  For maximum security, the administrator should
   1265      * also require (and check for) a pattern, PIN, or password.
   1266      *
   1267      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
   1268      * @param encrypt true to request encryption, false to release any previous request
   1269      * @return the new request status (for all active admins) - will be one of
   1270      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, or
   1271      * {@link #ENCRYPTION_STATUS_ACTIVE}.  This is the value of the requests;  Use
   1272      * {@link #getStorageEncryptionStatus()} to query the actual device state.
   1273      */
   1274     public int setStorageEncryption(ComponentName admin, boolean encrypt) {
   1275         if (mService != null) {
   1276             try {
   1277                 return mService.setStorageEncryption(admin, encrypt, UserHandle.myUserId());
   1278             } catch (RemoteException e) {
   1279                 Log.w(TAG, "Failed talking with device policy service", e);
   1280             }
   1281         }
   1282         return ENCRYPTION_STATUS_UNSUPPORTED;
   1283     }
   1284 
   1285     /**
   1286      * Called by an application that is administering the device to
   1287      * determine the requested setting for secure storage.
   1288      *
   1289      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
   1290      * this will return the requested encryption setting as an aggregate of all active
   1291      * administrators.
   1292      * @return true if the admin(s) are requesting encryption, false if not.
   1293      */
   1294     public boolean getStorageEncryption(ComponentName admin) {
   1295         if (mService != null) {
   1296             try {
   1297                 return mService.getStorageEncryption(admin, UserHandle.myUserId());
   1298             } catch (RemoteException e) {
   1299                 Log.w(TAG, "Failed talking with device policy service", e);
   1300             }
   1301         }
   1302         return false;
   1303     }
   1304 
   1305     /**
   1306      * Called by an application that is administering the device to
   1307      * determine the current encryption status of the device.
   1308      *
   1309      * Depending on the returned status code, the caller may proceed in different
   1310      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
   1311      * storage system does not support encryption.  If the
   1312      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
   1313      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
   1314      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING} or
   1315      * {@link #ENCRYPTION_STATUS_ACTIVE}, no further action is required.
   1316      *
   1317      * @return current status of encryption.  The value will be one of
   1318      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
   1319      * {@link #ENCRYPTION_STATUS_ACTIVATING}, or{@link #ENCRYPTION_STATUS_ACTIVE}.
   1320      */
   1321     public int getStorageEncryptionStatus() {
   1322         return getStorageEncryptionStatus(UserHandle.myUserId());
   1323     }
   1324 
   1325     /** @hide per-user version */
   1326     public int getStorageEncryptionStatus(int userHandle) {
   1327         if (mService != null) {
   1328             try {
   1329                 return mService.getStorageEncryptionStatus(userHandle);
   1330             } catch (RemoteException e) {
   1331                 Log.w(TAG, "Failed talking with device policy service", e);
   1332             }
   1333         }
   1334         return ENCRYPTION_STATUS_UNSUPPORTED;
   1335     }
   1336 
   1337     /**
   1338      * Installs the given certificate as a User CA.
   1339      *
   1340      * @return false if the certBuffer cannot be parsed or installation is
   1341      *         interrupted, otherwise true
   1342      * @hide
   1343      */
   1344     public boolean installCaCert(byte[] certBuffer) {
   1345         if (mService != null) {
   1346             try {
   1347                 return mService.installCaCert(certBuffer);
   1348             } catch (RemoteException e) {
   1349                 Log.w(TAG, "Failed talking with device policy service", e);
   1350             }
   1351         }
   1352         return false;
   1353     }
   1354 
   1355     /**
   1356      * Uninstalls the given certificate from the list of User CAs, if present.
   1357      *
   1358      * @hide
   1359      */
   1360     public void uninstallCaCert(byte[] certBuffer) {
   1361         if (mService != null) {
   1362             try {
   1363                 mService.uninstallCaCert(certBuffer);
   1364             } catch (RemoteException e) {
   1365                 Log.w(TAG, "Failed talking with device policy service", e);
   1366             }
   1367         }
   1368     }
   1369 
   1370     /**
   1371      * Returns whether there are any user-installed CA certificates.
   1372      *
   1373      * @hide
   1374      */
   1375     public static boolean hasAnyCaCertsInstalled() {
   1376         TrustedCertificateStore certStore = new TrustedCertificateStore();
   1377         Set<String> aliases = certStore.userAliases();
   1378         return aliases != null && !aliases.isEmpty();
   1379     }
   1380 
   1381     /**
   1382      * Returns whether this certificate has been installed as a User CA.
   1383      *
   1384      * @hide
   1385      */
   1386     public boolean hasCaCertInstalled(byte[] certBuffer) {
   1387         TrustedCertificateStore certStore = new TrustedCertificateStore();
   1388         String alias;
   1389         byte[] pemCert;
   1390         try {
   1391             CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
   1392             X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
   1393                             new ByteArrayInputStream(certBuffer));
   1394             return certStore.getCertificateAlias(cert) != null;
   1395         } catch (CertificateException ce) {
   1396             Log.w(TAG, "Could not parse certificate", ce);
   1397         }
   1398         return false;
   1399     }
   1400 
   1401     /**
   1402      * Called by an application that is administering the device to disable all cameras
   1403      * on the device.  After setting this, no applications will be able to access any cameras
   1404      * on the device.
   1405      *
   1406      * <p>The calling device admin must have requested
   1407      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call
   1408      * this method; if it has not, a security exception will be thrown.
   1409      *
   1410      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
   1411      * @param disabled Whether or not the camera should be disabled.
   1412      */
   1413     public void setCameraDisabled(ComponentName admin, boolean disabled) {
   1414         if (mService != null) {
   1415             try {
   1416                 mService.setCameraDisabled(admin, disabled, UserHandle.myUserId());
   1417             } catch (RemoteException e) {
   1418                 Log.w(TAG, "Failed talking with device policy service", e);
   1419             }
   1420         }
   1421     }
   1422 
   1423     /**
   1424      * Determine whether or not the device's cameras have been disabled either by the current
   1425      * admin, if specified, or all admins.
   1426      * @param admin The name of the admin component to check, or null to check if any admins
   1427      * have disabled the camera
   1428      */
   1429     public boolean getCameraDisabled(ComponentName admin) {
   1430         return getCameraDisabled(admin, UserHandle.myUserId());
   1431     }
   1432 
   1433     /** @hide per-user version */
   1434     public boolean getCameraDisabled(ComponentName admin, int userHandle) {
   1435         if (mService != null) {
   1436             try {
   1437                 return mService.getCameraDisabled(admin, userHandle);
   1438             } catch (RemoteException e) {
   1439                 Log.w(TAG, "Failed talking with device policy service", e);
   1440             }
   1441         }
   1442         return false;
   1443     }
   1444 
   1445     /**
   1446      * Called by an application that is administering the device to disable keyguard customizations,
   1447      * such as widgets. After setting this, keyguard features will be disabled according to the
   1448      * provided feature list.
   1449      *
   1450      * <p>The calling device admin must have requested
   1451      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call
   1452      * this method; if it has not, a security exception will be thrown.
   1453      *
   1454      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
   1455      * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
   1456      * {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
   1457      * {@link #KEYGUARD_DISABLE_FEATURES_ALL}
   1458      */
   1459     public void setKeyguardDisabledFeatures(ComponentName admin, int which) {
   1460         if (mService != null) {
   1461             try {
   1462                 mService.setKeyguardDisabledFeatures(admin, which, UserHandle.myUserId());
   1463             } catch (RemoteException e) {
   1464                 Log.w(TAG, "Failed talking with device policy service", e);
   1465             }
   1466         }
   1467     }
   1468 
   1469     /**
   1470      * Determine whether or not features have been disabled in keyguard either by the current
   1471      * admin, if specified, or all admins.
   1472      * @param admin The name of the admin component to check, or null to check if any admins
   1473      * have disabled features in keyguard.
   1474      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
   1475      * for a list.
   1476      */
   1477     public int getKeyguardDisabledFeatures(ComponentName admin) {
   1478         return getKeyguardDisabledFeatures(admin, UserHandle.myUserId());
   1479     }
   1480 
   1481     /** @hide per-user version */
   1482     public int getKeyguardDisabledFeatures(ComponentName admin, int userHandle) {
   1483         if (mService != null) {
   1484             try {
   1485                 return mService.getKeyguardDisabledFeatures(admin, userHandle);
   1486             } catch (RemoteException e) {
   1487                 Log.w(TAG, "Failed talking with device policy service", e);
   1488             }
   1489         }
   1490         return KEYGUARD_DISABLE_FEATURES_NONE;
   1491     }
   1492 
   1493     /**
   1494      * @hide
   1495      */
   1496     public void setActiveAdmin(ComponentName policyReceiver, boolean refreshing) {
   1497         if (mService != null) {
   1498             try {
   1499                 mService.setActiveAdmin(policyReceiver, refreshing, UserHandle.myUserId());
   1500             } catch (RemoteException e) {
   1501                 Log.w(TAG, "Failed talking with device policy service", e);
   1502             }
   1503         }
   1504     }
   1505 
   1506     /**
   1507      * Returns the DeviceAdminInfo as defined by the administrator's package info & meta-data
   1508      * @hide
   1509      */
   1510     public DeviceAdminInfo getAdminInfo(ComponentName cn) {
   1511         ActivityInfo ai;
   1512         try {
   1513             ai = mContext.getPackageManager().getReceiverInfo(cn,
   1514                     PackageManager.GET_META_DATA);
   1515         } catch (PackageManager.NameNotFoundException e) {
   1516             Log.w(TAG, "Unable to retrieve device policy " + cn, e);
   1517             return null;
   1518         }
   1519 
   1520         ResolveInfo ri = new ResolveInfo();
   1521         ri.activityInfo = ai;
   1522 
   1523         try {
   1524             return new DeviceAdminInfo(mContext, ri);
   1525         } catch (XmlPullParserException e) {
   1526             Log.w(TAG, "Unable to parse device policy " + cn, e);
   1527             return null;
   1528         } catch (IOException e) {
   1529             Log.w(TAG, "Unable to parse device policy " + cn, e);
   1530             return null;
   1531         }
   1532     }
   1533 
   1534     /**
   1535      * @hide
   1536      */
   1537     public void getRemoveWarning(ComponentName admin, RemoteCallback result) {
   1538         if (mService != null) {
   1539             try {
   1540                 mService.getRemoveWarning(admin, result, UserHandle.myUserId());
   1541             } catch (RemoteException e) {
   1542                 Log.w(TAG, "Failed talking with device policy service", e);
   1543             }
   1544         }
   1545     }
   1546 
   1547     /**
   1548      * @hide
   1549      */
   1550     public void setActivePasswordState(int quality, int length, int letters, int uppercase,
   1551             int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
   1552         if (mService != null) {
   1553             try {
   1554                 mService.setActivePasswordState(quality, length, letters, uppercase, lowercase,
   1555                         numbers, symbols, nonletter, userHandle);
   1556             } catch (RemoteException e) {
   1557                 Log.w(TAG, "Failed talking with device policy service", e);
   1558             }
   1559         }
   1560     }
   1561 
   1562     /**
   1563      * @hide
   1564      */
   1565     public void reportFailedPasswordAttempt(int userHandle) {
   1566         if (mService != null) {
   1567             try {
   1568                 mService.reportFailedPasswordAttempt(userHandle);
   1569             } catch (RemoteException e) {
   1570                 Log.w(TAG, "Failed talking with device policy service", e);
   1571             }
   1572         }
   1573     }
   1574 
   1575     /**
   1576      * @hide
   1577      */
   1578     public void reportSuccessfulPasswordAttempt(int userHandle) {
   1579         if (mService != null) {
   1580             try {
   1581                 mService.reportSuccessfulPasswordAttempt(userHandle);
   1582             } catch (RemoteException e) {
   1583                 Log.w(TAG, "Failed talking with device policy service", e);
   1584             }
   1585         }
   1586     }
   1587 
   1588     /**
   1589      * @hide
   1590      * Sets the given package as the device owner. The package must already be installed and there
   1591      * shouldn't be an existing device owner registered, for this call to succeed. Also, this
   1592      * method must be called before the device is provisioned.
   1593      * @param packageName the package name of the application to be registered as the device owner.
   1594      * @return whether the package was successfully registered as the device owner.
   1595      * @throws IllegalArgumentException if the package name is null or invalid
   1596      * @throws IllegalStateException if a device owner is already registered or the device has
   1597      *         already been provisioned.
   1598      */
   1599     public boolean setDeviceOwner(String packageName) throws IllegalArgumentException,
   1600             IllegalStateException {
   1601         return setDeviceOwner(packageName, null);
   1602     }
   1603 
   1604     /**
   1605      * @hide
   1606      * Sets the given package as the device owner. The package must already be installed and there
   1607      * shouldn't be an existing device owner registered, for this call to succeed. Also, this
   1608      * method must be called before the device is provisioned.
   1609      * @param packageName the package name of the application to be registered as the device owner.
   1610      * @param ownerName the human readable name of the institution that owns this device.
   1611      * @return whether the package was successfully registered as the device owner.
   1612      * @throws IllegalArgumentException if the package name is null or invalid
   1613      * @throws IllegalStateException if a device owner is already registered or the device has
   1614      *         already been provisioned.
   1615      */
   1616     public boolean setDeviceOwner(String packageName, String ownerName)
   1617             throws IllegalArgumentException, IllegalStateException {
   1618         if (mService != null) {
   1619             try {
   1620                 return mService.setDeviceOwner(packageName, ownerName);
   1621             } catch (RemoteException re) {
   1622                 Log.w(TAG, "Failed to set device owner");
   1623             }
   1624         }
   1625         return false;
   1626     }
   1627 
   1628 
   1629     /**
   1630      * Used to determine if a particular package has been registered as a Device Owner app.
   1631      * A device owner app is a special device admin that cannot be deactivated by the user, once
   1632      * activated as a device admin. It also cannot be uninstalled. To check if a particular
   1633      * package is currently registered as the device owner app, pass in the package name from
   1634      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
   1635      * admin apps that want to check if they are also registered as the device owner app. The
   1636      * exact mechanism by which a device admin app is registered as a device owner app is defined by
   1637      * the setup process.
   1638      * @param packageName the package name of the app, to compare with the registered device owner
   1639      * app, if any.
   1640      * @return whether or not the package is registered as the device owner app.
   1641      */
   1642     public boolean isDeviceOwnerApp(String packageName) {
   1643         if (mService != null) {
   1644             try {
   1645                 return mService.isDeviceOwner(packageName);
   1646             } catch (RemoteException re) {
   1647                 Log.w(TAG, "Failed to check device owner");
   1648             }
   1649         }
   1650         return false;
   1651     }
   1652 
   1653     /**
   1654      * @hide
   1655      * Redirect to isDeviceOwnerApp.
   1656      */
   1657     public boolean isDeviceOwner(String packageName) {
   1658         return isDeviceOwnerApp(packageName);
   1659     }
   1660 
   1661     /** @hide */
   1662     public String getDeviceOwner() {
   1663         if (mService != null) {
   1664             try {
   1665                 return mService.getDeviceOwner();
   1666             } catch (RemoteException re) {
   1667                 Log.w(TAG, "Failed to get device owner");
   1668             }
   1669         }
   1670         return null;
   1671     }
   1672 
   1673     /** @hide */
   1674     public String getDeviceOwnerName() {
   1675         if (mService != null) {
   1676             try {
   1677                 return mService.getDeviceOwnerName();
   1678             } catch (RemoteException re) {
   1679                 Log.w(TAG, "Failed to get device owner");
   1680             }
   1681         }
   1682         return null;
   1683     }
   1684 }
   1685