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