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