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