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