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