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