OSDN Git Service

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