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