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