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