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