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