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