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