DevicePolicyManager.java revision 9797880808320e3a7bae1f59bc7e0c5a13189e5f
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     * Can not be called from a managed profile.
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.  After setting this, no applications will be able to access any cameras
1891     * 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 either by the current
1912     * 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     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2022     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
2023     * {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
2024     * {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}, {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
2025     * {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
2026     */
2027    public void setKeyguardDisabledFeatures(ComponentName admin, int which) {
2028        if (mService != null) {
2029            try {
2030                mService.setKeyguardDisabledFeatures(admin, which, UserHandle.myUserId());
2031            } catch (RemoteException e) {
2032                Log.w(TAG, "Failed talking with device policy service", e);
2033            }
2034        }
2035    }
2036
2037    /**
2038     * Determine whether or not features have been disabled in keyguard either by the current
2039     * admin, if specified, or all admins.
2040     * @param admin The name of the admin component to check, or null to check if any admins
2041     * have disabled features in keyguard.
2042     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
2043     * for a list.
2044     */
2045    public int getKeyguardDisabledFeatures(ComponentName admin) {
2046        return getKeyguardDisabledFeatures(admin, UserHandle.myUserId());
2047    }
2048
2049    /** @hide per-user version */
2050    public int getKeyguardDisabledFeatures(ComponentName admin, int userHandle) {
2051        if (mService != null) {
2052            try {
2053                return mService.getKeyguardDisabledFeatures(admin, userHandle);
2054            } catch (RemoteException e) {
2055                Log.w(TAG, "Failed talking with device policy service", e);
2056            }
2057        }
2058        return KEYGUARD_DISABLE_FEATURES_NONE;
2059    }
2060
2061    /**
2062     * @hide
2063     */
2064    public void setActiveAdmin(ComponentName policyReceiver, boolean refreshing, int userHandle) {
2065        if (mService != null) {
2066            try {
2067                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
2068            } catch (RemoteException e) {
2069                Log.w(TAG, "Failed talking with device policy service", e);
2070            }
2071        }
2072    }
2073
2074    /**
2075     * @hide
2076     */
2077    public void setActiveAdmin(ComponentName policyReceiver, boolean refreshing) {
2078        setActiveAdmin(policyReceiver, refreshing, UserHandle.myUserId());
2079    }
2080
2081    /**
2082     * Returns the DeviceAdminInfo as defined by the administrator's package info & meta-data
2083     * @hide
2084     */
2085    public DeviceAdminInfo getAdminInfo(ComponentName cn) {
2086        ActivityInfo ai;
2087        try {
2088            ai = mContext.getPackageManager().getReceiverInfo(cn,
2089                    PackageManager.GET_META_DATA);
2090        } catch (PackageManager.NameNotFoundException e) {
2091            Log.w(TAG, "Unable to retrieve device policy " + cn, e);
2092            return null;
2093        }
2094
2095        ResolveInfo ri = new ResolveInfo();
2096        ri.activityInfo = ai;
2097
2098        try {
2099            return new DeviceAdminInfo(mContext, ri);
2100        } catch (XmlPullParserException e) {
2101            Log.w(TAG, "Unable to parse device policy " + cn, e);
2102            return null;
2103        } catch (IOException e) {
2104            Log.w(TAG, "Unable to parse device policy " + cn, e);
2105            return null;
2106        }
2107    }
2108
2109    /**
2110     * @hide
2111     */
2112    public void getRemoveWarning(ComponentName admin, RemoteCallback result) {
2113        if (mService != null) {
2114            try {
2115                mService.getRemoveWarning(admin, result, UserHandle.myUserId());
2116            } catch (RemoteException e) {
2117                Log.w(TAG, "Failed talking with device policy service", e);
2118            }
2119        }
2120    }
2121
2122    /**
2123     * @hide
2124     */
2125    public void setActivePasswordState(int quality, int length, int letters, int uppercase,
2126            int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
2127        if (mService != null) {
2128            try {
2129                mService.setActivePasswordState(quality, length, letters, uppercase, lowercase,
2130                        numbers, symbols, nonletter, userHandle);
2131            } catch (RemoteException e) {
2132                Log.w(TAG, "Failed talking with device policy service", e);
2133            }
2134        }
2135    }
2136
2137    /**
2138     * @hide
2139     */
2140    public void reportFailedPasswordAttempt(int userHandle) {
2141        if (mService != null) {
2142            try {
2143                mService.reportFailedPasswordAttempt(userHandle);
2144            } catch (RemoteException e) {
2145                Log.w(TAG, "Failed talking with device policy service", e);
2146            }
2147        }
2148    }
2149
2150    /**
2151     * @hide
2152     */
2153    public void reportSuccessfulPasswordAttempt(int userHandle) {
2154        if (mService != null) {
2155            try {
2156                mService.reportSuccessfulPasswordAttempt(userHandle);
2157            } catch (RemoteException e) {
2158                Log.w(TAG, "Failed talking with device policy service", e);
2159            }
2160        }
2161    }
2162
2163    /**
2164     * @hide
2165     * Sets the given package as the device owner. The package must already be installed and there
2166     * shouldn't be an existing device owner registered, for this call to succeed. Also, this
2167     * method must be called before the device is provisioned.
2168     * @param packageName the package name of the application to be registered as the device owner.
2169     * @return whether the package was successfully registered as the device owner.
2170     * @throws IllegalArgumentException if the package name is null or invalid
2171     * @throws IllegalStateException if a device owner is already registered or the device has
2172     *         already been provisioned.
2173     */
2174    public boolean setDeviceOwner(String packageName) throws IllegalArgumentException,
2175            IllegalStateException {
2176        return setDeviceOwner(packageName, null);
2177    }
2178
2179    /**
2180     * @hide
2181     * Sets the given package as the device owner. The package must already be installed and there
2182     * shouldn't be an existing device owner registered, for this call to succeed. Also, this
2183     * method must be called before the device is provisioned.
2184     * @param packageName the package name of the application to be registered as the device owner.
2185     * @param ownerName the human readable name of the institution that owns this device.
2186     * @return whether the package was successfully registered as the device owner.
2187     * @throws IllegalArgumentException if the package name is null or invalid
2188     * @throws IllegalStateException if a device owner is already registered or the device has
2189     *         already been provisioned.
2190     */
2191    public boolean setDeviceOwner(String packageName, String ownerName)
2192            throws IllegalArgumentException, IllegalStateException {
2193        if (mService != null) {
2194            try {
2195                return mService.setDeviceOwner(packageName, ownerName);
2196            } catch (RemoteException re) {
2197                Log.w(TAG, "Failed to set device owner");
2198            }
2199        }
2200        return false;
2201    }
2202
2203    /**
2204     * Used to determine if a particular package has been registered as a Device Owner app.
2205     * A device owner app is a special device admin that cannot be deactivated by the user, once
2206     * activated as a device admin. It also cannot be uninstalled. To check if a particular
2207     * package is currently registered as the device owner app, pass in the package name from
2208     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
2209     * admin apps that want to check if they are also registered as the device owner app. The
2210     * exact mechanism by which a device admin app is registered as a device owner app is defined by
2211     * the setup process.
2212     * @param packageName the package name of the app, to compare with the registered device owner
2213     * app, if any.
2214     * @return whether or not the package is registered as the device owner app.
2215     */
2216    public boolean isDeviceOwnerApp(String packageName) {
2217        if (mService != null) {
2218            try {
2219                return mService.isDeviceOwner(packageName);
2220            } catch (RemoteException re) {
2221                Log.w(TAG, "Failed to check device owner");
2222            }
2223        }
2224        return false;
2225    }
2226
2227    /**
2228     * @hide
2229     * Redirect to isDeviceOwnerApp.
2230     */
2231    public boolean isDeviceOwner(String packageName) {
2232        return isDeviceOwnerApp(packageName);
2233    }
2234
2235    /**
2236     * Clears the current device owner.  The caller must be the device owner.
2237     *
2238     * This function should be used cautiously as once it is called it cannot
2239     * be undone.  The device owner can only be set as a part of device setup
2240     * before setup completes.
2241     *
2242     * @param packageName The package name of the device owner.
2243     */
2244    public void clearDeviceOwnerApp(String packageName) {
2245        if (mService != null) {
2246            try {
2247                mService.clearDeviceOwner(packageName);
2248            } catch (RemoteException re) {
2249                Log.w(TAG, "Failed to clear device owner");
2250            }
2251        }
2252    }
2253
2254    /** @hide */
2255    @SystemApi
2256    public String getDeviceOwner() {
2257        if (mService != null) {
2258            try {
2259                return mService.getDeviceOwner();
2260            } catch (RemoteException re) {
2261                Log.w(TAG, "Failed to get device owner");
2262            }
2263        }
2264        return null;
2265    }
2266
2267    /** @hide */
2268    public String getDeviceOwnerName() {
2269        if (mService != null) {
2270            try {
2271                return mService.getDeviceOwnerName();
2272            } catch (RemoteException re) {
2273                Log.w(TAG, "Failed to get device owner");
2274            }
2275        }
2276        return null;
2277    }
2278
2279    /**
2280     * @hide
2281     * @deprecated Use #ACTION_SET_PROFILE_OWNER
2282     * Sets the given component as an active admin and registers the package as the profile
2283     * owner for this user. The package must already be installed and there shouldn't be
2284     * an existing profile owner registered for this user. Also, this method must be called
2285     * before the user setup has been completed.
2286     * <p>
2287     * This method can only be called by system apps that hold MANAGE_USERS permission and
2288     * MANAGE_DEVICE_ADMINS permission.
2289     * @param admin The component to register as an active admin and profile owner.
2290     * @param ownerName The user-visible name of the entity that is managing this user.
2291     * @return whether the admin was successfully registered as the profile owner.
2292     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
2293     *         the user has already been set up.
2294     */
2295    @SystemApi
2296    public boolean setActiveProfileOwner(ComponentName admin, String ownerName)
2297            throws IllegalArgumentException {
2298        if (mService != null) {
2299            try {
2300                final int myUserId = UserHandle.myUserId();
2301                mService.setActiveAdmin(admin, false, myUserId);
2302                return mService.setProfileOwner(admin, ownerName, myUserId);
2303            } catch (RemoteException re) {
2304                Log.w(TAG, "Failed to set profile owner " + re);
2305                throw new IllegalArgumentException("Couldn't set profile owner.", re);
2306            }
2307        }
2308        return false;
2309    }
2310
2311    /**
2312     * @hide
2313     * Clears the active profile owner and removes all user restrictions. The caller must
2314     * be from the same package as the active profile owner for this user, otherwise a
2315     * SecurityException will be thrown.
2316     *
2317     * @param admin The component to remove as the profile owner.
2318     * @return
2319     */
2320    @SystemApi
2321    public void clearProfileOwner(ComponentName admin) {
2322        if (mService != null) {
2323            try {
2324                mService.clearProfileOwner(admin);
2325            } catch (RemoteException re) {
2326                Log.w(TAG, "Failed to clear profile owner " + admin + re);
2327            }
2328        }
2329    }
2330
2331    /**
2332     * @hide
2333     * Checks if the user was already setup.
2334     */
2335    public boolean hasUserSetupCompleted() {
2336        if (mService != null) {
2337            try {
2338                return mService.hasUserSetupCompleted();
2339            } catch (RemoteException re) {
2340                Log.w(TAG, "Failed to check if user setup has completed");
2341            }
2342        }
2343        return true;
2344    }
2345
2346    /**
2347     * @deprecated Use setProfileOwner(ComponentName ...)
2348     * @hide
2349     * Sets the given package as the profile owner of the given user profile. The package must
2350     * already be installed and there shouldn't be an existing profile owner registered for this
2351     * user. Also, this method must be called before the user has been used for the first time.
2352     * @param packageName the package name of the application to be registered as profile owner.
2353     * @param ownerName the human readable name of the organisation associated with this DPM.
2354     * @param userHandle the userId to set the profile owner for.
2355     * @return whether the package was successfully registered as the profile owner.
2356     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
2357     *         the user has already been set up.
2358     */
2359    public boolean setProfileOwner(String packageName, String ownerName, int userHandle)
2360            throws IllegalArgumentException {
2361        if (packageName == null) {
2362            throw new NullPointerException("packageName cannot be null");
2363        }
2364        return setProfileOwner(new ComponentName(packageName, ""), ownerName, userHandle);
2365    }
2366
2367    /**
2368     * @hide
2369     * Sets the given component as the profile owner of the given user profile. The package must
2370     * already be installed and there shouldn't be an existing profile owner registered for this
2371     * user. Only the system can call this API if the user has already completed setup.
2372     * @param admin the component name to be registered as profile owner.
2373     * @param ownerName the human readable name of the organisation associated with this DPM.
2374     * @param userHandle the userId to set the profile owner for.
2375     * @return whether the component was successfully registered as the profile owner.
2376     * @throws IllegalArgumentException if admin is null, the package isn't installed, or
2377     *         the user has already been set up.
2378     */
2379    public boolean setProfileOwner(ComponentName admin, String ownerName, int userHandle)
2380            throws IllegalArgumentException {
2381        if (admin == null) {
2382            throw new NullPointerException("admin cannot be null");
2383        }
2384        if (mService != null) {
2385            try {
2386                if (ownerName == null) {
2387                    ownerName = "";
2388                }
2389                return mService.setProfileOwner(admin, ownerName, userHandle);
2390            } catch (RemoteException re) {
2391                Log.w(TAG, "Failed to set profile owner", re);
2392                throw new IllegalArgumentException("Couldn't set profile owner.", re);
2393            }
2394        }
2395        return false;
2396    }
2397
2398    /**
2399     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
2400     * be used. Only the profile owner can call this.
2401     *
2402     * @see #isProfileOwnerApp
2403     *
2404     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2405     */
2406    public void setProfileEnabled(ComponentName admin) {
2407        if (mService != null) {
2408            try {
2409                mService.setProfileEnabled(admin);
2410            } catch (RemoteException e) {
2411                Log.w(TAG, "Failed talking with device policy service", e);
2412            }
2413        }
2414    }
2415
2416    /**
2417     * Sets the name of the profile. In the device owner case it sets the name of the user
2418     * which it is called from. Only a profile owner or device owner can call this. If this is
2419     * never called by the profile or device owner, the name will be set to default values.
2420     *
2421     * @see #isProfileOwnerApp
2422     * @see #isDeviceOwnerApp
2423     *
2424     * @param profileName The name of the profile.
2425     */
2426    public void setProfileName(ComponentName who, String profileName) {
2427        if (mService != null) {
2428            try {
2429            mService.setProfileName(who, profileName);
2430        } catch (RemoteException e) {
2431            Log.w(TAG, "Failed talking with device policy service", e);
2432        }
2433    }
2434}
2435
2436    /**
2437     * Used to determine if a particular package is registered as the profile owner for the
2438     * current user. A profile owner is a special device admin that has additional privileges
2439     * within the profile.
2440     *
2441     * @param packageName The package name of the app to compare with the registered profile owner.
2442     * @return Whether or not the package is registered as the profile owner.
2443     */
2444    public boolean isProfileOwnerApp(String packageName) {
2445        if (mService != null) {
2446            try {
2447                ComponentName profileOwner = mService.getProfileOwner(
2448                        Process.myUserHandle().getIdentifier());
2449                return profileOwner != null
2450                        && profileOwner.getPackageName().equals(packageName);
2451            } catch (RemoteException re) {
2452                Log.w(TAG, "Failed to check profile owner");
2453            }
2454        }
2455        return false;
2456    }
2457
2458    /**
2459     * @hide
2460     * @return the packageName of the owner of the given user profile or null if no profile
2461     * owner has been set for that user.
2462     * @throws IllegalArgumentException if the userId is invalid.
2463     */
2464    @SystemApi
2465    public ComponentName getProfileOwner() throws IllegalArgumentException {
2466        return getProfileOwnerAsUser(Process.myUserHandle().getIdentifier());
2467    }
2468
2469    /**
2470     * @see #getProfileOwner()
2471     * @hide
2472     */
2473    public ComponentName getProfileOwnerAsUser(final int userId) throws IllegalArgumentException {
2474        if (mService != null) {
2475            try {
2476                return mService.getProfileOwner(userId);
2477            } catch (RemoteException re) {
2478                Log.w(TAG, "Failed to get profile owner");
2479                throw new IllegalArgumentException(
2480                        "Requested profile owner for invalid userId", re);
2481            }
2482        }
2483        return null;
2484    }
2485
2486    /**
2487     * @hide
2488     * @return the human readable name of the organisation associated with this DPM or null if
2489     *         one is not set.
2490     * @throws IllegalArgumentException if the userId is invalid.
2491     */
2492    public String getProfileOwnerName() throws IllegalArgumentException {
2493        if (mService != null) {
2494            try {
2495                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
2496            } catch (RemoteException re) {
2497                Log.w(TAG, "Failed to get profile owner");
2498                throw new IllegalArgumentException(
2499                        "Requested profile owner for invalid userId", re);
2500            }
2501        }
2502        return null;
2503    }
2504
2505    /**
2506     * @hide
2507     * @param user The user for whom to fetch the profile owner name, if any.
2508     * @return the human readable name of the organisation associated with this profile owner or
2509     *         null if one is not set.
2510     * @throws IllegalArgumentException if the userId is invalid.
2511     */
2512    @SystemApi
2513    public String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
2514        if (mService != null) {
2515            try {
2516                return mService.getProfileOwnerName(userId);
2517            } catch (RemoteException re) {
2518                Log.w(TAG, "Failed to get profile owner");
2519                throw new IllegalArgumentException(
2520                        "Requested profile owner for invalid userId", re);
2521            }
2522        }
2523        return null;
2524    }
2525
2526    /**
2527     * Called by a profile owner or device owner to add a default intent handler activity for
2528     * intents that match a certain intent filter. This activity will remain the default intent
2529     * handler even if the set of potential event handlers for the intent filter changes and if
2530     * the intent preferences are reset.
2531     *
2532     * <p>The default disambiguation mechanism takes over if the activity is not installed
2533     * (anymore). When the activity is (re)installed, it is automatically reset as default
2534     * intent handler for the filter.
2535     *
2536     * <p>The calling device admin must be a profile owner or device owner. If it is not, a
2537     * security exception will be thrown.
2538     *
2539     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2540     * @param filter The IntentFilter for which a default handler is added.
2541     * @param activity The Activity that is added as default intent handler.
2542     */
2543    public void addPersistentPreferredActivity(ComponentName admin, IntentFilter filter,
2544            ComponentName activity) {
2545        if (mService != null) {
2546            try {
2547                mService.addPersistentPreferredActivity(admin, filter, activity);
2548            } catch (RemoteException e) {
2549                Log.w(TAG, "Failed talking with device policy service", e);
2550            }
2551        }
2552    }
2553
2554    /**
2555     * Called by a profile owner or device owner to remove all persistent intent handler preferences
2556     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
2557     *
2558     * <p>The calling device admin must be a profile owner. If it is not, a security
2559     * exception will be thrown.
2560     *
2561     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2562     * @param packageName The name of the package for which preferences are removed.
2563     */
2564    public void clearPackagePersistentPreferredActivities(ComponentName admin,
2565            String packageName) {
2566        if (mService != null) {
2567            try {
2568                mService.clearPackagePersistentPreferredActivities(admin, packageName);
2569            } catch (RemoteException e) {
2570                Log.w(TAG, "Failed talking with device policy service", e);
2571            }
2572        }
2573    }
2574
2575    /**
2576     * Called by a profile or device owner to set the application restrictions for a given target
2577     * application running in the profile.
2578     *
2579     * <p>The provided {@link Bundle} consists of key-value pairs, where the types of values may be
2580     * boolean, int, String, or String[].
2581     *
2582     * <p>The application restrictions are only made visible to the target application and the
2583     * profile or device owner.
2584     *
2585     * <p>The calling device admin must be a profile or device owner; if it is not, a security
2586     * exception will be thrown.
2587     *
2588     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2589     * @param packageName The name of the package to update restricted settings for.
2590     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
2591     * set of active restrictions.
2592     */
2593    public void setApplicationRestrictions(ComponentName admin, String packageName,
2594            Bundle settings) {
2595        if (mService != null) {
2596            try {
2597                mService.setApplicationRestrictions(admin, packageName, settings);
2598            } catch (RemoteException e) {
2599                Log.w(TAG, "Failed talking with device policy service", e);
2600            }
2601        }
2602    }
2603
2604    /**
2605     * Sets a list of features to enable for a TrustAgent component. This is meant to be
2606     * used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which will disable all
2607     * trust agents but those with features enabled by this function call.
2608     *
2609     * <p>The calling device admin must have requested
2610     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call
2611     * this method; if it has not, a security exception will be thrown.
2612     *
2613     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2614     * @param agent Which component to enable features for.
2615     * @param features List of features to enable. Consult specific TrustAgent documentation for
2616     * the feature list.
2617     * @hide
2618     */
2619    public void setTrustAgentFeaturesEnabled(ComponentName admin, ComponentName agent,
2620            List<String> features) {
2621        if (mService != null) {
2622            try {
2623                mService.setTrustAgentFeaturesEnabled(admin, agent, features, UserHandle.myUserId());
2624            } catch (RemoteException e) {
2625                Log.w(TAG, "Failed talking with device policy service", e);
2626            }
2627        }
2628    }
2629
2630    /**
2631     * Gets list of enabled features for the given TrustAgent component. If admin is
2632     * null, this will return the intersection of all features enabled for the given agent by all
2633     * admins.
2634     *
2635     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2636     * @param agent Which component to get enabled features for.
2637     * @return List of enabled features.
2638     * @hide
2639     */
2640    public List<String> getTrustAgentFeaturesEnabled(ComponentName admin, ComponentName agent) {
2641        if (mService != null) {
2642            try {
2643                return mService.getTrustAgentFeaturesEnabled(admin, agent, UserHandle.myUserId());
2644            } catch (RemoteException e) {
2645                Log.w(TAG, "Failed talking with device policy service", e);
2646            }
2647        }
2648        return new ArrayList<String>(); // empty list
2649    }
2650
2651    /**
2652     * Called by a profile owner of a managed profile to set whether caller-Id information from
2653     * the managed profile will be shown in the parent profile, for incoming calls.
2654     *
2655     * <p>The calling device admin must be a profile owner. If it is not, a
2656     * security exception will be thrown.
2657     *
2658     * @param who Which {@link DeviceAdminReceiver} this request is associated with.
2659     * @param disabled If true caller-Id information in the managed profile is not displayed.
2660     */
2661    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
2662        if (mService != null) {
2663            try {
2664                mService.setCrossProfileCallerIdDisabled(who, disabled);
2665            } catch (RemoteException e) {
2666                Log.w(TAG, "Failed talking with device policy service", e);
2667            }
2668        }
2669    }
2670
2671    /**
2672     * Called by a profile owner of a managed profile to determine whether or not caller-Id
2673     * information has been disabled.
2674     *
2675     * <p>The calling device admin must be a profile owner. If it is not, a
2676     * security exception will be thrown.
2677     *
2678     * @param who Which {@link DeviceAdminReceiver} this request is associated with.
2679     */
2680    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
2681        if (mService != null) {
2682            try {
2683                return mService.getCrossProfileCallerIdDisabled(who);
2684            } catch (RemoteException e) {
2685                Log.w(TAG, "Failed talking with device policy service", e);
2686            }
2687        }
2688        return false;
2689    }
2690
2691    /**
2692     * Determine whether or not caller-Id information has been disabled.
2693     *
2694     * @param userHandle The user for whom to check the caller-id permission
2695     * @hide
2696     */
2697    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
2698        if (mService != null) {
2699            try {
2700                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
2701            } catch (RemoteException e) {
2702                Log.w(TAG, "Failed talking with device policy service", e);
2703            }
2704        }
2705        return false;
2706    }
2707
2708    /**
2709     * Called by the profile owner of a managed profile so that some intents sent in the managed
2710     * profile can also be resolved in the parent, or vice versa.
2711     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2712     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
2713     * other profile
2714     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
2715     * {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
2716     */
2717    public void addCrossProfileIntentFilter(ComponentName admin, IntentFilter filter, int flags) {
2718        if (mService != null) {
2719            try {
2720                mService.addCrossProfileIntentFilter(admin, filter, flags);
2721            } catch (RemoteException e) {
2722                Log.w(TAG, "Failed talking with device policy service", e);
2723            }
2724        }
2725    }
2726
2727    /**
2728     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
2729     * that go from the managed profile to the parent, or from the parent to the managed profile.
2730     * Only removes those that have been set by the profile owner.
2731     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2732     */
2733    public void clearCrossProfileIntentFilters(ComponentName admin) {
2734        if (mService != null) {
2735            try {
2736                mService.clearCrossProfileIntentFilters(admin);
2737            } catch (RemoteException e) {
2738                Log.w(TAG, "Failed talking with device policy service", e);
2739            }
2740        }
2741    }
2742
2743    /**
2744     * Called by a profile or device owner to set the permitted accessibility services. When
2745     * set by a device owner or profile owner the restriction applies to all profiles of the
2746     * user the device owner or profile owner is an admin for.
2747     *
2748     * By default the user can use any accessiblity service. When zero or more packages have
2749     * been added, accessiblity services that are not in the list and not part of the system
2750     * can not be enabled by the user.
2751     *
2752     * <p> Calling with a null value for the list disables the restriction so that all services
2753     * can be used, calling with an empty list only allows the builtin system's services.
2754     *
2755     * <p> System accesibility services are always available to the user the list can't modify
2756     * this.
2757     *
2758     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2759     * @param packageNames List of accessibility service package names.
2760     *
2761     * @return true if setting the restriction succeeded. It fail if there is
2762     * one or more non-system accessibility services enabled, that are not in the list.
2763     */
2764    public boolean setPermittedAccessibilityServices(ComponentName admin,
2765            List<String> packageNames) {
2766        if (mService != null) {
2767            try {
2768                return mService.setPermittedAccessibilityServices(admin, packageNames);
2769            } catch (RemoteException e) {
2770                Log.w(TAG, "Failed talking with device policy service", e);
2771            }
2772        }
2773        return false;
2774    }
2775
2776    /**
2777     * Returns the list of permitted accessibility services set by this device or profile owner.
2778     *
2779     * <p>An empty list means no accessibility services except system services are allowed.
2780     * Null means all accessibility services are allowed.
2781     *
2782     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2783     * @return List of accessiblity service package names.
2784     */
2785    public List<String> getPermittedAccessibilityServices(ComponentName admin) {
2786        if (mService != null) {
2787            try {
2788                return mService.getPermittedAccessibilityServices(admin);
2789            } catch (RemoteException e) {
2790                Log.w(TAG, "Failed talking with device policy service", e);
2791            }
2792        }
2793        return null;
2794    }
2795
2796    /**
2797     * Returns the list of accessibility services permitted by the device or profiles
2798     * owners of this user.
2799     *
2800     * <p>Null means all accessibility services are allowed, if a non-null list is returned
2801     * it will contain the intersection of the permitted lists for any device or profile
2802     * owners that apply to this user. It will also include any system accessibility services.
2803     *
2804     * @param userId which user to check for.
2805     * @return List of accessiblity service package names.
2806     * @hide
2807     */
2808     @SystemApi
2809     public List<String> getPermittedAccessibilityServices(int userId) {
2810        if (mService != null) {
2811            try {
2812                return mService.getPermittedAccessibilityServicesForUser(userId);
2813            } catch (RemoteException e) {
2814                Log.w(TAG, "Failed talking with device policy service", e);
2815            }
2816        }
2817        return null;
2818     }
2819
2820    /**
2821     * Called by a profile or device owner to set the permitted input methods services. When
2822     * set by a device owner or profile owner the restriction applies to all profiles of the
2823     * user the device owner or profile owner is an admin for.
2824     *
2825     * By default the user can use any input method. When zero or more packages have
2826     * been added, input method that are not in the list and not part of the system
2827     * can not be enabled by the user.
2828     *
2829     * This method will fail if it is called for a admin that is not for the foreground user
2830     * or a profile of the foreground user.
2831     *
2832     * <p> Calling with a null value for the list disables the restriction so that all input methods
2833     * can be used, calling with an empty list disables all but the system's own input methods.
2834     *
2835     * <p> System input methods are always available to the user this method can't modify this.
2836     *
2837     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2838     * @param packageNames List of input method package names.
2839     * @return true if setting the restriction succeeded. It will fail if there is
2840     *     one or more input method enabled, that are not in the list or user if the foreground
2841     *     user.
2842     */
2843    public boolean setPermittedInputMethods(ComponentName admin, List<String> packageNames) {
2844        if (mService != null) {
2845            try {
2846                return mService.setPermittedInputMethods(admin, packageNames);
2847            } catch (RemoteException e) {
2848                Log.w(TAG, "Failed talking with device policy service", e);
2849            }
2850        }
2851        return false;
2852    }
2853
2854
2855    /**
2856     * Returns the list of permitted input methods set by this device or profile owner.
2857     *
2858     * <p>An empty list means no input methods except system input methods are allowed.
2859     * Null means all input methods are allowed.
2860     *
2861     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2862     * @return List of input method package names.
2863     */
2864    public List<String> getPermittedInputMethods(ComponentName admin) {
2865        if (mService != null) {
2866            try {
2867                return mService.getPermittedInputMethods(admin);
2868            } catch (RemoteException e) {
2869                Log.w(TAG, "Failed talking with device policy service", e);
2870            }
2871        }
2872        return null;
2873    }
2874
2875    /**
2876     * Returns the list of input methods permitted by the device or profiles
2877     * owners of the current user.
2878     *
2879     * <p>Null means all input methods are allowed, if a non-null list is returned
2880     * it will contain the intersection of the permitted lists for any device or profile
2881     * owners that apply to this user. It will also include any system input methods.
2882     *
2883     * @return List of input method package names.
2884     * @hide
2885     */
2886    @SystemApi
2887    public List<String> getPermittedInputMethodsForCurrentUser() {
2888        if (mService != null) {
2889            try {
2890                return mService.getPermittedInputMethodsForCurrentUser();
2891            } catch (RemoteException e) {
2892                Log.w(TAG, "Failed talking with device policy service", e);
2893            }
2894        }
2895        return null;
2896    }
2897
2898    /**
2899     * Called by a device owner to create a user with the specified name. The UserHandle returned
2900     * by this method should not be persisted as user handles are recycled as users are removed and
2901     * created. If you need to persist an identifier for this user, use
2902     * {@link UserManager#getSerialNumberForUser}.
2903     *
2904     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2905     * @param name the user's name
2906     * @see UserHandle
2907     * @return the UserHandle object for the created user, or null if the user could not be created.
2908     */
2909    public UserHandle createUser(ComponentName admin, String name) {
2910        try {
2911            return mService.createUser(admin, name);
2912        } catch (RemoteException re) {
2913            Log.w(TAG, "Could not create a user", re);
2914        }
2915        return null;
2916    }
2917
2918    /**
2919     * Called by a device owner to create a user with the specified name. The UserHandle returned
2920     * by this method should not be persisted as user handles are recycled as users are removed and
2921     * created. If you need to persist an identifier for this user, use
2922     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
2923     * immediately.
2924     *
2925     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
2926     * as registered as an active admin on the new user.  The profile owner package will be
2927     * installed on the new user if it already is installed on the device.
2928     *
2929     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
2930     * profileOwnerComponent when onEnable is called.
2931     *
2932     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2933     * @param name the user's name
2934     * @param ownerName the human readable name of the organisation associated with this DPM.
2935     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
2936     *      the user.
2937     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
2938     *      on the new user.
2939     * @see UserHandle
2940     * @return the UserHandle object for the created user, or null if the user could not be created.
2941     */
2942    public UserHandle createAndInitializeUser(ComponentName admin, String name, String ownerName,
2943            ComponentName profileOwnerComponent, Bundle adminExtras) {
2944        try {
2945            return mService.createAndInitializeUser(admin, name, ownerName, profileOwnerComponent,
2946                    adminExtras);
2947        } catch (RemoteException re) {
2948            Log.w(TAG, "Could not create a user", re);
2949        }
2950        return null;
2951    }
2952
2953    /**
2954     * Called by a device owner to remove a user and all associated data. The primary user can
2955     * not be removed.
2956     *
2957     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2958     * @param userHandle the user to remove.
2959     * @return {@code true} if the user was removed, {@code false} otherwise.
2960     */
2961    public boolean removeUser(ComponentName admin, UserHandle userHandle) {
2962        try {
2963            return mService.removeUser(admin, userHandle);
2964        } catch (RemoteException re) {
2965            Log.w(TAG, "Could not remove user ", re);
2966            return false;
2967        }
2968    }
2969
2970    /**
2971     * Called by a device owner to switch the specified user to the foreground.
2972     *
2973     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2974     * @param userHandle the user to switch to; null will switch to primary.
2975     * @return {@code true} if the switch was successful, {@code false} otherwise.
2976     *
2977     * @see Intent#ACTION_USER_FOREGROUND
2978     */
2979    public boolean switchUser(ComponentName admin, UserHandle userHandle) {
2980        try {
2981            return mService.switchUser(admin, userHandle);
2982        } catch (RemoteException re) {
2983            Log.w(TAG, "Could not switch user ", re);
2984            return false;
2985        }
2986    }
2987
2988    /**
2989     * Called by a profile or device owner to get the application restrictions for a given target
2990     * application running in the profile.
2991     *
2992     * <p>The calling device admin must be a profile or device owner; if it is not, a security
2993     * exception will be thrown.
2994     *
2995     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2996     * @param packageName The name of the package to fetch restricted settings of.
2997     * @return {@link Bundle} of settings corresponding to what was set last time
2998     * {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty {@link Bundle}
2999     * if no restrictions have been set.
3000     */
3001    public Bundle getApplicationRestrictions(ComponentName admin, String packageName) {
3002        if (mService != null) {
3003            try {
3004                return mService.getApplicationRestrictions(admin, packageName);
3005            } catch (RemoteException e) {
3006                Log.w(TAG, "Failed talking with device policy service", e);
3007            }
3008        }
3009        return null;
3010    }
3011
3012    /**
3013     * Called by a profile or device owner to set a user restriction specified
3014     * by the key.
3015     * <p>
3016     * The calling device admin must be a profile or device owner; if it is not,
3017     * a security exception will be thrown.
3018     *
3019     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3020     *            with.
3021     * @param key The key of the restriction. See the constants in
3022     *            {@link android.os.UserManager} for the list of keys.
3023     */
3024    public void addUserRestriction(ComponentName admin, String key) {
3025        if (mService != null) {
3026            try {
3027                mService.setUserRestriction(admin, key, true);
3028            } catch (RemoteException e) {
3029                Log.w(TAG, "Failed talking with device policy service", e);
3030            }
3031        }
3032    }
3033
3034    /**
3035     * Called by a profile or device owner to clear a user restriction specified
3036     * by the key.
3037     * <p>
3038     * The calling device admin must be a profile or device owner; if it is not,
3039     * a security exception will be thrown.
3040     *
3041     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3042     *            with.
3043     * @param key The key of the restriction. See the constants in
3044     *            {@link android.os.UserManager} for the list of keys.
3045     */
3046    public void clearUserRestriction(ComponentName admin, String key) {
3047        if (mService != null) {
3048            try {
3049                mService.setUserRestriction(admin, key, false);
3050            } catch (RemoteException e) {
3051                Log.w(TAG, "Failed talking with device policy service", e);
3052            }
3053        }
3054    }
3055
3056    /**
3057     * Called by device or profile owner to hide or unhide packages. When a package is hidden it
3058     * is unavailable for use, but the data and actual package file remain.
3059     *
3060     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3061     * @param packageName The name of the package to hide or unhide.
3062     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
3063     *                 unhidden.
3064     * @return boolean Whether the hidden setting of the package was successfully updated.
3065     */
3066    public boolean setApplicationHidden(ComponentName admin, String packageName,
3067            boolean hidden) {
3068        if (mService != null) {
3069            try {
3070                return mService.setApplicationHidden(admin, packageName, hidden);
3071            } catch (RemoteException e) {
3072                Log.w(TAG, "Failed talking with device policy service", e);
3073            }
3074        }
3075        return false;
3076    }
3077
3078    /**
3079     * Called by device or profile owner to determine if a package is hidden.
3080     *
3081     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3082     * @param packageName The name of the package to retrieve the hidden status of.
3083     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
3084     */
3085    public boolean isApplicationHidden(ComponentName admin, String packageName) {
3086        if (mService != null) {
3087            try {
3088                return mService.isApplicationHidden(admin, packageName);
3089            } catch (RemoteException e) {
3090                Log.w(TAG, "Failed talking with device policy service", e);
3091            }
3092        }
3093        return false;
3094    }
3095
3096    /**
3097     * Called by profile or device owner to re-enable a system app that was disabled by default
3098     * when the user was initialized.
3099     *
3100     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3101     * @param packageName The package to be re-enabled in the current profile.
3102     */
3103    public void enableSystemApp(ComponentName admin, String packageName) {
3104        if (mService != null) {
3105            try {
3106                mService.enableSystemApp(admin, packageName);
3107            } catch (RemoteException e) {
3108                Log.w(TAG, "Failed to install package: " + packageName);
3109            }
3110        }
3111    }
3112
3113    /**
3114     * Called by profile or device owner to re-enable system apps by intent that were disabled
3115     * by default when the user was initialized.
3116     *
3117     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3118     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
3119     *               intent will be re-enabled in the current profile.
3120     * @return int The number of activities that matched the intent and were installed.
3121     */
3122    public int enableSystemApp(ComponentName admin, Intent intent) {
3123        if (mService != null) {
3124            try {
3125                return mService.enableSystemAppWithIntent(admin, intent);
3126            } catch (RemoteException e) {
3127                Log.w(TAG, "Failed to install packages matching filter: " + intent);
3128            }
3129        }
3130        return 0;
3131    }
3132
3133    /**
3134     * Called by a profile owner to disable account management for a specific type of account.
3135     *
3136     * <p>The calling device admin must be a profile owner. If it is not, a
3137     * security exception will be thrown.
3138     *
3139     * <p>When account management is disabled for an account type, adding or removing an account
3140     * of that type will not be possible.
3141     *
3142     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3143     * @param accountType For which account management is disabled or enabled.
3144     * @param disabled The boolean indicating that account management will be disabled (true) or
3145     * enabled (false).
3146     */
3147    public void setAccountManagementDisabled(ComponentName admin, String accountType,
3148            boolean disabled) {
3149        if (mService != null) {
3150            try {
3151                mService.setAccountManagementDisabled(admin, accountType, disabled);
3152            } catch (RemoteException e) {
3153                Log.w(TAG, "Failed talking with device policy service", e);
3154            }
3155        }
3156    }
3157
3158    /**
3159     * Gets the array of accounts for which account management is disabled by the profile owner.
3160     *
3161     * <p> Account management can be disabled/enabled by calling
3162     * {@link #setAccountManagementDisabled}.
3163     *
3164     * @return a list of account types for which account management has been disabled.
3165     *
3166     * @see #setAccountManagementDisabled
3167     */
3168    public String[] getAccountTypesWithManagementDisabled() {
3169        return getAccountTypesWithManagementDisabledAsUser(UserHandle.myUserId());
3170    }
3171
3172    /**
3173     * @see #getAccountTypesWithManagementDisabled()
3174     * @hide
3175     */
3176    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
3177        if (mService != null) {
3178            try {
3179                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
3180            } catch (RemoteException e) {
3181                Log.w(TAG, "Failed talking with device policy service", e);
3182            }
3183        }
3184
3185        return null;
3186    }
3187
3188    /**
3189     * Sets which packages may enter lock task mode.
3190     *
3191     * <p>Any packages that shares uid with an allowed package will also be allowed
3192     * to activate lock task.
3193     *
3194     * This function can only be called by the device owner.
3195     * @param packages The list of packages allowed to enter lock task mode
3196     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3197     *
3198     * @see Activity#startLockTask()
3199     * @see DeviceAdminReceiver#onLockTaskModeChanged(Context, Intent, boolean, String)
3200     * @see UserManager#DISALLOW_CREATE_WINDOWS
3201     */
3202    public void setLockTaskPackages(ComponentName admin, String[] packages)
3203            throws SecurityException {
3204        if (mService != null) {
3205            try {
3206                mService.setLockTaskPackages(admin, packages);
3207            } catch (RemoteException e) {
3208                Log.w(TAG, "Failed talking with device policy service", e);
3209            }
3210        }
3211    }
3212
3213    /**
3214     * This function returns the list of packages allowed to start the lock task mode.
3215     *
3216     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3217     * @hide
3218     */
3219    public String[] getLockTaskPackages(ComponentName admin) {
3220        if (mService != null) {
3221            try {
3222                return mService.getLockTaskPackages(admin);
3223            } catch (RemoteException e) {
3224                Log.w(TAG, "Failed talking with device policy service", e);
3225            }
3226        }
3227        return null;
3228    }
3229
3230    /**
3231     * This function lets the caller know whether the given component is allowed to start the
3232     * lock task mode.
3233     * @param pkg The package to check
3234     */
3235    public boolean isLockTaskPermitted(String pkg) {
3236        if (mService != null) {
3237            try {
3238                return mService.isLockTaskPermitted(pkg);
3239            } catch (RemoteException e) {
3240                Log.w(TAG, "Failed talking with device policy service", e);
3241            }
3242        }
3243        return false;
3244    }
3245
3246    /**
3247     * Called by device owners to update {@link Settings.Global} settings. Validation that the value
3248     * of the setting is in the correct form for the setting type should be performed by the caller.
3249     * <p>The settings that can be updated with this method are:
3250     * <ul>
3251     * <li>{@link Settings.Global#ADB_ENABLED}</li>
3252     * <li>{@link Settings.Global#AUTO_TIME}</li>
3253     * <li>{@link Settings.Global#AUTO_TIME_ZONE}</li>
3254     * <li>{@link Settings.Global#BLUETOOTH_ON}</li>
3255     * <li>{@link Settings.Global#DATA_ROAMING}</li>
3256     * <li>{@link Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
3257     * <li>{@link Settings.Global#MODE_RINGER}</li>
3258     * <li>{@link Settings.Global#NETWORK_PREFERENCE}</li>
3259     * <li>{@link Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
3260     * <li>{@link Settings.Global#WIFI_ON}</li>
3261     * <li>{@link Settings.Global#WIFI_SLEEP_POLICY}</li>
3262     * </ul>
3263     *
3264     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3265     * @param setting The name of the setting to update.
3266     * @param value The value to update the setting to.
3267     */
3268    public void setGlobalSetting(ComponentName admin, String setting, String value) {
3269        if (mService != null) {
3270            try {
3271                mService.setGlobalSetting(admin, setting, value);
3272            } catch (RemoteException e) {
3273                Log.w(TAG, "Failed talking with device policy service", e);
3274            }
3275        }
3276    }
3277
3278    /**
3279     * Called by profile or device owners to update {@link Settings.Secure} settings. Validation
3280     * that the value of the setting is in the correct form for the setting type should be performed
3281     * by the caller.
3282     * <p>The settings that can be updated by a profile or device owner with this method are:
3283     * <ul>
3284     * <li>{@link Settings.Secure#DEFAULT_INPUT_METHOD}</li>
3285     * <li>{@link Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
3286     * </ul>
3287     * <p>A device owner can additionally update the following settings:
3288     * <ul>
3289     * <li>{@link Settings.Secure#LOCATION_MODE}</li>
3290     * </ul>
3291     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3292     * @param setting The name of the setting to update.
3293     * @param value The value to update the setting to.
3294     */
3295    public void setSecureSetting(ComponentName admin, String setting, String value) {
3296        if (mService != null) {
3297            try {
3298                mService.setSecureSetting(admin, setting, value);
3299            } catch (RemoteException e) {
3300                Log.w(TAG, "Failed talking with device policy service", e);
3301            }
3302        }
3303    }
3304
3305    /**
3306     * Designates a specific service component as the provider for
3307     * making permission requests of a local or remote administrator of the user.
3308     * <p/>
3309     * Only a profile owner can designate the restrictions provider.
3310     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3311     * @param provider The component name of the service that implements
3312     * {@link RestrictionsReceiver}. If this param is null,
3313     * it removes the restrictions provider previously assigned.
3314     */
3315    public void setRestrictionsProvider(ComponentName admin, ComponentName provider) {
3316        if (mService != null) {
3317            try {
3318                mService.setRestrictionsProvider(admin, provider);
3319            } catch (RemoteException re) {
3320                Log.w(TAG, "Failed to set permission provider on device policy service");
3321            }
3322        }
3323    }
3324
3325    /**
3326     * Called by profile or device owners to set the master volume mute on or off.
3327     *
3328     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3329     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
3330     */
3331    public void setMasterVolumeMuted(ComponentName admin, boolean on) {
3332        if (mService != null) {
3333            try {
3334                mService.setMasterVolumeMuted(admin, on);
3335            } catch (RemoteException re) {
3336                Log.w(TAG, "Failed to setMasterMute on device policy service");
3337            }
3338        }
3339    }
3340
3341    /**
3342     * Called by profile or device owners to check whether the master volume mute is on or off.
3343     *
3344     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3345     * @return {@code true} if master volume is muted, {@code false} if it's not.
3346     */
3347    public boolean isMasterVolumeMuted(ComponentName admin) {
3348        if (mService != null) {
3349            try {
3350                return mService.isMasterVolumeMuted(admin);
3351            } catch (RemoteException re) {
3352                Log.w(TAG, "Failed to get isMasterMute on device policy service");
3353            }
3354        }
3355        return false;
3356    }
3357
3358    /**
3359     * Called by profile or device owners to change whether a user can uninstall
3360     * a package.
3361     *
3362     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3363     * @param packageName package to change.
3364     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
3365     */
3366    public void setUninstallBlocked(ComponentName admin, String packageName,
3367            boolean uninstallBlocked) {
3368        if (mService != null) {
3369            try {
3370                mService.setUninstallBlocked(admin, packageName, uninstallBlocked);
3371            } catch (RemoteException re) {
3372                Log.w(TAG, "Failed to call block uninstall on device policy service");
3373            }
3374        }
3375    }
3376
3377    /**
3378     * Called by profile or device owners to check whether a user has been blocked from
3379     * uninstalling a package.
3380     *
3381     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3382     * @param packageName package to check.
3383     * @return true if the user shouldn't be able to uninstall the package.
3384     */
3385    public boolean isUninstallBlocked(ComponentName admin, String packageName) {
3386        if (mService != null) {
3387            try {
3388                return mService.isUninstallBlocked(admin, packageName);
3389            } catch (RemoteException re) {
3390                Log.w(TAG, "Failed to call block uninstall on device policy service");
3391            }
3392        }
3393        return false;
3394    }
3395
3396    /**
3397     * Called by the profile owner of a managed profile to enable widget providers from a
3398     * given package to be available in the parent profile. As a result the user will be able to
3399     * add widgets from the white-listed package running under the profile to a widget
3400     * host which runs under the parent profile, for example the home screen. Note that
3401     * a package may have zero or more provider components, where each component
3402     * provides a different widget type.
3403     * <p>
3404     * <strong>Note:</strong> By default no widget provider package is white-listed.
3405     * </p>
3406     *
3407     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3408     * @param packageName The package from which widget providers are white-listed.
3409     * @return Whether the package was added.
3410     *
3411     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
3412     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
3413     */
3414    public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3415        if (mService != null) {
3416            try {
3417                return mService.addCrossProfileWidgetProvider(admin, packageName);
3418            } catch (RemoteException re) {
3419                Log.w(TAG, "Error calling addCrossProfileWidgetProvider", re);
3420            }
3421        }
3422        return false;
3423    }
3424
3425    /**
3426     * Called by the profile owner of a managed profile to disable widget providers from a given
3427     * package to be available in the parent profile. For this method to take effect the
3428     * package should have been added via {@link #addCrossProfileWidgetProvider(
3429     * android.content.ComponentName, String)}.
3430     * <p>
3431     * <strong>Note:</strong> By default no widget provider package is white-listed.
3432     * </p>
3433     *
3434     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3435     * @param packageName The package from which widget providers are no longer
3436     *     white-listed.
3437     * @return Whether the package was removed.
3438     *
3439     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
3440     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
3441     */
3442    public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3443        if (mService != null) {
3444            try {
3445                return mService.removeCrossProfileWidgetProvider(admin, packageName);
3446            } catch (RemoteException re) {
3447                Log.w(TAG, "Error calling removeCrossProfileWidgetProvider", re);
3448            }
3449        }
3450        return false;
3451    }
3452
3453    /**
3454     * Called by the profile owner of a managed profile to query providers from which packages are
3455     * available in the parent profile.
3456     *
3457     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3458     * @return The white-listed package list.
3459     *
3460     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
3461     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
3462     */
3463    public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3464        if (mService != null) {
3465            try {
3466                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
3467                if (providers != null) {
3468                    return providers;
3469                }
3470            } catch (RemoteException re) {
3471                Log.w(TAG, "Error calling getCrossProfileWidgetProviders", re);
3472            }
3473        }
3474        return Collections.emptyList();
3475    }
3476}
3477