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