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