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