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