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