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