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