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