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