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