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