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