Debian Codegraph @

core/java/android/app/admin/DevicePolicyManager.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.app.admin;
18
19 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
20
21 import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
22
23 import android.Manifest.permission;
24 import android.accounts.Account;
25 import android.annotation.CallbackExecutor;
26 import android.annotation.ColorInt;
27 import android.annotation.IntDef;
28 import android.annotation.NonNull;
29 import android.annotation.Nullable;
30 import android.annotation.RequiresFeature;
31 import android.annotation.RequiresPermission;
32 import android.annotation.SdkConstant;
33 import android.annotation.SdkConstant.SdkConstantType;
34 import android.annotation.StringDef;
35 import android.annotation.SuppressLint;
36 import android.annotation.SystemApi;
37 import android.annotation.SystemService;
38 import android.annotation.TestApi;
39 import android.annotation.UserHandleAware;
40 import android.annotation.UserIdInt;
41 import android.annotation.WorkerThread;
42 import android.app.Activity;
43 import android.app.IServiceConnection;
44 import android.app.KeyguardManager;
45 import android.app.admin.SecurityLog.SecurityEvent;
46 import android.compat.annotation.UnsupportedAppUsage;
47 import android.content.ComponentName;
48 import android.content.Context;
49 import android.content.Intent;
50 import android.content.IntentFilter;
51 import android.content.ServiceConnection;
52 import android.content.pm.ApplicationInfo;
53 import android.content.pm.IPackageDataObserver;
54 import android.content.pm.PackageManager;
55 import android.content.pm.PackageManager.NameNotFoundException;
56 import android.content.pm.ParceledListSlice;
57 import android.content.pm.UserInfo;
58 import android.graphics.Bitmap;
59 import android.graphics.drawable.Drawable;
60 import android.net.PrivateDnsConnectivityChecker;
61 import android.net.ProxyInfo;
62 import android.net.Uri;
63 import android.nfc.NfcAdapter;
64 import android.os.Binder;
65 import android.os.Build;
66 import android.os.Bundle;
67 import android.os.IpcDataCache;
68 import android.os.ParcelFileDescriptor;
69 import android.os.Parcelable;
70 import android.os.PersistableBundle;
71 import android.os.Process;
72 import android.os.RemoteCallback;
73 import android.os.RemoteException;
74 import android.os.ServiceSpecificException;
75 import android.os.UserHandle;
76 import android.os.UserManager;
77 import android.os.UserManager.UserOperationException;
78 import android.os.UserManager.UserOperationResult;
79 import android.provider.CalendarContract;
80 import android.provider.ContactsContract.Directory;
81 import android.provider.Settings;
82 import android.security.AttestedKeyPair;
83 import android.security.Credentials;
84 import android.security.KeyChain;
85 import android.security.KeyChainException;
86 import android.security.keymaster.KeymasterCertificateChain;
87 import android.security.keystore.AttestationUtils;
88 import android.security.keystore.KeyAttestationException;
89 import android.security.keystore.KeyGenParameterSpec;
90 import android.security.keystore.ParcelableKeyGenParameterSpec;
91 import android.security.keystore.StrongBoxUnavailableException;
92 import android.service.restrictions.RestrictionsReceiver;
93 import android.telephony.TelephonyManager;
94 import android.telephony.data.ApnSetting;
95 import android.text.TextUtils;
96 import android.util.ArraySet;
97 import android.util.DebugUtils;
98 import android.util.Log;
99 import android.util.Pair;
100
101 import com.android.internal.annotations.VisibleForTesting;
102 import com.android.internal.infra.AndroidFuture;
103 import com.android.internal.net.NetworkUtilsInternal;
104 import com.android.internal.os.BackgroundThread;
105 import com.android.internal.util.Preconditions;
106 import com.android.org.conscrypt.TrustedCertificateStore;
107
108 import java.io.ByteArrayInputStream;
109 import java.io.FileNotFoundException;
110 import java.io.IOException;
111 import java.lang.annotation.Retention;
112 import java.lang.annotation.RetentionPolicy;
113 import java.net.InetSocketAddress;
114 import java.net.Proxy;
115 import java.security.KeyFactory;
116 import java.security.KeyPair;
117 import java.security.NoSuchAlgorithmException;
118 import java.security.PrivateKey;
119 import java.security.cert.Certificate;
120 import java.security.cert.CertificateException;
121 import java.security.cert.CertificateFactory;
122 import java.security.cert.X509Certificate;
123 import java.security.spec.InvalidKeySpecException;
124 import java.security.spec.PKCS8EncodedKeySpec;
125 import java.util.ArrayList;
126 import java.util.Arrays;
127 import java.util.Collections;
128 import java.util.HashSet;
129 import java.util.List;
130 import java.util.Map;
131 import java.util.Objects;
132 import java.util.Set;
133 import java.util.concurrent.CompletableFuture;
134 import java.util.concurrent.ExecutionException;
135 import java.util.concurrent.Executor;
136 import java.util.function.Consumer;
137
138 // TODO(b/172376923) - add CarDevicePolicyManager examples below (or remove reference to it).
139 /**
140 * Public interface for managing policies enforced on a device. Most clients of this class must be
141 * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
142 * administrator</a>. Additionally, a device administrator may be registered as either a profile or
143 * device owner. A given method is accessible to all device administrators unless the documentation
144 * for that method specifies that it is restricted to either device or profile owners. Any
145 * application calling an api may only pass as an argument a device administrator component it
146 * owns. Otherwise, a {@link SecurityException} will be thrown.
147 *
148 * <p><b>Note: </b>on
149 * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, some methods can
150 * throw an {@link UnsafeStateException} exception (for example, if the vehicle is moving), so
151 * callers running on automotive builds should wrap every method call under the methods provided by
152 * {@code android.car.admin.CarDevicePolicyManager}.
153 *
154 * <div class="special reference">
155 * <h3>Developer Guides</h3>
156 * <p>
157 * For more information about managing policies for device administration, read the <a href=
158 * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
159 * guide. </div>
160 */
161 @SystemService(Context.DEVICE_POLICY_SERVICE)
162 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN)
163 @SuppressLint("UseIcu")
164 public class DevicePolicyManager {
165
166 private static String TAG = "DevicePolicyManager";
167
168 private final Context mContext;
169 private final IDevicePolicyManager mService;
170 private final boolean mParentInstance;
171 private final DevicePolicyResourcesManager mResourcesManager;
172
173 /** @hide */
174 public DevicePolicyManager(Context context, IDevicePolicyManager service) {
175 this(context, service, false);
176 }
177
178 /** @hide */
179 @VisibleForTesting
180 protected DevicePolicyManager(Context context, IDevicePolicyManager service,
181 boolean parentInstance) {
182 mContext = context;
183 mService = service;
184 mParentInstance = parentInstance;
185 mResourcesManager = new DevicePolicyResourcesManager(context, service);
186 }
187
188 /**
189 * Fetch the current value of mService. This is used in the binder cache lambda
190 * expressions.
191 */
192 private final IDevicePolicyManager getService() {
193 return mService;
194 }
195
196 /**
197 * Fetch the current value of mParentInstance. This is used in the binder cache
198 * lambda expressions.
199 */
200 private final boolean isParentInstance() {
201 return mParentInstance;
202 }
203
204 /**
205 * Fetch the current value of mContext. This is used in the binder cache lambda
206 * expressions.
207 */
208 private final Context getContext() {
209 return mContext;
210 }
211
212 /** @hide test will override it. */
213 @VisibleForTesting
214 protected int myUserId() {
215 return mContext.getUserId();
216 }
217
218 /**
219 * Activity action: Starts the provisioning flow which sets up a managed profile.
220 *
221 * <p>A managed profile allows data separation for example for the usage of a
222 * device as a personal and corporate device. The user which provisioning is started from and
223 * the managed profile share a launcher.
224 *
225 * <p>This intent will typically be sent by a mobile device management application (MDM).
226 * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
227 * control over the profile.
228 *
229 * <p>It is possible to check if provisioning is allowed or not by querying the method
230 * {@link #isProvisioningAllowed(String)}.
231 *
232 * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
233 * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
234 * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
235 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
236 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
237 *
238 * <p>The intent may also contain the following extras:
239 * <ul>
240 * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
241 * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
242 * {@link android.os.Build.VERSION_CODES#N}</li>
243 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
244 * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
245 * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
246 * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
247 * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
248 * </ul>
249 *
250 * <p>When managed provisioning has completed, broadcasts are sent to the application specified
251 * in the provisioning intent. The
252 * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
253 * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
254 * the primary profile.
255 *
256 * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
257 * completed, along with the above broadcast, activity intent
258 * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
259 *
260 * <p>If provisioning fails, the managedProfile is removed so the device returns to its
261 * previous state.
262 *
263 * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
264 * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
265 * the provisioning flow was successful, although this doesn't guarantee the full flow will
266 * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
267 * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
268 *
269 * <p>If a device policy management role holder (DPMRH) updater is present on the device, an
270 * internet connection attempt must be made prior to launching this intent. If internet
271 * connection could not be established, provisioning will fail unless {@link
272 * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is explicitly set to {@code true}, in which case
273 * provisioning will continue without using the DPMRH. If an internet connection has been
274 * established, the DPMRH updater will be launched, which will update the DPMRH if it's not
275 * present on the device, or if it's present and not valid.
276 *
277 * <p>If a DPMRH is present on the device and valid, the provisioning flow will be deferred to
278 * it.
279 */
280 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
281 public static final String ACTION_PROVISION_MANAGED_PROFILE
282 = "android.app.action.PROVISION_MANAGED_PROFILE";
283
284 /**
285 * Activity action: Starts the provisioning flow which sets up a managed user.
286 *
287 * <p>This intent will typically be sent by a mobile device management application (MDM).
288 * Provisioning configures the user as managed user and sets the MDM as the profile
289 * owner who has full control over the user. Provisioning can only happen before user setup has
290 * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
291 * allowed.
292 *
293 * <p>The intent contains the following extras:
294 * <ul>
295 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
296 * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
297 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
298 * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
299 * </ul>
300 *
301 * <p>If provisioning fails, the device returns to its previous state.
302 *
303 * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
304 * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
305 * the provisioning flow was successful, although this doesn't guarantee the full flow will
306 * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
307 * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
308 *
309 * @hide
310 */
311 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
312 public static final String ACTION_PROVISION_MANAGED_USER
313 = "android.app.action.PROVISION_MANAGED_USER";
314
315 /**
316 * Activity action: Starts the provisioning flow which sets up a managed device.
317 * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
318 *
319 * <p> During device owner provisioning a device admin app is set as the owner of the device.
320 * A device owner has full control over the device. The device owner can not be modified by the
321 * user.
322 *
323 * <p> A typical use case would be a device that is owned by a company, but used by either an
324 * employee or client.
325 *
326 * <p> An intent with this action can be sent only on an unprovisioned device.
327 * It is possible to check if provisioning is allowed or not by querying the method
328 * {@link #isProvisioningAllowed(String)}.
329 *
330 * <p>The intent contains the following extras:
331 * <ul>
332 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
333 * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
334 * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
335 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
336 * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
337 * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
338 * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional</li>
339 * </ul>
340 *
341 * <p>When device owner provisioning has completed, an intent of the type
342 * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
343 * device owner.
344 *
345 * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
346 * completed, along with the above broadcast, activity intent
347 * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
348 *
349 * <p>If provisioning fails, the device is factory reset.
350 *
351 * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
352 * of the provisioning flow was successful, although this doesn't guarantee the full flow will
353 * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
354 * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
355 *
356 * @deprecated to support {@link android.os.Build.VERSION_CODES#S} and later, admin apps must
357 * implement activities with intent filters for the {@link #ACTION_GET_PROVISIONING_MODE} and
358 * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent actions; using {@link
359 * #ACTION_PROVISION_MANAGED_DEVICE} to start provisioning will cause the provisioning to fail;
360 * to additionally support pre-{@link android.os.Build.VERSION_CODES#S}, admin apps must also
361 * continue to use this constant.
362 */
363 @Deprecated
364 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
365 public static final String ACTION_PROVISION_MANAGED_DEVICE
366 = "android.app.action.PROVISION_MANAGED_DEVICE";
367
368 /**
369 * Activity action: launch when user provisioning completed, i.e.
370 * {@link #getUserProvisioningState()} returns one of the complete state.
371 *
372 * <p> Please note that the API behavior is not necessarily consistent across various releases,
373 * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
374 * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
375 *
376 * <p> The activity must be protected by permission
377 * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
378 * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
379 * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
380 * components are not started by this intent.
381 *
382 * @deprecated Starting from Android T, the system no longer launches an intent with this action
383 * when user provisioning completes.
384 * @hide
385 */
386 @Deprecated
387 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
388 @SystemApi
389 public static final String ACTION_STATE_USER_SETUP_COMPLETE =
390 "android.app.action.STATE_USER_SETUP_COMPLETE";
391
392 /**
393 * Activity action: Starts the provisioning flow which sets up a managed device.
394 *
395 * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
396 * the device. A device owner has full control over the device. The device owner can not be
397 * modified by the user and the only way of resetting the device is via factory reset.
398 *
399 * <p>From version {@link android.os.Build.VERSION_CODES#Q}, the admin app can choose
400 * whether to set up a fully managed device or a managed profile. For the admin app to support
401 * this, it must have an activity with intent filter {@link #ACTION_GET_PROVISIONING_MODE} and
402 * another one with intent filter {@link #ACTION_ADMIN_POLICY_COMPLIANCE}. For example:
403 * <pre>
404 * &lt;activity
405 * android:name=".GetProvisioningModeActivity"
406 * android:label="@string/app_name"
407 * android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
408 * &lt;intent-filter&gt;
409 * &lt;action
410 * android:name="android.app.action.GET_PROVISIONING_MODE" /&gt;
411 * &lt;category android:name="android.intent.category.DEFAULT" /&gt;
412 * &lt;/intent-filter&gt;
413 * &lt;/activity&gt;
414 *
415 * &lt;activity
416 * android:name=".PolicyComplianceActivity"
417 * android:label="@string/app_name"
418 * android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
419 * &lt;intent-filter&gt;
420 * &lt;action
421 * android:name="android.app.action.ADMIN_POLICY_COMPLIANCE" /&gt;
422 * &lt;category android:name="android.intent.category.DEFAULT" /&gt;
423 * &lt;/intent-filter&gt;
424 * &lt;/activity&gt;</pre>
425 *
426 * <p>A typical use case would be a device that is owned by a company, but used by either an
427 * employee or client.
428 *
429 * <p>The provisioning message should be sent to an unprovisioned device.
430 *
431 * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
432 * by a privileged app with the permission
433 * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
434 *
435 * <p>If a device policy management role holder (DPMRH) updater is present on the device, an
436 * internet connection attempt must be made prior to launching this intent. If internet
437 * connection could not be established, provisioning will fail unless {@link
438 * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is explicitly set to {@code true}, in which case
439 * provisioning will continue without using the DPMRH. If an internet connection has been
440 * established, the DPMRH updater will be launched via {@link
441 * #ACTION_UPDATE_DEVICE_MANAGEMENT_ROLE_HOLDER}, which will update the DPMRH if it's not
442 * present on the device, or if it's present and not valid.
443 *
444 * <p>A DPMRH is considered valid if it has intent filters for {@link
445 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}, {@link
446 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link
447 * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION}.
448 *
449 * <p>If a DPMRH is present on the device and valid, the provisioning flow will be deferred to
450 * it via the {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent.
451 *
452 * <p>The provisioning intent contains the following properties:
453 * <ul>
454 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
455 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
456 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
457 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
458 * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
459 * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
460 * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
461 * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
462 * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
463 * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
464 * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
465 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
466 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
467 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
468 * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
469 * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
470 * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
471 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
472 * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA}, optional </li>
473 * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional - when not used for
474 * cloud enrollment, NFC or QR provisioning</li>
475 * </ul>
476 *
477 * @hide
478 */
479 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
480 @SystemApi
481 public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
482 "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
483
484 /**
485 * Activity action: Starts the provisioning flow which sets up a financed device.
486 *
487 * <p>During financed device provisioning, a device admin app is downloaded and set as the owner
488 * of the device. A device owner has full control over the device. The device owner can not be
489 * modified by the user.
490 *
491 * <p>A typical use case would be a device that is bought from the reseller through financing
492 * program.
493 *
494 * <p>An intent with this action can be sent only on an unprovisioned device.
495 *
496 * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
497 * by a privileged app with the permission
498 * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
499 *
500 * <p>The provisioning intent contains the following properties:
501 * <ul>
502 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
503 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
504 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
505 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
506 * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
507 * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
508 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
509 * </ul>
510 *
511 * <p>Once the device admin app is set as the device owner, the following APIs are available for
512 * managing polices on the device:
513 * <ul>
514 * <li>{@link #isDeviceManaged()}</li>
515 * <li>{@link #isUninstallBlocked(ComponentName, String)}</li>
516 * <li>{@link #setUninstallBlocked(ComponentName, String, boolean)}</li>
517 * <li>{@link #setUserControlDisabledPackages(ComponentName, List)}</li>
518 * <li>{@link #getUserControlDisabledPackages(ComponentName)}</li>
519 * <li>{@link #setOrganizationName(ComponentName, CharSequence)}</li>
520 * <li>{@link #getOrganizationName(ComponentName)} </li>
521 * <li>{@link #setShortSupportMessage(ComponentName, CharSequence)}</li>
522 * <li>{@link #getShortSupportMessage(ComponentName)}</li>
523 * <li>{@link #isBackupServiceEnabled(ComponentName)}</li>
524 * <li>{@link #setBackupServiceEnabled(ComponentName, boolean)}</li>
525 * <li>{@link #isLockTaskPermitted(String)}</li>
526 * <li>{@link #setLockTaskFeatures(ComponentName, int)}, where the following lock task features
527 * can be set (otherwise a {@link SecurityException} will be thrown):</li>
528 * <ul>
529 * <li>{@link #LOCK_TASK_FEATURE_SYSTEM_INFO}</li>
530 * <li>{@link #LOCK_TASK_FEATURE_KEYGUARD}</li>
531 * <li>{@link #LOCK_TASK_FEATURE_HOME}</li>
532 * <li>{@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}</li>
533 * <li>{@link #LOCK_TASK_FEATURE_NOTIFICATIONS}</li>
534 * </ul>
535 * <li>{@link #getLockTaskFeatures(ComponentName)}</li>
536 * <li>{@link #setLockTaskPackages(ComponentName, String[])}</li>
537 * <li>{@link #getLockTaskPackages(ComponentName)}</li>
538 * <li>{@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}</li>
539 * <li>{@link #clearPackagePersistentPreferredActivities(ComponentName, String)} </li>
540 * <li>{@link #wipeData(int)}</li>
541 * <li>{@link #isDeviceOwnerApp(String)}</li>
542 * <li>{@link #clearDeviceOwnerApp(String)}</li>
543 * <li>{@link #setPermissionGrantState(ComponentName, String, String, int)}, where
544 * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be
545 * {@link #PERMISSION_GRANT_STATE_GRANTED}, {@link #PERMISSION_GRANT_STATE_DENIED}, or
546 * {@link #PERMISSION_GRANT_STATE_DEFAULT} and can <b>only</b> be applied to the device admin
547 * app (otherwise a {@link SecurityException} will be thrown)</li>
548 * <li>{@link #getPermissionGrantState(ComponentName, String, String)}, where
549 * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be
550 * used and device admin app is the only package that can be used to retrieve the permission
551 * permission grant state for (otherwise a {@link SecurityException} will be thrown)</li>
552 * <li>{@link #addUserRestriction(ComponentName, String)}, where the following user restrictions
553 * are permitted (otherwise a {@link SecurityException} will be thrown):</li>
554 * <ul>
555 * <li>{@link UserManager#DISALLOW_ADD_USER}</li>
556 * <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li>
557 * <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li>
558 * <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li>
559 * <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li>
560 * <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li>
561 * </ul>
562 * <li>{@link #getUserRestrictions(ComponentName)}</li>
563 * <li>{@link #clearUserRestriction(ComponentName, String)}, where the following user
564 * restrictions are permitted (otherwise a {@link SecurityException} will be thrown):</li>
565 * <ul>
566 * <li>{@link UserManager#DISALLOW_ADD_USER}</li>
567 * <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li>
568 * <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li>
569 * <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li>
570 * <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li>
571 * <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li>
572 * </ul>
573 * </ul>
574 *
575 * @hide
576 */
577 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
578 @SystemApi
579 public static final String ACTION_PROVISION_FINANCED_DEVICE =
580 "android.app.action.PROVISION_FINANCED_DEVICE";
581
582 /**
583 * Activity action: Finalizes management provisioning, should be used after user-setup
584 * has been completed and {@link #getUserProvisioningState()} returns one of:
585 * <ul>
586 * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
587 * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
588 * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
589 * </ul>
590 *
591 * <p>If a device policy management role holder (DPMRH) is present on the device and
592 * valid, the provisioning flow will be deferred to it via the {@link
593 * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION} intent.
594 *
595 * @hide
596 */
597 @SystemApi
598 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
599 public static final String ACTION_PROVISION_FINALIZATION
600 = "android.app.action.PROVISION_FINALIZATION";
601
602 /**
603 * Activity action: starts the managed profile provisioning flow inside the device policy
604 * management role holder.
605 *
606 * <p>During the managed profile provisioning flow, the platform-provided provisioning handler
607 * will delegate provisioning to the device policy management role holder, by firing this
608 * intent. Third-party mobile device management applications attempting to fire this intent will
609 * receive a {@link SecurityException}.
610 *
611 * <p>Device policy management role holders are required to have a handler for this intent
612 * action.
613 *
614 * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility
615 * of the role holder to restore its state from this extra. This is the same {@link Bundle}
616 * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}.
617 *
618 * <p>A result code of {@link Activity#RESULT_OK} implies that managed profile provisioning
619 * finished successfully. If it did not, a result code of {@link Activity#RESULT_CANCELED}
620 * is used instead.
621 *
622 * @see #ACTION_PROVISION_MANAGED_PROFILE
623 *
624 * @hide
625 */
626 @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
627 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
628 @SystemApi
629 public static final String ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE =
630 "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_PROFILE";
631
632 /**
633 * Result code that can be returned by the {@link
634 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
635 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if a work
636 * profile has been created.
637 *
638 * @hide
639 */
640 @SystemApi
641 public static final int RESULT_WORK_PROFILE_CREATED = 122;
642
643 /**
644 * Result code that can be returned by the {@link
645 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
646 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if the
647 * device owner was set.
648 *
649 * @hide
650 */
651 @SystemApi
652 public static final int RESULT_DEVICE_OWNER_SET = 123;
653
654 /**
655 * Activity action: starts the trusted source provisioning flow inside the device policy
656 * management role holder.
657 *
658 * <p>During the trusted source provisioning flow, the platform-provided provisioning handler
659 * will delegate provisioning to the device policy management role holder, by firing this
660 * intent. Third-party mobile device management applications attempting to fire this intent will
661 * receive a {@link SecurityException}.
662 *
663 * <p>Device policy management role holders are required to have a handler for this intent
664 * action.
665 *
666 * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility
667 * of the role holder to restore its state from this extra. This is the same {@link Bundle}
668 * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}.
669 *
670 * <p>The result codes can be either {@link #RESULT_WORK_PROFILE_CREATED}, {@link
671 * #RESULT_DEVICE_OWNER_SET} or {@link Activity#RESULT_CANCELED} if provisioning failed.
672 *
673 * @see #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE
674 *
675 * @hide
676 */
677 @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
678 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
679 @SystemApi
680 public static final String ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
681 "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
682
683 /**
684 * Activity action: starts the provisioning finalization flow inside the device policy
685 * management role holder.
686 *
687 * <p>During the provisioning finalization flow, the platform-provided provisioning handler
688 * will delegate provisioning to the device policy management role holder, by firing this
689 * intent. Third-party mobile device management applications attempting to fire this intent will
690 * receive a {@link SecurityException}.
691 *
692 * <p>Device policy management role holders are required to have a handler for this intent
693 * action.
694 *
695 * <p>This handler forwards the result from the admin app's {@link
696 * #ACTION_ADMIN_POLICY_COMPLIANCE} handler. Result code {@link Activity#RESULT_CANCELED}
697 * implies the provisioning finalization flow has failed.
698 *
699 * @see #ACTION_PROVISION_FINALIZATION
700 *
701 * @hide
702 */
703 @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
704 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
705 @SystemApi
706 public static final String ACTION_ROLE_HOLDER_PROVISION_FINALIZATION =
707 "android.app.action.ROLE_HOLDER_PROVISION_FINALIZATION";
708
709 /**
710 * {@link Activity} result code which can be returned by {@link
711 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link
712 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} to signal that an update
713 * to the role holder is required.
714 *
715 * <p>This result code can be accompanied by {@link #EXTRA_ROLE_HOLDER_STATE}.
716 *
717 * @hide
718 */
719 @SystemApi
720 public static final int RESULT_UPDATE_ROLE_HOLDER = 2;
721
722 /**
723 * A {@link PersistableBundle} extra which the role holder can use to describe its own state
724 * when it returns {@link #RESULT_UPDATE_ROLE_HOLDER}.
725 *
726 * <p>If {@link #RESULT_UPDATE_ROLE_HOLDER} was accompanied by this extra, after the update
727 * completes, the role holder's {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} or {@link
728 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent will be relaunched,
729 * which will contain this extra. It is the role holder's responsibility to restore its
730 * state from this extra.
731 *
732 * <p>The content of this {@link PersistableBundle} is entirely up to the role holder. It
733 * should contain anything the role holder needs to restore its original state when it gets
734 * restarted.
735 *
736 * @hide
737 */
738 @SystemApi
739 public static final String EXTRA_ROLE_HOLDER_STATE = "android.app.extra.ROLE_HOLDER_STATE";
740
741 /**
742 * A {@code boolean} extra which determines whether to force a role holder update, regardless
743 * of any internal conditions {@link #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} might
744 * have.
745 *
746 * <p>This extra can be provided to intents with action {@link
747 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}.
748 *
749 * @hide
750 */
751 @SystemApi
752 public static final String EXTRA_FORCE_UPDATE_ROLE_HOLDER =
753 "android.app.extra.FORCE_UPDATE_ROLE_HOLDER";
754
755 /**
756 * A boolean extra indicating whether offline provisioning is allowed.
757 *
758 * <p>For the online provisioning flow, there will be an attempt to download and install
759 * the latest version of the device policy management role holder. The platform will then
760 * delegate provisioning to the device policy management role holder via role holder-specific
761 * provisioning actions.
762 *
763 * <p>For the offline provisioning flow, the provisioning flow will always be handled by
764 * the platform.
765 *
766 * <p>If this extra is set to {@code false}, the provisioning flow will enforce that an
767 * internet connection is established, which will start the online provisioning flow. If an
768 * internet connection cannot be established, provisioning will fail.
769 *
770 * <p>If this extra is set to {@code true}, the provisioning flow will still try to connect to
771 * the internet, but if it fails it will start the offline provisioning flow.
772 *
773 * <p>For T if this extra is set to {@code true}, the provisioning flow will be forced through
774 * the platform and there will be no attempt to download and install the device policy
775 * management role holder.
776 *
777 * <p>The default value is {@code false}.
778 *
779 * <p>This extra is respected when provided via the provisioning intent actions such as {@link
780 * #ACTION_PROVISION_MANAGED_PROFILE}.
781 */
782 public static final String EXTRA_PROVISIONING_ALLOW_OFFLINE =
783 "android.app.extra.PROVISIONING_ALLOW_OFFLINE";
784
785 /**
786 * A String extra holding a url that specifies the download location of the device policy
787 * management role holder package.
788 *
789 * <p>This is only meant to be used in cases when a specific variant of the role holder package
790 * is needed (such as a debug variant). If not provided, the default variant of the device
791 * manager role holder package is downloaded.
792 *
793 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
794 * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
795 * provisioning via an NFC bump.
796 *
797 * @hide
798 */
799 @SystemApi
800 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION =
801 "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION";
802
803 /**
804 * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
805 * android package archive at the download location specified in {@link
806 * #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}.
807 *
808 * <p>The signatures of an android package archive can be obtained using
809 * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
810 * {@link android.content.pm.PackageManager#GET_SIGNING_CERTIFICATES}.
811 *
812 * <p>If {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION} is provided, it must
813 * be accompanied by this extra. The provided checksum must match the checksum of any signature
814 * of the file at the download location. If the checksum does not match an error will be shown
815 * to the user and the user will be asked to factory reset the device.
816 *
817 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
818 * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
819 * provisioning via an NFC bump.
820 *
821 * @hide
822 */
823 @SystemApi
824 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM =
825 "android.app.extra.PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM";
826
827 /**
828 * A String extra holding a http cookie header which should be used in the http request to the
829 * url specified in {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}.
830 *
831 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
832 * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
833 * provisioning via an NFC bump.
834 *
835 * @hide
836 */
837 @SystemApi
838 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER =
839 "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER";
840
841 /**
842 * An extra of type {@link android.os.PersistableBundle} that allows the provisioning initiator
843 * to pass data to the device policy management role holder.
844 *
845 * <p>The device policy management role holder will receive this extra via the {@link
846 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent.
847 *
848 * <p>The contents of this extra are up to the contract between the provisioning initiator
849 * and the device policy management role holder.
850 *
851 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
852 * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
853 * provisioning via an NFC bump.
854 *
855 * @hide
856 */
857 @SystemApi
858 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE =
859 "android.app.extra.PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE";
860
861 /**
862 * A String extra containing the package name of the provisioning initiator.
863 *
864 * <p>Use in an intent with action {@link
865 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
866 *
867 * @hide
868 */
869 @SystemApi
870 public static final String EXTRA_ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE =
871 "android.app.extra.ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE";
872
873 /**
874 * An {@link Intent} result extra specifying the {@link Intent} to be launched after
875 * provisioning is finalized.
876 *
877 * <p>If {@link #EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT} is set to {@code false},
878 * this result will be supplied as part of the result {@link Intent} for provisioning actions
879 * such as {@link #ACTION_PROVISION_MANAGED_PROFILE}. This result will also be supplied as
880 * part of the result {@link Intent} for the device policy management role holder provisioning
881 * actions.
882 */
883 public static final String EXTRA_RESULT_LAUNCH_INTENT =
884 "android.app.extra.RESULT_LAUNCH_INTENT";
885
886 /**
887 * A boolean extra that determines whether the provisioning flow should launch the resulting
888 * launch intent, if one is supplied by the device policy management role holder via {@link
889 * #EXTRA_RESULT_LAUNCH_INTENT}. Default value is {@code false}.
890 *
891 * <p>If {@code true}, the resulting intent will be launched by the provisioning flow, if one
892 * is supplied by the device policy management role holder.
893 *
894 * <p>If {@code false}, the resulting intent will be returned as {@link
895 * #EXTRA_RESULT_LAUNCH_INTENT} to the provisioning initiator, if one is supplied by the device
896 * manager role holder. It will be the responsibility of the provisioning initiator to launch
897 * this {@link Intent} after provisioning completes.
898 *
899 * <p>This extra is respected when provided via the provisioning intent actions such as {@link
900 * #ACTION_PROVISION_MANAGED_PROFILE}.
901 */
902 public static final String EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT =
903 "android.app.extra.PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT";
904
905 /**
906 * Action: Bugreport sharing with device owner has been accepted by the user.
907 *
908 * @hide
909 */
910 public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
911 "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
912
913 /**
914 * Action: Bugreport sharing with device owner has been declined by the user.
915 *
916 * @hide
917 */
918 public static final String ACTION_BUGREPORT_SHARING_DECLINED =
919 "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
920
921 /**
922 * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
923 *
924 * @hide
925 */
926 public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
927 "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
928
929 /**
930 * Extra for shared bugreport's SHA-256 hash.
931 *
932 * @hide
933 */
934 public static final String EXTRA_REMOTE_BUGREPORT_HASH =
935 "android.intent.extra.REMOTE_BUGREPORT_HASH";
936
937 /**
938 * Extra for shared bugreport's nonce in long integer type.
939 *
940 * @hide
941 */
942 public static final String EXTRA_REMOTE_BUGREPORT_NONCE =
943 "android.intent.extra.REMOTE_BUGREPORT_NONCE";
944
945 /**
946 * Extra for remote bugreport notification shown type.
947 *
948 * @hide
949 */
950 public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
951 "android.app.extra.bugreport_notification_type";
952
953 /**
954 * Default value for preferential network service enabling.
955 *
956 * @hide
957 */
958 public static final boolean PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT = false;
959
960 /**
961 * Notification type for a started remote bugreport flow.
962 *
963 * @hide
964 */
965 public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
966
967 /**
968 * Notification type for a bugreport that has already been accepted to be shared, but is still
969 * being taken.
970 *
971 * @hide
972 */
973 public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
974
975 /**
976 * Notification type for a bugreport that has been taken and can be shared or declined.
977 *
978 * @hide
979 */
980 public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
981
982 /**
983 * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
984 * i.e. the user has to use a strong authentication method like password, PIN or pattern.
985 *
986 * @hide
987 */
988 public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
989
990 /**
991 * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
992 * allows a mobile device management application or NFC programmer application which starts
993 * managed provisioning to pass data to the management application instance after provisioning.
994 * <p>
995 * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
996 * sends the intent to pass data to itself on the newly created profile.
997 * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
998 * instance of the app on the primary user.
999 * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
1000 * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
1001 * message should contain a stringified {@link java.util.Properties} instance, whose string
1002 * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
1003 * management application after provisioning.
1004 *
1005 * <p>Admin apps will receive this extra in their {@link #ACTION_GET_PROVISIONING_MODE} and
1006 * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent handlers. Additionally, {@link
1007 * #ACTION_GET_PROVISIONING_MODE} may also return this extra which will then be sent over to
1008 * {@link #ACTION_ADMIN_POLICY_COMPLIANCE}, alongside the original values that were passed to
1009 * {@link #ACTION_GET_PROVISIONING_MODE}.
1010 *
1011 * <p>
1012 * In both cases the application receives the data in
1013 * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
1014 * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
1015 * during the managed provisioning.
1016 */
1017 public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
1018 "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
1019
1020 /**
1021 * A String extra holding the package name of the mobile device management application that
1022 * will be set as the profile owner or device owner.
1023 *
1024 * <p>If an application starts provisioning directly via an intent with action
1025 * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
1026 * application that started provisioning. The package will be set as profile owner in that case.
1027 *
1028 * <p>This package is set as device owner when device owner provisioning is started by an NFC
1029 * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
1030 *
1031 * <p> When this extra is set, the application must have exactly one device admin receiver.
1032 * This receiver will be set as the profile or device owner and active admin.
1033 *
1034 * @see DeviceAdminReceiver
1035 * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
1036 * supported, but only if there is only one device admin receiver in the package that requires
1037 * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
1038 */
1039 @Deprecated
1040 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
1041 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
1042
1043 /**
1044 * A ComponentName extra indicating the device admin receiver of the mobile device management
1045 * application that will be set as the profile owner or device owner and active admin.
1046 *
1047 * <p>If an application starts provisioning directly via an intent with action
1048 * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1049 * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
1050 * component has to match the package name of the application that started provisioning.
1051 *
1052 * <p>This component is set as device owner and active admin when device owner provisioning is
1053 * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
1054 * message containing an NFC record with MIME type
1055 * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
1056 * flattened to a string, via {@link ComponentName#flattenToShortString()}.
1057 *
1058 * @see DeviceAdminReceiver
1059 */
1060 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
1061 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
1062
1063 /**
1064 * An {@link android.accounts.Account} extra holding the account to migrate during managed
1065 * profile provisioning. If the account supplied is present in the primary user, it will be
1066 * copied, along with its credentials to the managed profile and removed from the primary user.
1067 *
1068 * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}, with managed account provisioning, or
1069 * return as an extra to the intent result from the {@link #ACTION_GET_PROVISIONING_MODE}
1070 * activity.
1071 */
1072
1073 public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
1074 = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
1075
1076 /**
1077 * Boolean extra to indicate that the migrated account should be kept. This is used in
1078 * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
1079 * the account will not be removed from the primary user after it is migrated to the newly
1080 * created user or profile.
1081 *
1082 * <p> Defaults to {@code false}
1083 *
1084 * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or set as an extra to the
1085 * intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1086 *
1087 * @see #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
1088 */
1089 public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
1090 = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
1091
1092 /**
1093 * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
1094 * device.
1095 */
1096 @Deprecated
1097 public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
1098 = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
1099
1100 /**
1101 * A integer extra indicating the predominant color to show during the provisioning.
1102 * Refer to {@link android.graphics.Color} for how the color is represented.
1103 *
1104 * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1105 * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
1106 *
1107 * @deprecated Color customization is no longer supported in the provisioning flow.
1108 */
1109 @Deprecated
1110 public static final String EXTRA_PROVISIONING_MAIN_COLOR =
1111 "android.app.extra.PROVISIONING_MAIN_COLOR";
1112
1113 /**
1114 * A Boolean extra that can be used by the mobile device management application to skip the
1115 * disabling of system apps during provisioning when set to {@code true}.
1116 *
1117 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC}, an intent with action
1118 * {@link #ACTION_PROVISION_MANAGED_PROFILE} that starts profile owner provisioning or
1119 * set as an extra to the intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1120 */
1121 public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
1122 "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
1123
1124 /**
1125 * A String extra holding the time zone {@link android.app.AlarmManager} that the device
1126 * will be set to.
1127 *
1128 * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1129 * performing the admin-integrated provisioning flow as a result of the {@link
1130 * #ACTION_GET_PROVISIONING_MODE} activity.
1131 *
1132 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1133 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1134 */
1135 public static final String EXTRA_PROVISIONING_TIME_ZONE
1136 = "android.app.extra.PROVISIONING_TIME_ZONE";
1137
1138 /**
1139 * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
1140 * {@link android.app.AlarmManager}.
1141 *
1142 * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1143 * performing the admin-integrated provisioning flow as a result of the {@link
1144 * #ACTION_GET_PROVISIONING_MODE} activity.
1145 *
1146 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1147 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1148 */
1149 public static final String EXTRA_PROVISIONING_LOCAL_TIME
1150 = "android.app.extra.PROVISIONING_LOCAL_TIME";
1151
1152 /**
1153 * A String extra holding the {@link java.util.Locale} that the device will be set to.
1154 * Format: xx_yy, where xx is the language code, and yy the country code.
1155 *
1156 * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1157 * performing the admin-integrated provisioning flow as a result of the {@link
1158 * #ACTION_GET_PROVISIONING_MODE} activity.
1159 *
1160 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1161 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1162 */
1163 public static final String EXTRA_PROVISIONING_LOCALE
1164 = "android.app.extra.PROVISIONING_LOCALE";
1165
1166 /**
1167 * A String extra holding the ssid of the wifi network that should be used during nfc device
1168 * owner provisioning for downloading the mobile device management application.
1169 *
1170 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1171 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1172 */
1173 public static final String EXTRA_PROVISIONING_WIFI_SSID
1174 = "android.app.extra.PROVISIONING_WIFI_SSID";
1175
1176 /**
1177 * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1178 * is hidden or not.
1179 *
1180 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1181 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1182 */
1183 public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
1184 = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
1185
1186 /**
1187 * A String extra indicating the security type of the wifi network in
1188 * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA},
1189 * {@code WEP} or {@code EAP}.
1190 *
1191 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1192 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1193 */
1194 public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
1195 = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
1196
1197 /**
1198 * A String extra holding the password of the wifi network in
1199 * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1200 *
1201 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1202 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1203 */
1204 public static final String EXTRA_PROVISIONING_WIFI_PASSWORD =
1205 "android.app.extra.PROVISIONING_WIFI_PASSWORD";
1206
1207 /**
1208 * The EAP method of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1209 * and could be one of {@code PEAP}, {@code TLS}, {@code TTLS}, {@code PWD}, {@code SIM},
1210 * {@code AKA} or {@code AKA_PRIME}. This is only used if the
1211 * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1212 *
1213 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1214 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1215 */
1216 public static final String EXTRA_PROVISIONING_WIFI_EAP_METHOD =
1217 "android.app.extra.PROVISIONING_WIFI_EAP_METHOD";
1218
1219 /**
1220 * The phase 2 authentication of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1221 * and could be one of {@code NONE}, {@code PAP}, {@code MSCHAP}, {@code MSCHAPV2}, {@code GTC},
1222 * {@code SIM}, {@code AKA} or {@code AKA_PRIME}. This is only used if the
1223 * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1224 *
1225 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1226 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1227 */
1228 public static final String EXTRA_PROVISIONING_WIFI_PHASE2_AUTH =
1229 "android.app.extra.PROVISIONING_WIFI_PHASE2_AUTH";
1230
1231 /**
1232 * The CA certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This should
1233 * be an X.509 certificate Base64 encoded DER format, ie. PEM representation of a certificate
1234 * without header, footer and line breaks. <a href=
1235 * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
1236 * used if the {@link
1237 * #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1238 *
1239 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1240 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1241 */
1242 public static final String EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE =
1243 "android.app.extra.PROVISIONING_WIFI_CA_CERTIFICATE";
1244
1245 /**
1246 * The user certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This
1247 * should be an X.509 certificate and private key Base64 encoded DER format, ie. PEM
1248 * representation of a certificate and key without header, footer and line breaks. <a href=
1249 * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
1250 * used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1251 *
1252 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1253 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1254 */
1255 public static final String EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE =
1256 "android.app.extra.PROVISIONING_WIFI_USER_CERTIFICATE";
1257
1258 /**
1259 * The identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used
1260 * if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1261 *
1262 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1263 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1264 */
1265 public static final String EXTRA_PROVISIONING_WIFI_IDENTITY =
1266 "android.app.extra.PROVISIONING_WIFI_IDENTITY";
1267
1268 /**
1269 * The anonymous identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is
1270 * only used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1271 *
1272 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1273 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1274 */
1275
1276 public static final String EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY =
1277 "android.app.extra.PROVISIONING_WIFI_ANONYMOUS_IDENTITY";
1278 /**
1279 * The domain of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used if
1280 * the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1281 *
1282 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1283 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1284 */
1285 public static final String EXTRA_PROVISIONING_WIFI_DOMAIN =
1286 "android.app.extra.PROVISIONING_WIFI_DOMAIN";
1287
1288 /**
1289 * A String extra holding the proxy host for the wifi network in
1290 * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1291 *
1292 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1293 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1294 */
1295 public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
1296 = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
1297
1298 /**
1299 * An int extra holding the proxy port for the wifi network in
1300 * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1301 *
1302 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1303 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1304 */
1305 public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
1306 = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
1307
1308 /**
1309 * A String extra holding the proxy bypass for the wifi network in
1310 * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1311 *
1312 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1313 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1314 */
1315 public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
1316 = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
1317
1318 /**
1319 * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
1320 * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1321 *
1322 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1323 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1324 */
1325 public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
1326 = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
1327
1328 /**
1329 * A String extra holding a url that specifies the download location of the device admin
1330 * package. When not provided it is assumed that the device admin package is already installed.
1331 *
1332 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1333 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1334 */
1335 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
1336 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
1337
1338 /**
1339 * A String extra holding the localized name of the organization under management.
1340 *
1341 * The name is displayed only during provisioning.
1342 *
1343 * <p>Use in an intent with action {@link #ACTION_PROVISION_FINANCED_DEVICE}
1344 *
1345 * @hide
1346 */
1347 @SystemApi
1348 public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
1349 "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
1350
1351 /**
1352 * A String extra holding a url to the website of the device provider so the user can open it
1353 * during provisioning. If the url is not HTTPS, an error will be shown.
1354 *
1355 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1356 * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1357 *
1358 * @hide
1359 */
1360 @SystemApi
1361 public static final String EXTRA_PROVISIONING_SUPPORT_URL =
1362 "android.app.extra.PROVISIONING_SUPPORT_URL";
1363
1364 /**
1365 * A String extra holding the localized name of the device admin package. It should be the same
1366 * as the app label of the package.
1367 *
1368 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1369 * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1370 *
1371 * @deprecated This extra is no longer respected in the provisioning flow.
1372 * @hide
1373 */
1374 @Deprecated
1375 @SystemApi
1376 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
1377 "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
1378
1379 /**
1380 * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
1381 * shown during the provisioning.
1382 * <h5>The following URI schemes are accepted:</h5>
1383 * <ul>
1384 * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1385 * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1386 * </ul>
1387 *
1388 * <p> It is the responsibility of the caller to provide an image with a reasonable
1389 * pixel density for the device.
1390 *
1391 * <p> If a content: URI is passed, the intent should have the flag
1392 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1393 * {@link android.content.ClipData} of the intent too.
1394 *
1395 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1396 * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1397 *
1398 * @deprecated This extra is no longer respected in the provisioning flow.
1399 * @hide
1400 */
1401 @SystemApi
1402 @Deprecated
1403 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
1404 "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
1405
1406 /**
1407 * An int extra holding a minimum required version code for the device admin package. If the
1408 * device admin is already installed on the device, it will only be re-downloaded from
1409 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
1410 * installed package is less than this version code.
1411 *
1412 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1413 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1414 */
1415 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
1416 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
1417
1418 /**
1419 * A String extra holding a http cookie header which should be used in the http request to the
1420 * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1421 *
1422 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1423 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1424 */
1425 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
1426 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
1427
1428 /**
1429 * A String extra holding the URL-safe base64 encoded SHA-256 hash of the file at download
1430 * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1431 *
1432 * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
1433 * present. The provided checksum must match the checksum of the file at the download
1434 * location. If the checksum doesn't match an error will be shown to the user and the user will
1435 * be asked to factory reset the device.
1436 *
1437 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1438 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1439 *
1440 * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
1441 * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
1442 * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
1443 * addition to SHA-1. From {@link android.os.Build.VERSION_CODES#Q}, only SHA-256 hash is
1444 * supported.
1445 */
1446 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
1447 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
1448
1449 /**
1450 * A boolean extra indicating the admin of a fully-managed device opts out of controlling
1451 * permission grants for sensor-related permissions,
1452 * see {@link #setPermissionGrantState(ComponentName, String, String, int)}.
1453 *
1454 * The default for this extra is {@code false} - by default, the admin of a fully-managed
1455 * device has the ability to grant sensors-related permissions.
1456 *
1457 * <p>Use only for device owner provisioning. This extra can be returned by the
1458 * admin app when performing the admin-integrated provisioning flow as a result of the
1459 * {@link #ACTION_GET_PROVISIONING_MODE} activity.
1460 *
1461 * <p>This extra may also be provided to the admin app via an intent extra for {@link
1462 * #ACTION_GET_PROVISIONING_MODE}.
1463 *
1464 * @see #ACTION_GET_PROVISIONING_MODE
1465 */
1466 public static final String EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT =
1467 "android.app.extra.PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT";
1468
1469 /**
1470 * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
1471 * android package archive at the download location specified in {@link
1472 * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1473 *
1474 * <p>The signatures of an android package archive can be obtained using
1475 * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
1476 * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
1477 *
1478 * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
1479 * present. The provided checksum must match the checksum of any signature of the file at
1480 * the download location. If the checksum does not match an error will be shown to the user and
1481 * the user will be asked to factory reset the device.
1482 *
1483 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1484 * provisioning via an NFC bump. It can also be used for QR code provisioning.
1485 */
1486 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
1487 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
1488
1489 /**
1490 * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
1491 * has completed successfully.
1492 *
1493 * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
1494 * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1495 *
1496 * <p>This intent will contain the following extras
1497 * <ul>
1498 * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
1499 * profile.</li>
1500 * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
1501 * be migrated at provisioning time, if any.</li>
1502 * </ul>
1503 */
1504 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1505 public static final String ACTION_MANAGED_PROFILE_PROVISIONED
1506 = "android.app.action.MANAGED_PROFILE_PROVISIONED";
1507
1508 /**
1509 * Activity action: This activity action is sent to indicate that provisioning of a managed
1510 * profile or managed device has completed successfully. It'll be sent at the same time as
1511 * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
1512 * delivered faster as it's an activity intent.
1513 *
1514 * <p>The intent is only sent to the new device or profile owner.
1515 *
1516 * @see #ACTION_PROVISION_MANAGED_PROFILE
1517 * @see #ACTION_PROVISION_MANAGED_DEVICE
1518 */
1519 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1520 public static final String ACTION_PROVISIONING_SUCCESSFUL =
1521 "android.app.action.PROVISIONING_SUCCESSFUL";
1522
1523 /**
1524 * A boolean extra indicating whether device encryption can be skipped as part of device owner
1525 * or managed profile provisioning.
1526 *
1527 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
1528 * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
1529 *
1530 * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
1531 * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1532 *
1533 * <p>This extra can also be returned by the admin app when performing the admin-integrated
1534 * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1535 */
1536 public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
1537 "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
1538
1539 /**
1540 * A {@link Uri} extra pointing to a logo image. This image will be shown during the
1541 * provisioning. If this extra is not passed, a default image will be shown.
1542 * <h5>The following URI schemes are accepted:</h5>
1543 * <ul>
1544 * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1545 * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1546 * </ul>
1547 *
1548 * <p> It is the responsibility of the caller to provide an image with a reasonable
1549 * pixel density for the device.
1550 *
1551 * <p> If a content: URI is passed, the intent should have the flag
1552 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1553 * {@link android.content.ClipData} of the intent too.
1554 *
1555 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1556 * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1557 *
1558 * @deprecated Logo customization is no longer supported in the provisioning flow.
1559 */
1560 @Deprecated
1561 public static final String EXTRA_PROVISIONING_LOGO_URI =
1562 "android.app.extra.PROVISIONING_LOGO_URI";
1563
1564 /**
1565 * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
1566 * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
1567 * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
1568 * content.
1569 *
1570 * <p> The extra typically contains one disclaimer from the company of mobile device
1571 * management application (MDM), and one disclaimer from the organization.
1572 *
1573 * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
1574 *
1575 * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
1576 *
1577 * <p> Can be used in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}. This
1578 * extra can also be returned by the admin app when performing the admin-integrated
1579 * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1580 */
1581 public static final String EXTRA_PROVISIONING_DISCLAIMERS =
1582 "android.app.extra.PROVISIONING_DISCLAIMERS";
1583
1584 /**
1585 * A String extra of localized disclaimer header.
1586 *
1587 * <p> The extra is typically the company name of mobile device management application (MDM)
1588 * or the organization name.
1589 *
1590 * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1591 *
1592 * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1593 * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1594 * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
1595 *
1596 * <pre>
1597 * &lt;meta-data
1598 * android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
1599 * android:resource="@string/disclaimer_header"
1600 * /&gt;</pre>
1601 */
1602 public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
1603 "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
1604
1605 /**
1606 * A {@link Uri} extra pointing to disclaimer content.
1607 *
1608 * <h5>The following URI schemes are accepted:</h5>
1609 * <ul>
1610 * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1611 * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1612 * </ul>
1613 *
1614 * <p> Styled text is supported in the disclaimer content. The content is parsed by
1615 * {@link android.text.Html#fromHtml(String)} and displayed in a
1616 * {@link android.widget.TextView}.
1617 *
1618 * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
1619 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1620 * {@link android.content.ClipData} of the intent too.
1621 *
1622 * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1623 *
1624 * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1625 * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1626 * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
1627 *
1628 * <pre>
1629 * &lt;meta-data
1630 * android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
1631 * android:resource="@string/disclaimer_content"
1632 * /&gt;</pre>
1633 */
1634 public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
1635 "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
1636
1637 /**
1638 * A boolean extra indicating if the user consent steps from the provisioning flow should be
1639 * skipped. If unspecified, defaults to {@code false}.
1640 *
1641 * It can only be used by an existing device owner trying to create a managed profile via
1642 * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1643 *
1644 * @deprecated this extra is no longer relevant as device owners cannot create managed profiles
1645 */
1646 @Deprecated
1647 public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1648 "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1649
1650 /**
1651 * A boolean extra indicating if the education screens from the provisioning flow should be
1652 * skipped. If unspecified, defaults to {@code false}.
1653 *
1654 * <p>This extra can be set in the following ways:
1655 * <ul>
1656 * <li>By the admin app when performing the admin-integrated
1657 * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity</li>
1658 * <li>For managed account enrollment</li>
1659 * </ul>
1660 *
1661 * <p>If the education screens are skipped, it is the admin application's responsibility
1662 * to display its own user education screens.
1663 */
1664 public static final String EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS =
1665 "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS";
1666
1667 /**
1668 * A boolean extra indicating if mobile data should be used during the provisioning flow
1669 * for downloading the admin app. If {@link #EXTRA_PROVISIONING_WIFI_SSID} is also specified,
1670 * wifi network will be used instead.
1671 *
1672 * <p>Default value is {@code false}.
1673 *
1674 * <p>If this extra is set to {@code true} and {@link #EXTRA_PROVISIONING_WIFI_SSID} is not
1675 * specified, this extra has different behaviour depending on the way provisioning is triggered:
1676 * <ul>
1677 * <li>
1678 * For provisioning started via a QR code or an NFC tag, mobile data is always used for
1679 * downloading the admin app.
1680 * </li>
1681 * <li>
1682 * For all other provisioning methods, a mobile data connection check is made at the start
1683 * of provisioning. If mobile data is connected at that point, the admin app download will
1684 * happen using mobile data. If mobile data is not connected at that point, the end-user
1685 * will be asked to pick a wifi network and the admin app download will proceed over wifi.
1686 * </li>
1687 * </ul>
1688 */
1689 public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA =
1690 "android.app.extra.PROVISIONING_USE_MOBILE_DATA";
1691
1692 /**
1693 * Possible values for {@link #EXTRA_PROVISIONING_TRIGGER}.
1694 *
1695 * @hide
1696 */
1697 @IntDef(prefix = { "PROVISIONING_TRIGGER_" }, value = {
1698 PROVISIONING_TRIGGER_UNSPECIFIED,
1699 PROVISIONING_TRIGGER_CLOUD_ENROLLMENT,
1700 PROVISIONING_TRIGGER_QR_CODE,
1701 PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER,
1702 PROVISIONING_TRIGGER_MANAGED_ACCOUNT,
1703 PROVISIONING_TRIGGER_NFC
1704 })
1705 @Retention(RetentionPolicy.SOURCE)
1706 public @interface ProvisioningTrigger {}
1707
1708 /**
1709 * Flags for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES}.
1710 *
1711 * @hide
1712 */
1713 @IntDef(flag = true, prefix = { "FLAG_SUPPORTED_MODES_" }, value = {
1714 FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED,
1715 FLAG_SUPPORTED_MODES_PERSONALLY_OWNED,
1716 FLAG_SUPPORTED_MODES_DEVICE_OWNER
1717 })
1718 @Retention(RetentionPolicy.SOURCE)
1719 public @interface ProvisioningConfiguration {}
1720
1721 /**
1722 * An int extra holding the provisioning trigger. It could be one of
1723 * {@link #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT}, {@link #PROVISIONING_TRIGGER_QR_CODE},
1724 * {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} or {@link
1725 * #PROVISIONING_TRIGGER_UNSPECIFIED}.
1726 *
1727 * <p>Use in an intent with action {@link
1728 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
1729 * @hide
1730 */
1731 @SystemApi
1732 public static final String EXTRA_PROVISIONING_TRIGGER =
1733 "android.app.extra.PROVISIONING_TRIGGER";
1734
1735 /**
1736 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1737 * trigger has not been specified.
1738 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1739 * @see #PROVISIONING_TRIGGER_QR_CODE
1740 * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1741 * @see #PROVISIONING_TRIGGER_NFC
1742 * @hide
1743 */
1744 @SystemApi
1745 public static final int PROVISIONING_TRIGGER_UNSPECIFIED = 0;
1746
1747 /**
1748 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1749 * trigger is cloud enrollment.
1750 * @see #PROVISIONING_TRIGGER_QR_CODE
1751 * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1752 * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1753 * @see #PROVISIONING_TRIGGER_NFC
1754 * @hide
1755 */
1756 @SystemApi
1757 public static final int PROVISIONING_TRIGGER_CLOUD_ENROLLMENT = 1;
1758
1759 /**
1760 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1761 * trigger is the QR code scanner.
1762 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1763 * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1764 * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1765 * @see #PROVISIONING_TRIGGER_NFC
1766 * @hide
1767 */
1768 @SystemApi
1769 public static final int PROVISIONING_TRIGGER_QR_CODE = 2;
1770
1771 /**
1772 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1773 * trigger is persistent device owner enrollment.
1774 * <p>This constant is meant to represent a specific type of managed account provisioning which
1775 * provisions a device to a device owner by invoking the standard provisioning flow (where
1776 * the ManagedProvisioning component downloads and installs the admin app), as opposed to
1777 * relying on the provisioning trigger to handle download and install of the admin app.
1778 * <p>As of {@link android.os.Build.VERSION_CODES#S}, this constant is no longer used in favor
1779 * of the more general {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} which handles all managed
1780 * account provisioning types.
1781 * @deprecated Use the broader {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} instead
1782 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1783 * @see #PROVISIONING_TRIGGER_QR_CODE
1784 * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1785 * @see #PROVISIONING_TRIGGER_NFC
1786 * @hide
1787 */
1788 @SystemApi
1789 @Deprecated
1790 public static final int PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER = 3;
1791
1792 /**
1793 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1794 * trigger is managed account enrollment.
1795 * <p>
1796 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1797 * @see #PROVISIONING_TRIGGER_QR_CODE
1798 * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1799 * @see #PROVISIONING_TRIGGER_NFC
1800 * @hide
1801 */
1802 @SystemApi
1803 public static final int PROVISIONING_TRIGGER_MANAGED_ACCOUNT = 4;
1804
1805 /**
1806 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning is
1807 * triggered by tapping an NFC tag.
1808 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1809 * @see #PROVISIONING_TRIGGER_QR_CODE
1810 * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1811 * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1812 * @hide
1813 */
1814 @SystemApi
1815 public static final int PROVISIONING_TRIGGER_NFC = 5;
1816
1817 /**
1818 * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning is
1819 * organization-owned.
1820 *
1821 * <p>Using this value indicates the admin app can only be provisioned in either a
1822 * fully-managed device or a corporate-owned work profile. This will cause the admin app's
1823 * {@link #ACTION_GET_PROVISIONING_MODE} activity to have the {@link
1824 * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1825 * #PROVISIONING_MODE_MANAGED_PROFILE} and {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}.
1826 *
1827 * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}. In
1828 * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have
1829 * the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1830 * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1831 * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1832 *
1833 * @hide
1834 */
1835 @SystemApi
1836 public static final int FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED = 1;
1837
1838 /**
1839 * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning
1840 * is personally-owned.
1841 *
1842 * <p>Using this flag will cause the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
1843 * activity to have the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra
1844 * contain only {@link #PROVISIONING_MODE_MANAGED_PROFILE}.
1845 *
1846 * <p>Also, if this flag is set, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity
1847 * will not receive the {@link #EXTRA_PROVISIONING_IMEI} and {@link
1848 * #EXTRA_PROVISIONING_SERIAL_NUMBER} extras.
1849 *
1850 * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}. In
1851 * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have the
1852 * {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1853 * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1854 * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1855 *
1856 * @hide
1857 */
1858 @SystemApi
1859 public static final int FLAG_SUPPORTED_MODES_PERSONALLY_OWNED = 1 << 1;
1860
1861 /**
1862 * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that the only
1863 * supported provisioning mode is device owner.
1864 *
1865 * @hide
1866 */
1867 @SystemApi
1868 public static final int FLAG_SUPPORTED_MODES_DEVICE_OWNER = 1 << 2;
1869
1870 /**
1871 * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1872 * {@link #setMinimumRequiredWifiSecurityLevel(int)}: no minimum security level.
1873 *
1874 * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1875 * represents the current minimum security level required.
1876 * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1877 * minimum security level a Wi-Fi network must meet.
1878 *
1879 * @see #WIFI_SECURITY_PERSONAL
1880 * @see #WIFI_SECURITY_ENTERPRISE_EAP
1881 * @see #WIFI_SECURITY_ENTERPRISE_192
1882 */
1883 public static final int WIFI_SECURITY_OPEN = 0;
1884
1885 /**
1886 * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1887 * {@link #setMinimumRequiredWifiSecurityLevel(int)}: personal network such as WEP, WPA2-PSK.
1888 *
1889 * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1890 * represents the current minimum security level required.
1891 * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1892 * minimum security level a Wi-Fi network must meet.
1893 *
1894 * @see #WIFI_SECURITY_OPEN
1895 * @see #WIFI_SECURITY_ENTERPRISE_EAP
1896 * @see #WIFI_SECURITY_ENTERPRISE_192
1897 */
1898 public static final int WIFI_SECURITY_PERSONAL = 1;
1899
1900 /**
1901 * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1902 * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise EAP network.
1903 *
1904 * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1905 * represents the current minimum security level required.
1906 * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1907 * minimum security level a Wi-Fi network must meet.
1908 *
1909 * @see #WIFI_SECURITY_OPEN
1910 * @see #WIFI_SECURITY_PERSONAL
1911 * @see #WIFI_SECURITY_ENTERPRISE_192
1912 */
1913 public static final int WIFI_SECURITY_ENTERPRISE_EAP = 2;
1914
1915 /**
1916 * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1917 * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise 192 bit network.
1918 *
1919 * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1920 * represents the current minimum security level required.
1921 * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1922 * minimum security level a Wi-Fi network must meet.
1923 *
1924 * @see #WIFI_SECURITY_OPEN
1925 * @see #WIFI_SECURITY_PERSONAL
1926 * @see #WIFI_SECURITY_ENTERPRISE_EAP
1927 */
1928 public static final int WIFI_SECURITY_ENTERPRISE_192 = 3;
1929
1930 /**
1931 * Possible Wi-Fi minimum security levels
1932 *
1933 * @hide */
1934 @Retention(RetentionPolicy.SOURCE)
1935 @IntDef(prefix = {"WIFI_SECURITY_"}, value = {
1936 WIFI_SECURITY_OPEN,
1937 WIFI_SECURITY_PERSONAL,
1938 WIFI_SECURITY_ENTERPRISE_EAP,
1939 WIFI_SECURITY_ENTERPRISE_192})
1940 public @interface WifiSecurity {}
1941
1942 /**
1943 * This MIME type is used for starting the device owner provisioning.
1944 *
1945 * <p>During device owner provisioning a device admin app is set as the owner of the device.
1946 * A device owner has full control over the device. The device owner can not be modified by the
1947 * user and the only way of resetting the device is if the device owner app calls a factory
1948 * reset.
1949 *
1950 * <p> A typical use case would be a device that is owned by a company, but used by either an
1951 * employee or client.
1952 *
1953 * <p> The NFC message must be sent to an unprovisioned device.
1954 *
1955 * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1956 * contains the following properties:
1957 * <ul>
1958 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1959 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1960 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1961 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1962 * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1963 * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1964 * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1965 * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1966 * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1967 * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1968 * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1969 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1970 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1971 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1972 * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1973 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from {@link
1974 * android.os.Build.VERSION_CODES#M} </li>
1975 * <li>{@link #EXTRA_PROVISIONING_WIFI_EAP_METHOD}, optional, supported from {@link
1976 * android.os.Build.VERSION_CODES#Q}</li>
1977 * <li>{@link #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}, optional, supported from {@link
1978 * android.os.Build.VERSION_CODES#Q}</li>
1979 * <li>{@link #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}, optional, supported from {@link
1980 * android.os.Build.VERSION_CODES#Q}</li>
1981 * <li>{@link #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}, optional, supported from {@link
1982 * android.os.Build.VERSION_CODES#Q}</li>
1983 * <li>{@link #EXTRA_PROVISIONING_WIFI_IDENTITY}, optional, supported from {@link
1984 * android.os.Build.VERSION_CODES#Q}</li>
1985 * <li>{@link #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}, optional, supported from {@link
1986 * android.os.Build.VERSION_CODES#Q}</li>
1987 * <li>{@link #EXTRA_PROVISIONING_WIFI_DOMAIN}, optional, supported from {@link
1988 * android.os.Build.VERSION_CODES#Q}</li></ul>
1989 *
1990 * <p>
1991 * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1992 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1993 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1994 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1995 */
1996 public static final String MIME_TYPE_PROVISIONING_NFC
1997 = "application/com.android.managedprovisioning";
1998
1999 /**
2000 * Activity action: ask the user to add a new device administrator to the system.
2001 * The desired policy is the ComponentName of the policy in the
2002 * {@link #EXTRA_DEVICE_ADMIN} extra field. This will invoke a UI to
2003 * bring the user through adding the device administrator to the system (or
2004 * allowing them to reject it).
2005 *
2006 * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
2007 * field to provide the user with additional explanation (in addition
2008 * to your component's description) about what is being added.
2009 *
2010 * <p>If your administrator is already active, this will ordinarily return immediately (without
2011 * user intervention). However, if your administrator has been updated and is requesting
2012 * additional uses-policy flags, the user will be presented with the new list. New policies
2013 * will not be available to the updated administrator until the user has accepted the new list.
2014 */
2015 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2016 public static final String ACTION_ADD_DEVICE_ADMIN
2017 = "android.app.action.ADD_DEVICE_ADMIN";
2018
2019 /**
2020 * @hide
2021 * Activity action: ask the user to add a new device administrator as the profile owner
2022 * for this user. Only system apps can launch this intent.
2023 *
2024 * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
2025 * extra field. This will invoke a UI to bring the user through adding the profile owner admin
2026 * to remotely control restrictions on the user.
2027 *
2028 * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
2029 * result of whether or not the user approved the action. If approved, the result will
2030 * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
2031 * as a profile owner.
2032 *
2033 * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
2034 * field to provide the user with additional explanation (in addition
2035 * to your component's description) about what is being added.
2036 *
2037 * <p>If there is already a profile owner active or the caller is not a system app, the
2038 * operation will return a failure result.
2039 */
2040 @SystemApi
2041 public static final String ACTION_SET_PROFILE_OWNER
2042 = "android.app.action.SET_PROFILE_OWNER";
2043
2044 /**
2045 * @hide
2046 * Name of the profile owner admin that controls the user.
2047 */
2048 @SystemApi
2049 public static final String EXTRA_PROFILE_OWNER_NAME
2050 = "android.app.extra.PROFILE_OWNER_NAME";
2051
2052 /**
2053 * Broadcast action: send when any policy admin changes a policy.
2054 * This is generally used to find out when a new policy is in effect.
2055 *
2056 * If the profile owner of an organization-owned managed profile changes some user
2057 * restriction explicitly on the parent user, this broadcast will <em>not</em> be
2058 * sent to the parent user.
2059 * @hide
2060 */
2061 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2062 public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
2063 = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
2064
2065 /**
2066 * Broadcast action: sent when the device owner is set, changed or cleared.
2067 *
2068 * This broadcast is sent only to the primary user.
2069 * @see #ACTION_PROVISION_MANAGED_DEVICE
2070 * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
2071 */
2072 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2073 public static final String ACTION_DEVICE_OWNER_CHANGED
2074 = "android.app.action.DEVICE_OWNER_CHANGED";
2075
2076 /**
2077 * Broadcast action: sent when the factory reset protection (FRP) policy is changed.
2078 *
2079 * @see #setFactoryResetProtectionPolicy
2080 * @hide
2081 */
2082 @RequiresPermission(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION)
2083 @SystemApi
2084 public static final String ACTION_RESET_PROTECTION_POLICY_CHANGED =
2085 "android.app.action.RESET_PROTECTION_POLICY_CHANGED";
2086
2087 /**
2088 * Broadcast action: sent when there is a location update on a device in lost mode. This
2089 * broadcast is explicitly sent to the device policy controller app only.
2090 *
2091 * @see DevicePolicyManager#sendLostModeLocationUpdate
2092 * @hide
2093 */
2094 @SystemApi
2095 public static final String ACTION_LOST_MODE_LOCATION_UPDATE =
2096 "android.app.action.LOST_MODE_LOCATION_UPDATE";
2097
2098 /**
2099 * Extra used with {@link #ACTION_LOST_MODE_LOCATION_UPDATE} to send the location of a device
2100 * in lost mode. Value is {@code Location}.
2101 *
2102 * @see DevicePolicyManager#sendLostModeLocationUpdate
2103 * @hide
2104 */
2105 @SystemApi
2106 public static final String EXTRA_LOST_MODE_LOCATION =
2107 "android.app.extra.LOST_MODE_LOCATION";
2108
2109 /**
2110 * The ComponentName of the administrator component.
2111 *
2112 * @see #ACTION_ADD_DEVICE_ADMIN
2113 */
2114 public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
2115
2116 /**
2117 * An optional CharSequence providing additional explanation for why the
2118 * admin is being added.
2119 *
2120 * @see #ACTION_ADD_DEVICE_ADMIN
2121 */
2122 public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
2123
2124 /**
2125 * Constant to indicate the feature of disabling the camera. Used as argument to
2126 * {@link #createAdminSupportIntent(String)}.
2127 * @see #setCameraDisabled(ComponentName, boolean)
2128 */
2129 public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
2130
2131 /**
2132 * Constant to indicate the feature of disabling screen captures. Used as argument to
2133 * {@link #createAdminSupportIntent(String)}.
2134 * @see #setScreenCaptureDisabled(ComponentName, boolean)
2135 */
2136 public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
2137
2138 /**
2139 * Constant to indicate the feature of suspending app. Use it as the value of
2140 * {@link #EXTRA_RESTRICTION}.
2141 * @hide
2142 */
2143 public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
2144
2145 /**
2146 * A String indicating a specific restricted feature. Can be a user restriction from the
2147 * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
2148 * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
2149 * @see #createAdminSupportIntent(String)
2150 * @hide
2151 */
2152 @SystemApi
2153 public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
2154
2155 /**
2156 * Activity action: have the user enter a new password.
2157 *
2158 * <p>For admin apps, this activity should be launched after using {@link
2159 * #setPasswordQuality(ComponentName, int)}, or {@link
2160 * #setPasswordMinimumLength(ComponentName, int)} to have the user enter a new password that
2161 * meets the current requirements. You can use {@link #isActivePasswordSufficient()} to
2162 * determine whether you need to have the user select a new password in order to meet the
2163 * current constraints. Upon being resumed from this activity, you can check the new
2164 * password characteristics to see if they are sufficient.
2165 *
2166 * <p>Non-admin apps can use {@link #getPasswordComplexity()} to check the current screen lock
2167 * complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest
2168 * to users how complex the app wants the new screen lock to be. Note that both {@link
2169 * #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the
2170 * calling app to have the permission {@link permission#REQUEST_PASSWORD_COMPLEXITY}.
2171 *
2172 * <p>If the intent is launched from within a managed profile with a profile
2173 * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
2174 * this will trigger entering a new password for the parent of the profile.
2175 * For all other cases it will trigger entering a new password for the user
2176 * or profile it is launched from.
2177 *
2178 * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
2179 */
2180 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2181 public static final String ACTION_SET_NEW_PASSWORD
2182 = "android.app.action.SET_NEW_PASSWORD";
2183
2184 /**
2185 * An integer indicating the complexity level of the new password an app would like the user to
2186 * set when launching the action {@link #ACTION_SET_NEW_PASSWORD}.
2187 *
2188 * <p>Must be one of
2189 * <ul>
2190 * <li>{@link #PASSWORD_COMPLEXITY_HIGH}
2191 * <li>{@link #PASSWORD_COMPLEXITY_MEDIUM}
2192 * <li>{@link #PASSWORD_COMPLEXITY_LOW}
2193 * <li>{@link #PASSWORD_COMPLEXITY_NONE}
2194 * </ul>
2195 *
2196 * <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}.
2197 */
2198 @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
2199 public static final String EXTRA_PASSWORD_COMPLEXITY =
2200 "android.app.extra.PASSWORD_COMPLEXITY";
2201
2202 /**
2203 * Constant for {@link #getPasswordComplexity()} and
2204 * {@link #setRequiredPasswordComplexity(int)}: no password.
2205 *
2206 * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2207 * the exact complexity band the password is in.
2208 * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2209 * band which the password must meet.
2210 */
2211 public static final int PASSWORD_COMPLEXITY_NONE = 0;
2212
2213 /**
2214 * Constant for {@link #getPasswordComplexity()} and
2215 * {@link #setRequiredPasswordComplexity(int)}.
2216 * Define the low password complexity band as:
2217 * <ul>
2218 * <li>pattern
2219 * <li>PIN with repeating (4444) or ordered (1234, 4321, 2468) sequences
2220 * </ul>
2221 *
2222 * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2223 * the exact complexity band the password is in.
2224 * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2225 * band which the password must meet.
2226 *
2227 * @see #PASSWORD_QUALITY_SOMETHING
2228 * @see #PASSWORD_QUALITY_NUMERIC
2229 */
2230 public static final int PASSWORD_COMPLEXITY_LOW = 0x10000;
2231
2232 /**
2233 * Constant for {@link #getPasswordComplexity()} and
2234 * {@link #setRequiredPasswordComplexity(int)}.
2235 * Define the medium password complexity band as:
2236 * <ul>
2237 * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
2238 * least 4
2239 * <li>alphabetic, length at least 4
2240 * <li>alphanumeric, length at least 4
2241 * </ul>
2242 *
2243 * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2244 * the exact complexity band the password is in.
2245 * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2246 * band which the password must meet.
2247 *
2248 * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
2249 * @see #PASSWORD_QUALITY_ALPHABETIC
2250 * @see #PASSWORD_QUALITY_ALPHANUMERIC
2251 */
2252 public static final int PASSWORD_COMPLEXITY_MEDIUM = 0x30000;
2253
2254 /**
2255 * Constant for {@link #getPasswordComplexity()} and
2256 * {@link #setRequiredPasswordComplexity(int)}.
2257 * Define the high password complexity band as:
2258 * <ul>
2259 * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
2260 * least 8
2261 * <li>alphabetic, length at least 6
2262 * <li>alphanumeric, length at least 6
2263 * </ul>
2264 *
2265 * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2266 * the exact complexity band the password is in.
2267 * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2268 * band which the password must meet.
2269 *
2270 * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
2271 * @see #PASSWORD_QUALITY_ALPHABETIC
2272 * @see #PASSWORD_QUALITY_ALPHANUMERIC
2273 */
2274 public static final int PASSWORD_COMPLEXITY_HIGH = 0x50000;
2275
2276 /**
2277 * A boolean extra for {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} requesting that only
2278 * device password requirement is enforced during the parent profile password enrolment flow.
2279 * <p> Normally when enrolling password for the parent profile, both the device-wide password
2280 * requirement (requirement set via {@link #getParentProfileInstance(ComponentName)} instance)
2281 * and the profile password requirement are enforced, if the profile currently does not have a
2282 * separate work challenge. By setting this to {@code true}, profile password requirement is
2283 * explicitly disregarded.
2284 *
2285 * @see #isActivePasswordSufficientForDeviceRequirement()
2286 */
2287 public static final String EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY =
2288 "android.app.extra.DEVICE_PASSWORD_REQUIREMENT_ONLY";
2289
2290 /**
2291 * @hide
2292 */
2293 @Retention(RetentionPolicy.SOURCE)
2294 @IntDef(prefix = {"PASSWORD_COMPLEXITY_"}, value = {
2295 PASSWORD_COMPLEXITY_NONE,
2296 PASSWORD_COMPLEXITY_LOW,
2297 PASSWORD_COMPLEXITY_MEDIUM,
2298 PASSWORD_COMPLEXITY_HIGH,
2299 })
2300 public @interface PasswordComplexity {}
2301
2302 /**
2303 * Indicates that nearby streaming is not controlled by policy, which means nearby streaming is
2304 * allowed.
2305 */
2306 public static final int NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY = 0;
2307
2308 /** Indicates that nearby streaming is disabled. */
2309 public static final int NEARBY_STREAMING_DISABLED = 1;
2310
2311 /** Indicates that nearby streaming is enabled. */
2312 public static final int NEARBY_STREAMING_ENABLED = 2;
2313
2314 /**
2315 * Indicates that nearby streaming is enabled only to devices offering a comparable level of
2316 * security, with the same authenticated managed account.
2317 */
2318 public static final int NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY = 3;
2319
2320 /**
2321 * @hide
2322 */
2323 @Retention(RetentionPolicy.SOURCE)
2324 @IntDef(prefix = {"NEARBY_STREAMING_"}, value = {
2325 NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY,
2326 NEARBY_STREAMING_DISABLED,
2327 NEARBY_STREAMING_ENABLED,
2328 NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY,
2329 })
2330 public @interface NearbyStreamingPolicy {}
2331
2332 /**
2333 * Activity action: have the user enter a new password for the parent profile.
2334 * If the intent is launched from within a managed profile, this will trigger
2335 * entering a new password for the parent of the profile. The caller can optionally
2336 * set {@link #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY} to only enforce device-wide
2337 * password requirement. In all other cases the behaviour is identical to
2338 * {@link #ACTION_SET_NEW_PASSWORD}.
2339 */
2340 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2341 public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
2342 = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
2343
2344 /**
2345 * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
2346 * Network logging was enabled and the user tapped the notification.
2347 * <p class="note">This is a protected intent that can only be sent by the system.</p>
2348 * @hide
2349 */
2350 public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
2351 = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
2352
2353 /**
2354 * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
2355 * scopes will be sent in an {@code ArrayList<String>} extra identified by the
2356 * {@link #EXTRA_DELEGATION_SCOPES} key.
2357 *
2358 * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the
2359 * system.</p>
2360 */
2361 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2362 public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
2363 "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
2364
2365 /**
2366 * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
2367 * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
2368 */
2369 public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
2370
2371 /**
2372 * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
2373 * the parent profile to access intents sent from the managed profile.
2374 * That is, when an app in the managed profile calls
2375 * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
2376 * matching activity in the parent profile.
2377 */
2378 public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
2379
2380 /**
2381 * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
2382 * the managed profile to access intents sent from the parent profile.
2383 * That is, when an app in the parent profile calls
2384 * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
2385 * matching activity in the managed profile.
2386 */
2387 public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
2388
2389 /**
2390 * Broadcast action: notify that a new local system update policy has been set by the device
2391 * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
2392 */
2393 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2394 public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
2395 = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
2396
2397 /**
2398 * Broadcast action from ManagedProvisioning to notify that the latest change to
2399 * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
2400 * applied (cross profile intent filters updated). Only usesd for CTS tests.
2401 * @hide
2402 */
2403 @SuppressLint("ActionValue")
2404 @TestApi
2405 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2406 public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
2407 "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
2408
2409 /**
2410 * Broadcast action: notify that a value of {@link Settings.Global#DEVICE_POLICY_CONSTANTS}
2411 * has been changed.
2412 * @hide
2413 */
2414 @SuppressLint("ActionValue")
2415 @TestApi
2416 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2417 public static final String ACTION_DEVICE_POLICY_CONSTANTS_CHANGED =
2418 "android.app.action.DEVICE_POLICY_CONSTANTS_CHANGED";
2419
2420 /**
2421 * Permission policy to prompt user for new permission requests for runtime permissions.
2422 * Already granted or denied permissions are not affected by this.
2423 */
2424 public static final int PERMISSION_POLICY_PROMPT = 0;
2425
2426 /**
2427 * Permission policy to always grant new permission requests for runtime permissions.
2428 * Already granted or denied permissions are not affected by this.
2429 */
2430 public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
2431
2432 /**
2433 * Permission policy to always deny new permission requests for runtime permissions.
2434 * Already granted or denied permissions are not affected by this.
2435 */
2436 public static final int PERMISSION_POLICY_AUTO_DENY = 2;
2437
2438 /**
2439 * Possible policy values for permissions.
2440 *
2441 * @hide
2442 */
2443 @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = {
2444 PERMISSION_GRANT_STATE_DEFAULT,
2445 PERMISSION_GRANT_STATE_GRANTED,
2446 PERMISSION_GRANT_STATE_DENIED
2447 })
2448 @Retention(RetentionPolicy.SOURCE)
2449 public @interface PermissionGrantState {}
2450
2451 /**
2452 * Runtime permission state: The user can manage the permission
2453 * through the UI.
2454 */
2455 public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
2456
2457 /**
2458 * Runtime permission state: The permission is granted to the app
2459 * and the user cannot manage the permission through the UI.
2460 */
2461 public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
2462
2463 /**
2464 * Runtime permission state: The permission is denied to the app
2465 * and the user cannot manage the permission through the UI.
2466 */
2467 public static final int PERMISSION_GRANT_STATE_DENIED = 2;
2468
2469 /**
2470 * Delegation of certificate installation and management. This scope grants access to the
2471 * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
2472 * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
2473 * This scope also grants the ability to read identifiers that the delegating device owner or
2474 * profile owner can obtain. See {@link #getEnrollmentSpecificId()}.
2475 */
2476 public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
2477
2478 /**
2479 * Delegation of application restrictions management. This scope grants access to the
2480 * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
2481 */
2482 public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
2483
2484 /**
2485 * Delegation of application uninstall block. This scope grants access to the
2486 * {@link #setUninstallBlocked} API.
2487 */
2488 public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
2489
2490 /**
2491 * Delegation of permission policy and permission grant state. This scope grants access to the
2492 * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
2493 * and {@link #setPermissionGrantState} APIs.
2494 */
2495 public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
2496
2497 /**
2498 * Delegation of package access state. This scope grants access to the
2499 * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
2500 * {@link #setPackagesSuspended} APIs.
2501 */
2502 public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
2503
2504 /**
2505 * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
2506 * API.
2507 */
2508 public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
2509
2510 /**
2511 * Delegation for installing existing packages. This scope grants access to the
2512 * {@link #installExistingPackage} API.
2513 */
2514 public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
2515 "delegation-install-existing-package";
2516
2517 /**
2518 * Delegation of management of uninstalled packages. This scope grants access to the
2519 * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs.
2520 */
2521 public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
2522 "delegation-keep-uninstalled-packages";
2523
2524 /**
2525 * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and
2526 * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving
2527 * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner or Profile Owner
2528 * will no longer receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback.
2529 * There can be at most one app that has this delegation.
2530 * If another app already had delegated network logging access,
2531 * it will lose the delegation when a new app is delegated.
2532 *
2533 * <p> Device Owner can grant this access since Android 10. Profile Owner of a managed profile
2534 * can grant this access since Android 12.
2535 */
2536 public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
2537
2538 /**
2539 * Grants access to selection of KeyChain certificates on behalf of requesting apps.
2540 * Once granted the app will start receiving
2541 * {@link DelegatedAdminReceiver#onChoosePrivateKeyAlias}. The caller (PO/DO) will
2542 * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2543 * There can be at most one app that has this delegation.
2544 * If another app already had delegated certificate selection access,
2545 * it will lose the delegation when a new app is delegated.
2546 * <p> The delegaetd app can also call {@link #grantKeyPairToApp} and
2547 * {@link #revokeKeyPairFromApp} to directly grant KeyCain keys to other apps.
2548 * <p> Can be granted by Device Owner or Profile Owner.
2549 */
2550 public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
2551
2552 /**
2553 * Grants access to {@link #setSecurityLoggingEnabled}, {@link #isSecurityLoggingEnabled},
2554 * {@link #retrieveSecurityLogs}, and {@link #retrievePreRebootSecurityLogs}. Once granted the
2555 * delegated app will start receiving {@link DelegatedAdminReceiver#onSecurityLogsAvailable}
2556 * callback, and Device owner or Profile Owner will no longer receive the
2557 * {@link DeviceAdminReceiver#onSecurityLogsAvailable} callback. There can be at most one app
2558 * that has this delegation. If another app already had delegated security logging access, it
2559 * will lose the delegation when a new app is delegated.
2560 *
2561 * <p> Can only be granted by Device Owner or Profile Owner of an organization-owned
2562 * managed profile.
2563 */
2564 public static final String DELEGATION_SECURITY_LOGGING = "delegation-security-logging";
2565
2566 /**
2567 * No management for current user in-effect. This is the default.
2568 * @hide
2569 */
2570 @SystemApi
2571 public static final int STATE_USER_UNMANAGED = 0;
2572
2573 /**
2574 * Management partially setup, user setup needs to be completed.
2575 * @hide
2576 */
2577 @SystemApi
2578 public static final int STATE_USER_SETUP_INCOMPLETE = 1;
2579
2580 /**
2581 * Management partially setup, user setup completed.
2582 * @hide
2583 */
2584 @SystemApi
2585 public static final int STATE_USER_SETUP_COMPLETE = 2;
2586
2587 /**
2588 * Management setup and active on current user.
2589 * @hide
2590 */
2591 @SystemApi
2592 public static final int STATE_USER_SETUP_FINALIZED = 3;
2593
2594 /**
2595 * Management partially setup on a managed profile.
2596 * @hide
2597 */
2598 @SystemApi
2599 public static final int STATE_USER_PROFILE_COMPLETE = 4;
2600
2601 /**
2602 * Management setup on a managed profile.
2603 * <p>This is used as an intermediate state after {@link #STATE_USER_PROFILE_COMPLETE} once the
2604 * work profile has been created.
2605 * @hide
2606 */
2607 @SystemApi
2608 public static final int STATE_USER_PROFILE_FINALIZED = 5;
2609
2610 /**
2611 * @hide
2612 */
2613 @IntDef(prefix = { "STATE_USER_" }, value = {
2614 STATE_USER_UNMANAGED,
2615 STATE_USER_SETUP_INCOMPLETE,
2616 STATE_USER_SETUP_COMPLETE,
2617 STATE_USER_SETUP_FINALIZED,
2618 STATE_USER_PROFILE_COMPLETE,
2619 STATE_USER_PROFILE_FINALIZED
2620 })
2621 @Retention(RetentionPolicy.SOURCE)
2622 public @interface UserProvisioningState {}
2623
2624 /**
2625 * Result code for {@link #checkProvisioningPrecondition}.
2626 *
2627 * <p>Unknown error code returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2628 * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}.
2629 *
2630 * @hide
2631 */
2632 @SystemApi
2633 public static final int STATUS_UNKNOWN_ERROR = -1;
2634
2635 /**
2636 * Result code for {@link #checkProvisioningPrecondition}.
2637 *
2638 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2639 * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}
2640 * when provisioning is allowed.
2641 *
2642 * @hide
2643 */
2644 @SystemApi
2645 public static final int STATUS_OK = 0;
2646
2647 /**
2648 * Result code for {@link #checkProvisioningPrecondition}.
2649 *
2650 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the device already has a
2651 * device owner.
2652 *
2653 * @hide
2654 */
2655 @SystemApi
2656 public static final int STATUS_HAS_DEVICE_OWNER = 1;
2657
2658 /**
2659 * Result code for {@link #checkProvisioningPrecondition}.
2660 *
2661 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user has a profile owner
2662 * and for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
2663 *
2664 * @hide
2665 */
2666 @SystemApi
2667 public static final int STATUS_USER_HAS_PROFILE_OWNER = 2;
2668
2669 /**
2670 * Result code for {@link #checkProvisioningPrecondition}.
2671 *
2672 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user isn't running.
2673 *
2674 * @hide
2675 */
2676 @SystemApi
2677 public static final int STATUS_USER_NOT_RUNNING = 3;
2678
2679 /**
2680 * Result code for {@link #checkProvisioningPrecondition}.
2681 *
2682 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the device has already been
2683 * setup and for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
2684 *
2685 * @hide
2686 */
2687 @SystemApi
2688 public static final int STATUS_USER_SETUP_COMPLETED = 4;
2689
2690 /**
2691 * Code used to indicate that the device also has a user other than the system user.
2692 *
2693 * @hide
2694 */
2695 @SystemApi
2696 public static final int STATUS_NONSYSTEM_USER_EXISTS = 5;
2697
2698 /**
2699 * Code used to indicate that device has an account that prevents provisioning.
2700 *
2701 * @hide
2702 */
2703 @SystemApi
2704 public static final int STATUS_ACCOUNTS_NOT_EMPTY = 6;
2705
2706 /**
2707 * Result code for {@link #checkProvisioningPrecondition}.
2708 *
2709 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the user is not a system user.
2710 *
2711 * @hide
2712 */
2713 @SystemApi
2714 public static final int STATUS_NOT_SYSTEM_USER = 7;
2715
2716 /**
2717 * Result code for {@link #checkProvisioningPrecondition}.
2718 *
2719 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2720 * {@link #ACTION_PROVISION_MANAGED_USER} when the device is a watch and is already paired.
2721 *
2722 * @hide
2723 */
2724 @SystemApi
2725 public static final int STATUS_HAS_PAIRED = 8;
2726
2727 /**
2728 * Result code for {@link #checkProvisioningPrecondition}.
2729 *
2730 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
2731 * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
2732 *
2733 * @see {@link PackageManager#FEATURE_MANAGED_USERS}
2734 * @hide
2735 */
2736 @SystemApi
2737 public static final int STATUS_MANAGED_USERS_NOT_SUPPORTED = 9;
2738
2739 /**
2740 * Result code for {@link #checkProvisioningPrecondition}.
2741 *
2742 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user and
2743 * for {@link #ACTION_PROVISION_MANAGED_DEVICE} on devices running headless system user mode
2744 * and the user is a system user.
2745 *
2746 * @hide
2747 */
2748 @SystemApi
2749 public static final int STATUS_SYSTEM_USER = 10;
2750
2751 /**
2752 * Result code for {@link #checkProvisioningPrecondition}.
2753 *
2754 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
2755 * managed profiles.
2756 *
2757 * @hide
2758 */
2759 @SystemApi
2760 public static final int STATUS_CANNOT_ADD_MANAGED_PROFILE = 11;
2761
2762 /**
2763 * Result code for {@link #checkProvisioningPrecondition}.
2764 *
2765 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2766 * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support device
2767 * admins.
2768 *
2769 * @hide
2770 */
2771 @SystemApi
2772 public static final int STATUS_DEVICE_ADMIN_NOT_SUPPORTED = 13;
2773
2774 /**
2775 * TODO (b/137101239): clean up split system user codes
2776 * Result code for {@link #checkProvisioningPrecondition}.
2777 *
2778 * @hide
2779 * @deprecated not used anymore but can't be removed since it's a @TestApi.
2780 */
2781 @Deprecated
2782 @TestApi
2783 public static final int STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
2784
2785 /**
2786 * Result code for {@link #checkProvisioningPrecondition}.
2787 *
2788 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2789 * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support provisioning.
2790 *
2791 * @hide
2792 */
2793 @SystemApi
2794 public static final int STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS = 15;
2795
2796 /**
2797 * Result codes for {@link #checkProvisioningPrecondition} indicating all the provisioning pre
2798 * conditions.
2799 *
2800 * @hide
2801 */
2802 @Retention(RetentionPolicy.SOURCE)
2803 @IntDef(prefix = { "STATUS_" }, value = {
2804 STATUS_UNKNOWN_ERROR, STATUS_OK, STATUS_HAS_DEVICE_OWNER, STATUS_USER_HAS_PROFILE_OWNER,
2805 STATUS_USER_NOT_RUNNING, STATUS_USER_SETUP_COMPLETED, STATUS_NOT_SYSTEM_USER,
2806 STATUS_HAS_PAIRED, STATUS_MANAGED_USERS_NOT_SUPPORTED, STATUS_SYSTEM_USER,
2807 STATUS_CANNOT_ADD_MANAGED_PROFILE, STATUS_DEVICE_ADMIN_NOT_SUPPORTED,
2808 STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER,
2809 STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS
2810 })
2811 public @interface ProvisioningPrecondition {}
2812
2813 /**
2814 * Disable all configurable SystemUI features during LockTask mode. This includes,
2815 * <ul>
2816 * <li>system info area in the status bar (connectivity icons, clock, etc.)
2817 * <li>notifications (including alerts, icons, and the notification shade)
2818 * <li>Home button
2819 * <li>Recents button and UI
2820 * <li>global actions menu (i.e. power button menu)
2821 * <li>keyguard
2822 * </ul>
2823 *
2824 * @see #setLockTaskFeatures(ComponentName, int)
2825 */
2826 public static final int LOCK_TASK_FEATURE_NONE = 0;
2827
2828 /**
2829 * Enable the system info area in the status bar during LockTask mode. The system info area
2830 * usually occupies the right side of the status bar (although this can differ across OEMs). It
2831 * includes all system information indicators, such as date and time, connectivity, battery,
2832 * vibration mode, etc.
2833 *
2834 * @see #setLockTaskFeatures(ComponentName, int)
2835 */
2836 public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
2837
2838 /**
2839 * Enable notifications during LockTask mode. This includes notification icons on the status
2840 * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
2841 * Settings panel remains disabled. This feature flag can only be used in combination with
2842 * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
2843 * throws an {@link IllegalArgumentException} if this feature flag is defined without
2844 * {@link #LOCK_TASK_FEATURE_HOME}.
2845 *
2846 * @see #setLockTaskFeatures(ComponentName, int)
2847 */
2848 public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
2849
2850 /**
2851 * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
2852 * to be registered as the default launcher with
2853 * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
2854 * package needs to be allowlisted for LockTask with
2855 * {@link #setLockTaskPackages(ComponentName, String[])}.
2856 *
2857 * @see #setLockTaskFeatures(ComponentName, int)
2858 */
2859 public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
2860
2861 /**
2862 * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
2863 * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
2864 * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
2865 * {@link IllegalArgumentException} if this feature flag is defined without
2866 * {@link #LOCK_TASK_FEATURE_HOME}.
2867 *
2868 * @see #setLockTaskFeatures(ComponentName, int)
2869 */
2870 public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
2871
2872 /**
2873 * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
2874 * the user long-presses the power button, for example. Note that the user may not be able to
2875 * power off the device if this flag is not set.
2876 *
2877 * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
2878 * called for the first time.
2879 *
2880 * @see #setLockTaskFeatures(ComponentName, int)
2881 */
2882 public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
2883
2884 /**
2885 * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
2886 * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
2887 * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
2888 * credential.
2889 *
2890 * @see #setLockTaskFeatures(ComponentName, int)
2891 */
2892 public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
2893
2894 /**
2895 * Enable blocking of non-allowlisted activities from being started into a locked task.
2896 *
2897 * @see #setLockTaskFeatures(ComponentName, int)
2898 */
2899 public static final int LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK = 1 << 6;
2900
2901 /**
2902 * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
2903 *
2904 * @hide
2905 */
2906 @Retention(RetentionPolicy.SOURCE)
2907 @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
2908 LOCK_TASK_FEATURE_NONE,
2909 LOCK_TASK_FEATURE_SYSTEM_INFO,
2910 LOCK_TASK_FEATURE_NOTIFICATIONS,
2911 LOCK_TASK_FEATURE_HOME,
2912 LOCK_TASK_FEATURE_OVERVIEW,
2913 LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
2914 LOCK_TASK_FEATURE_KEYGUARD,
2915 LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK
2916 })
2917 public @interface LockTaskFeature {}
2918
2919 /**
2920 * Service action: Action for a service that device owner and profile owner can optionally
2921 * own. If a device owner or a profile owner has such a service, the system tries to keep
2922 * a bound connection to it, in order to keep their process always running.
2923 * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
2924 * permission.
2925 */
2926 @SdkConstant(SdkConstantType.SERVICE_ACTION)
2927 public static final String ACTION_DEVICE_ADMIN_SERVICE
2928 = "android.app.action.DEVICE_ADMIN_SERVICE";
2929
2930 /** @hide */
2931 @Retention(RetentionPolicy.SOURCE)
2932 @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
2933 ID_TYPE_BASE_INFO,
2934 ID_TYPE_SERIAL,
2935 ID_TYPE_IMEI,
2936 ID_TYPE_MEID,
2937 ID_TYPE_INDIVIDUAL_ATTESTATION
2938 })
2939 public @interface AttestationIdType {}
2940
2941 /**
2942 * Specifies that the device should attest its manufacturer details. For use with
2943 * {@link #generateKeyPair}.
2944 *
2945 * @see #generateKeyPair
2946 */
2947 public static final int ID_TYPE_BASE_INFO = 1;
2948
2949 /**
2950 * Specifies that the device should attest its serial number. For use with
2951 * {@link #generateKeyPair}.
2952 *
2953 * @see #generateKeyPair
2954 */
2955 public static final int ID_TYPE_SERIAL = 2;
2956
2957 /**
2958 * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
2959 *
2960 * @see #generateKeyPair
2961 */
2962 public static final int ID_TYPE_IMEI = 4;
2963
2964 /**
2965 * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
2966 *
2967 * @see #generateKeyPair
2968 */
2969 public static final int ID_TYPE_MEID = 8;
2970
2971 /**
2972 * Specifies that the device should attest using an individual attestation certificate.
2973 * For use with {@link #generateKeyPair}.
2974 *
2975 * @see #generateKeyPair
2976 */
2977 public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16;
2978
2979 /**
2980 * Service-specific error code for {@link #generateKeyPair}:
2981 * Indicates the call has failed due to StrongBox unavailability.
2982 * @hide
2983 */
2984 public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1;
2985
2986 /**
2987 * Specifies that the calling app should be granted access to the installed credentials
2988 * immediately. Otherwise, access to the credentials will be gated by user approval.
2989 * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2990 *
2991 * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2992 */
2993 public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
2994
2995 /**
2996 * Specifies that a user can select the key via the Certificate Selection prompt.
2997 * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
2998 * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2999 * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
3000 *
3001 * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
3002 */
3003 public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
3004
3005 /**
3006 * Broadcast action: sent when the profile owner is set, changed or cleared.
3007 *
3008 * This broadcast is sent only to the user managed by the new profile owner.
3009 * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
3010 */
3011 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3012 public static final String ACTION_PROFILE_OWNER_CHANGED =
3013 "android.app.action.PROFILE_OWNER_CHANGED";
3014
3015 /** @hide */
3016 @Retention(RetentionPolicy.SOURCE)
3017 @IntDef(prefix = {"PRIVATE_DNS_MODE_"}, value = {
3018 PRIVATE_DNS_MODE_UNKNOWN,
3019 PRIVATE_DNS_MODE_OFF,
3020 PRIVATE_DNS_MODE_OPPORTUNISTIC,
3021 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME
3022 })
3023 public @interface PrivateDnsMode {}
3024
3025 /**
3026 * Specifies that the Private DNS setting is in an unknown state.
3027 */
3028 public static final int PRIVATE_DNS_MODE_UNKNOWN = 0;
3029
3030 /**
3031 * Specifies that Private DNS was turned off completely.
3032 */
3033 public static final int PRIVATE_DNS_MODE_OFF = 1;
3034
3035 /**
3036 * Specifies that the device owner requested opportunistic DNS over TLS
3037 */
3038 public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2;
3039
3040 /**
3041 * Specifies that the device owner configured a specific host to use for Private DNS.
3042 */
3043 public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3;
3044
3045 /**
3046 * Callback used in {@link #installSystemUpdate} to indicate that there was an error while
3047 * trying to install an update.
3048 */
3049 public abstract static class InstallSystemUpdateCallback {
3050 /** Represents an unknown error while trying to install an update. */
3051 public static final int UPDATE_ERROR_UNKNOWN = 1;
3052
3053 /** Represents the update file being intended for different OS version. */
3054 public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
3055
3056 /**
3057 * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
3058 * compression method is used.
3059 */
3060 public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
3061
3062 /** Represents that the file could not be found. */
3063 public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4;
3064
3065 /** Represents the battery being too low to apply an update. */
3066 public static final int UPDATE_ERROR_BATTERY_LOW = 5;
3067
3068 /**
3069 * Method invoked when there was an error while installing an update.
3070 *
3071 * <p>The given error message is not intended to be user-facing. It is intended to be
3072 * reported back to the IT admin to be read.
3073 */
3074 public void onInstallUpdateError(
3075 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) {
3076 }
3077 }
3078
3079 /**
3080 * @hide
3081 */
3082 @IntDef(prefix = { "UPDATE_ERROR_" }, value = {
3083 InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
3084 InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
3085 InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
3086 InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
3087 InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
3088 })
3089 @Retention(RetentionPolicy.SOURCE)
3090 public @interface InstallUpdateCallbackErrorConstants {}
3091
3092 /**
3093 * The selected mode has been set successfully. If the mode is
3094 * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid
3095 * and reachable.
3096 */
3097 public static final int PRIVATE_DNS_SET_NO_ERROR = 0;
3098
3099 /**
3100 * If the {@code privateDnsHost} provided was of a valid hostname but that host was found
3101 * to not support DNS-over-TLS.
3102 */
3103 public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1;
3104
3105 /**
3106 * General failure to set the Private DNS mode, not due to one of the reasons listed above.
3107 */
3108 public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2;
3109
3110 /**
3111 * @hide
3112 */
3113 @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = {
3114 PRIVATE_DNS_SET_NO_ERROR,
3115 PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING,
3116 PRIVATE_DNS_SET_ERROR_FAILURE_SETTING
3117 })
3118 @Retention(RetentionPolicy.SOURCE)
3119 public @interface PrivateDnsModeErrorCodes {}
3120
3121 /**
3122 * Activity action: Starts the administrator to get the mode for the provisioning.
3123 * This intent may contain the following extras:
3124 * <ul>
3125 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li>
3126 * <li>{@link #EXTRA_PROVISIONING_IMEI}</li>
3127 * <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li>
3128 * <li>{@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}</li>
3129 * <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT}</li>
3130 * </ul>
3131 *
3132 * <p>The target activity should return one of the following values in
3133 * {@link #EXTRA_PROVISIONING_MODE} as result:
3134 * <ul>
3135 * <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
3136 * <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
3137 * </ul>
3138 *
3139 * <p>If performing fully-managed device provisioning and the admin app desires to show its
3140 * own education screens, the target activity can additionally return
3141 * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>.
3142 *
3143 * <p>The target activity may also return the account that needs to be migrated from primary
3144 * user to managed profile in case of a profile owner provisioning in
3145 * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result.
3146 *
3147 * <p>The target activity may also include the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}
3148 * extra in the intent result. The values of this {@link android.os.PersistableBundle} will be
3149 * sent as an intent extra of the same name to the {@link #ACTION_ADMIN_POLICY_COMPLIANCE}
3150 * activity, along with the values of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra
3151 * that are already supplied to this activity.
3152 *
3153 * <p>Other extras the target activity may include in the intent result:
3154 * <ul>
3155 * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li>
3156 * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}</li>
3157 * <li>{@link #EXTRA_PROVISIONING_KEEP_SCREEN_ON}</li>
3158 * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION} for work profile
3159 * provisioning</li>
3160 * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED} for work profile
3161 * provisioning</li>
3162 * <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} for fully-managed
3163 * device provisioning</li>
3164 * <li>{@link #EXTRA_PROVISIONING_LOCALE} for fully-managed device provisioning</li>
3165 * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} for fully-managed device provisioning</li>
3166 * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE} for fully-managed device provisioning</li>
3167 * </ul>
3168 *
3169 * @see #ACTION_ADMIN_POLICY_COMPLIANCE
3170 */
3171 public static final String ACTION_GET_PROVISIONING_MODE =
3172 "android.app.action.GET_PROVISIONING_MODE";
3173
3174 /**
3175 * A string extra holding the IMEI (International Mobile Equipment Identity) of the device.
3176 */
3177 public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI";
3178
3179 /**
3180 * A string extra holding the serial number of the device.
3181 */
3182 public static final String EXTRA_PROVISIONING_SERIAL_NUMBER =
3183 "android.app.extra.PROVISIONING_SERIAL_NUMBER";
3184
3185 /**
3186 * An intent extra holding the provisioning mode returned by the administrator.
3187 * The value of this extra must be one of the values provided in {@link
3188 * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}, which is provided as an intent extra to
3189 * the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity.
3190 *
3191 * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
3192 * @see #PROVISIONING_MODE_MANAGED_PROFILE
3193 */
3194 public static final String EXTRA_PROVISIONING_MODE =
3195 "android.app.extra.PROVISIONING_MODE";
3196
3197 /**
3198 * An integer extra indication what provisioning modes should be available for the admin app
3199 * to pick.
3200 *
3201 * <p>The default value is {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}.
3202 *
3203 * <p>The value of this extra will determine the contents of the {@link
3204 * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array that is passed to the admin app as an
3205 * extra to its {@link #ACTION_GET_PROVISIONING_MODE} activity.
3206 *
3207 * <p>If one of the possible admin app choices is a personally-owned work profile, then the
3208 * IMEI and serial number will not be passed to the admin app's {@link
3209 * #ACTION_GET_PROVISIONING_MODE} activity via the {@link #EXTRA_PROVISIONING_IMEI} and {@link
3210 * #EXTRA_PROVISIONING_SERIAL_NUMBER} respectively.
3211 *
3212 * <p>The allowed flag combinations are:
3213 * <ul>
3214 * <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}</li>
3215 * <li>{@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
3216 * <li>{@link #FLAG_SUPPORTED_MODES_DEVICE_OWNER}</li>
3217 * <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}
3218 * | {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
3219 * </ul>
3220 *
3221 * <p>This extra is only respected when provided alongside the {@link
3222 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3223 *
3224 * @see #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED
3225 * @see #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED
3226 * @see #FLAG_SUPPORTED_MODES_DEVICE_OWNER
3227 * @hide
3228 */
3229 @SystemApi
3230 public static final String EXTRA_PROVISIONING_SUPPORTED_MODES =
3231 "android.app.extra.PROVISIONING_SUPPORTED_MODES";
3232
3233 /**
3234 * A boolean extra which determines whether to skip the ownership disclaimer screen during the
3235 * provisioning flow. The default value is {@code false}.
3236 *
3237 * If the value is {@code true}, the provisioning initiator must display a device ownership
3238 * disclaimer screen similar to that provided in AOSP.
3239 *
3240 * <p>This extra is only respected when provided alongside the {@link
3241 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3242 *
3243 * @hide
3244 */
3245 @SystemApi
3246 public static final String EXTRA_PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER =
3247 "android.app.extra.PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER";
3248
3249 /**
3250 * An {@link ArrayList} of {@link Integer} extra specifying the allowed provisioning modes.
3251 * <p>This extra will be passed to the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
3252 * activity, whose result intent must contain {@link #EXTRA_PROVISIONING_MODE} set to one of
3253 * the values in this array.
3254 * <p>If the value set to {@link #EXTRA_PROVISIONING_MODE} is not in the array,
3255 * provisioning will fail.
3256 * @see #PROVISIONING_MODE_MANAGED_PROFILE
3257 * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
3258 */
3259 public static final String EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES =
3260 "android.app.extra.PROVISIONING_ALLOWED_PROVISIONING_MODES";
3261
3262 /**
3263 * The provisioning mode for fully managed device.
3264 */
3265 public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1;
3266
3267 /**
3268 * The provisioning mode for managed profile.
3269 */
3270 public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2;
3271
3272 /**
3273 * The provisioning mode for a managed profile on a personal device.
3274 * <p>This mode is only available when the provisioning initiator has explicitly instructed the
3275 * provisioning flow to support managed profile on a personal device provisioning. In that case,
3276 * {@link #PROVISIONING_MODE_MANAGED_PROFILE} corresponds to an organization-owned managed
3277 * profile, whereas this constant corresponds to a personally-owned managed profile.
3278 *
3279 * @see #EXTRA_PROVISIONING_MODE
3280 */
3281 public static final int PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE = 3;
3282
3283 /**
3284 * A {@code boolean} flag that indicates whether the provisioning flow should return before
3285 * starting the admin app's {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. The default value
3286 * is {@code true}.
3287 *
3288 * <p>If this extra is set to {@code true}, then when the provisioning flow returns back to the
3289 * provisioning initiator, provisioning will not be complete. The provisioning initiator can
3290 * use this opportunity to do its own preparatory steps prior to the launch of the admin app's
3291 * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. It is the responsibility of the
3292 * provisioning initiator to ensure that the provisioning flow is then resumed and completed.
3293 *
3294 * <p>If this extra is set to {@code false}, then when the provisioning flow returns back to
3295 * the provisioning initiator, provisioning will be complete. Note that device owner
3296 * provisioning is not currently supported for the this scenario.
3297 *
3298 * <p>This extra is only respected when provided alongside the {@link
3299 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3300 *
3301 * @hide
3302 */
3303 @SystemApi
3304 public static final String EXTRA_PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE =
3305 "android.app.extra.PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE";
3306
3307 /**
3308 * A {@code boolean} flag that indicates whether the screen should be on throughout the
3309 * provisioning flow.
3310 *
3311 * <p>The default value is {@code false}.
3312 *
3313 * <p>This extra can either be passed as an extra to the {@link
3314 * #ACTION_PROVISION_MANAGED_PROFILE} intent, or it can be returned by the
3315 * admin app when performing the admin-integrated provisioning flow as a result of the
3316 * {@link #ACTION_GET_PROVISIONING_MODE} activity.
3317 */
3318 public static final String EXTRA_PROVISIONING_KEEP_SCREEN_ON =
3319 "android.app.extra.PROVISIONING_KEEP_SCREEN_ON";
3320
3321 /**
3322 * Activity action: Starts the administrator to show policy compliance for the provisioning.
3323 * This action is used any time that the administrator has an opportunity to show policy
3324 * compliance before the end of setup wizard. This could happen as part of the admin-integrated
3325 * provisioning flow (in which case this gets sent after {@link #ACTION_GET_PROVISIONING_MODE}),
3326 * or it could happen during provisioning finalization if the administrator supports
3327 * finalization during setup wizard.
3328 *
3329 * <p>Intents with this action may also be supplied with the {@link
3330 * #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra.
3331 *
3332 * @see #ACTION_GET_PROVISIONING_MODE
3333 */
3334 public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
3335 "android.app.action.ADMIN_POLICY_COMPLIANCE";
3336
3337 /**
3338 * Activity action: Starts the device policy management role holder updater.
3339 *
3340 * <p>The activity must handle the device policy management role holder update and set the
3341 * intent result. This can include {@link Activity#RESULT_OK} if the update was successful,
3342 * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if
3343 * it encounters a problem that may be solved by relaunching it again, {@link
3344 * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED} if role holder
3345 * provisioning is disabled, or {@link
3346 * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if it encounters
3347 * any other problem that will not be solved by relaunching it again.
3348 *
3349 * <p>If this activity has additional internal conditions which are not met, it should return
3350 * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR}.
3351 *
3352 * @hide
3353 */
3354 @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
3355 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3356 @SystemApi
3357 public static final String ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER =
3358 "android.app.action.UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER";
3359
3360 /**
3361 * Result code that can be returned by the {@link
3362 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem
3363 * that may be solved by relaunching it again.
3364 *
3365 * @hide
3366 */
3367 @SystemApi
3368 public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR =
3369 1;
3370
3371 /**
3372 * Result code that can be returned by the {@link
3373 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem that
3374 * will not be solved by relaunching it again.
3375 *
3376 * @hide
3377 */
3378 @SystemApi
3379 public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR =
3380 2;
3381
3382 /**
3383 * Result code that can be returned by the {@link
3384 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if role holder provisioning
3385 * is disabled.
3386 *
3387 * @hide
3388 */
3389 @SystemApi
3390 public static final int
3391 RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED = 3;
3392
3393 /**
3394 * An {@code int} extra that specifies one of {@link
3395 * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING} or {@link
3396 * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING}.
3397 *
3398 * <p>The failure strategy specifies how the platform should handle a failed device policy
3399 * management role holder update via {@link
3400 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} when {@link
3401 * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is not set or set to {@code false}.
3402 *
3403 * <p>This extra may be supplied as part of the {@link
3404 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} result intent.
3405 *
3406 * <p>Default value is {@link #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING}.
3407 *
3408 * @hide
3409 */
3410 public static final String EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY =
3411 "android.app.extra.ROLE_HOLDER_UPDATE_FAILURE_STRATEGY";
3412
3413 /**
3414 * Possible values for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY}.
3415 *
3416 * @hide
3417 */
3418 @IntDef(prefix = { "ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_" }, value = {
3419 ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING,
3420 ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING
3421 })
3422 @Retention(RetentionPolicy.SOURCE)
3423 public @interface RoleHolderUpdateFailureStrategy {}
3424
3425 /**
3426 * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon
3427 * failure to update the role holder, provisioning should fail.
3428 *
3429 * @hide
3430 */
3431 public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING = 1;
3432
3433 /**
3434 * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon
3435 * failure to update the role holder, provisioning should fallback to be platform-driven.
3436 *
3437 * @hide
3438 */
3439 public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING =
3440 2;
3441
3442 /**
3443 * An {@code int} extra which contains the result code of the last attempt to update
3444 * the device policy management role holder via {@link
3445 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}.
3446 *
3447 * <p>This extra is provided to the device policy management role holder via either {@link
3448 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
3449 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} when started after the role holder
3450 * had previously returned {@link #RESULT_UPDATE_ROLE_HOLDER}.
3451 *
3452 * <p>If the role holder update had failed, the role holder can use the value of this extra to
3453 * make a decision whether to fail the provisioning flow or to carry on with the older version
3454 * of the role holder.
3455 *
3456 * <p>Possible values can be:
3457 * <ul>
3458 * <li>{@link Activity#RESULT_OK} if the update was successful
3459 * <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if it
3460 * encounters a problem that may be solved by relaunching it again.
3461 * <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if
3462 * it encounters a problem that will not be solved by relaunching it again.
3463 * <li>Any other value returned by {@link
3464 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}
3465 * </ul>
3466 *
3467 * @hide
3468 */
3469 @SystemApi
3470 public static final String EXTRA_ROLE_HOLDER_UPDATE_RESULT_CODE =
3471 "android.app.extra.ROLE_HOLDER_UPDATE_RESULT_CODE";
3472
3473 /**
3474 * An {@link Intent} extra which resolves to a custom user consent screen.
3475 *
3476 * <p>If this extra is provided to the device policy management role holder via either {@link
3477 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
3478 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE}, the device policy management role holder must
3479 * launch this intent which shows the custom user consent screen, replacing its own standard
3480 * consent screen.
3481 *
3482 * <p>If this extra is provided, it is the responsibility of the intent handler to show the
3483 * list of disclaimers which are normally shown by the standard consent screen:
3484 * <ul>
3485 * <li>Disclaimers set by the IT admin via the {@link #EXTRA_PROVISIONING_DISCLAIMERS}
3486 * provisioning extra</li>
3487 * <li>For fully-managed device provisioning, disclaimers defined in system apps via the
3488 * {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER} and {@link
3489 * #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} metadata in their manifests</li>
3490 * <li>General disclaimer relevant to the provisioning mode</li>
3491 * </ul>
3492 *
3493 * <p>When this {@link Intent} is started, the following intent extras will be supplied:
3494 * <ul>
3495 * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li>
3496 * <li>{@link #EXTRA_PROVISIONING_MODE}</li>
3497 * <li>{@link #EXTRA_PROVISIONING_LOCALE}</li>
3498 * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME}</li>
3499 * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}</li>
3500 * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}</li>
3501 * </ul>
3502 *
3503 * <p>If the custom consent screens are granted by the user {@link Activity#RESULT_OK} is
3504 * returned, otherwise {@link Activity#RESULT_CANCELED} is returned. The device policy
3505 * management role holder should ensure that the provisioning flow terminates immediately if
3506 * consent is not granted by the user.
3507 *
3508 * @hide
3509 */
3510 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3511 @SystemApi
3512 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT =
3513 "android.app.extra.PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT";
3514
3515 /**
3516 * Activity action: attempts to establish network connection
3517 *
3518 * <p>This intent can be accompanied by any of the relevant provisioning extras related to
3519 * network connectivity, such as:
3520 * <ul>
3521 * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}</li>
3522 * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN}</li>
3523 * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}</li>
3524 * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}</li>
3525 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}</li>
3526 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT}</li>
3527 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}</li>
3528 * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}</li>
3529 * <li>{@code #EXTRA_PROVISIONING_WIFI_EAP_METHOD}</li>
3530 * <li>{@code #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}</li>
3531 * <li>{@code #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}</li>
3532 * <li>{@code #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}</li>
3533 * <li>{@code #EXTRA_PROVISIONING_WIFI_IDENTITY}</li>
3534 * <li>{@code #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}</li>
3535 * <li>{@code #EXTRA_PROVISIONING_WIFI_DOMAIN}</li>
3536 * </ul>
3537 *
3538 * <p>If there are provisioning extras related to network connectivity, this activity
3539 * attempts to connect to the specified network. Otherwise it prompts the end-user to connect.
3540 *
3541 * <p>This activity is meant to be started by the provisioning initiator prior to starting
3542 * {@link #ACTION_PROVISION_MANAGED_PROFILE} or {@link
3543 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
3544 *
3545 * <p>Note that network connectivity is still also handled when provisioning via {@link
3546 * #ACTION_PROVISION_MANAGED_PROFILE} or {@link
3547 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}. {@link
3548 * #ACTION_ESTABLISH_NETWORK_CONNECTION} should only be used in cases when the provisioning
3549 * initiator would like to do some additional logic after the network connectivity step and
3550 * before the start of provisioning.
3551 *
3552 * If network connection is established, {@link Activity#RESULT_OK} will be returned. Otherwise
3553 * the result will be {@link Activity#RESULT_CANCELED}.
3554 *
3555 * @hide
3556 */
3557 @RequiresPermission(android.Manifest.permission.DISPATCH_PROVISIONING_MESSAGE)
3558 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3559 @SystemApi
3560 public static final String ACTION_ESTABLISH_NETWORK_CONNECTION =
3561 "android.app.action.ESTABLISH_NETWORK_CONNECTION";
3562
3563 /**
3564 * Maximum supported password length. Kind-of arbitrary.
3565 * @hide
3566 */
3567 public static final int MAX_PASSWORD_LENGTH = 16;
3568
3569 /**
3570 * Service Action: Service implemented by a device owner or profile owner supervision app to
3571 * provide a secondary lockscreen.
3572 * @hide
3573 */
3574 @SystemApi
3575 public static final String ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE =
3576 "android.app.action.BIND_SECONDARY_LOCKSCREEN_SERVICE";
3577
3578 /**
3579 * Return value for {@link #getPersonalAppsSuspendedReasons} when personal apps are not
3580 * suspended.
3581 */
3582 public static final int PERSONAL_APPS_NOT_SUSPENDED = 0;
3583
3584 /**
3585 * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal
3586 * apps are suspended by an admin explicitly via {@link #setPersonalAppsSuspended}.
3587 */
3588 public static final int PERSONAL_APPS_SUSPENDED_EXPLICITLY = 1 << 0;
3589
3590 /**
3591 * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal apps are
3592 * suspended by framework because managed profile was off for longer than allowed by policy.
3593 * @see #setManagedProfileMaximumTimeOff
3594 */
3595 public static final int PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT = 1 << 1;
3596
3597 /**
3598 * @hide
3599 */
3600 @IntDef(flag = true, prefix = { "PERSONAL_APPS_" }, value = {
3601 PERSONAL_APPS_NOT_SUSPENDED,
3602 PERSONAL_APPS_SUSPENDED_EXPLICITLY,
3603 PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT
3604 })
3605 @Retention(RetentionPolicy.SOURCE)
3606 public @interface PersonalAppsSuspensionReason {}
3607
3608 /**
3609 * The default device owner type for a managed device.
3610 *
3611 * @hide
3612 */
3613 @TestApi
3614 public static final int DEVICE_OWNER_TYPE_DEFAULT = 0;
3615
3616 /**
3617 * The device owner type for a financed device.
3618 *
3619 * @hide
3620 */
3621 @TestApi
3622 public static final int DEVICE_OWNER_TYPE_FINANCED = 1;
3623
3624 /**
3625 * Different device owner types for a managed device.
3626 *
3627 * @hide
3628 */
3629 @Retention(RetentionPolicy.SOURCE)
3630 @IntDef(prefix = { "DEVICE_OWNER_TYPE_" }, value = {
3631 DEVICE_OWNER_TYPE_DEFAULT,
3632 DEVICE_OWNER_TYPE_FINANCED
3633 })
3634 public @interface DeviceOwnerType {}
3635
3636 /** @hide */
3637 @TestApi
3638 public static final int OPERATION_LOCK_NOW = 1;
3639 /** @hide */
3640 @TestApi
3641 public static final int OPERATION_SWITCH_USER = 2;
3642 /** @hide */
3643 @TestApi
3644 public static final int OPERATION_START_USER_IN_BACKGROUND = 3;
3645 /** @hide */
3646 @TestApi
3647 public static final int OPERATION_STOP_USER = 4;
3648 /** @hide */
3649 @TestApi
3650 public static final int OPERATION_CREATE_AND_MANAGE_USER = 5;
3651 /** @hide */
3652 @TestApi
3653 public static final int OPERATION_REMOVE_USER = 6;
3654 /** @hide */
3655 @TestApi
3656 public static final int OPERATION_REBOOT = 7;
3657 /** @hide */
3658 @TestApi
3659 public static final int OPERATION_WIPE_DATA = 8;
3660 /** @hide */
3661 @TestApi
3662 public static final int OPERATION_LOGOUT_USER = 9;
3663 /** @hide */
3664 @TestApi
3665 public static final int OPERATION_SET_USER_RESTRICTION = 10;
3666 /** @hide */
3667 @TestApi
3668 public static final int OPERATION_SET_SYSTEM_SETTING = 11;
3669 /** @hide */
3670 @TestApi
3671 public static final int OPERATION_SET_KEYGUARD_DISABLED = 12;
3672 /** @hide */
3673 @TestApi
3674 public static final int OPERATION_SET_STATUS_BAR_DISABLED = 13;
3675 /** @hide */
3676 @TestApi
3677 public static final int OPERATION_SET_SYSTEM_UPDATE_POLICY = 14;
3678 /** @hide */
3679 @TestApi
3680 public static final int OPERATION_SET_APPLICATION_HIDDEN = 15;
3681 /** @hide */
3682 @TestApi
3683 public static final int OPERATION_SET_APPLICATION_RESTRICTIONS = 16;
3684 /** @hide */
3685 @TestApi
3686 public static final int OPERATION_SET_KEEP_UNINSTALLED_PACKAGES = 17;
3687 /** @hide */
3688 @TestApi
3689 public static final int OPERATION_SET_LOCK_TASK_FEATURES = 18;
3690 /** @hide */
3691 @TestApi
3692 public static final int OPERATION_SET_LOCK_TASK_PACKAGES = 19;
3693 /** @hide */
3694 @TestApi
3695 public static final int OPERATION_SET_PACKAGES_SUSPENDED = 20;
3696 /** @hide */
3697 @TestApi
3698 public static final int OPERATION_SET_TRUST_AGENT_CONFIGURATION = 21;
3699 /** @hide */
3700 @TestApi
3701 public static final int OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES = 22;
3702 /** @hide */
3703 @TestApi
3704 public static final int OPERATION_CLEAR_APPLICATION_USER_DATA = 23;
3705 /** @hide */
3706 @TestApi
3707 public static final int OPERATION_INSTALL_CA_CERT = 24;
3708 /** @hide */
3709 @TestApi
3710 public static final int OPERATION_INSTALL_KEY_PAIR = 25;
3711 /** @hide */
3712 @TestApi
3713 public static final int OPERATION_INSTALL_SYSTEM_UPDATE = 26;
3714 /** @hide */
3715 @TestApi
3716 public static final int OPERATION_REMOVE_ACTIVE_ADMIN = 27;
3717 /** @hide */
3718 @TestApi
3719 public static final int OPERATION_REMOVE_KEY_PAIR = 28;
3720 /** @hide */
3721 @TestApi
3722 public static final int OPERATION_REQUEST_BUGREPORT = 29;
3723 /** @hide */
3724 @TestApi
3725 public static final int OPERATION_SET_ALWAYS_ON_VPN_PACKAGE = 30;
3726 /** @hide */
3727 @TestApi
3728 public static final int OPERATION_SET_CAMERA_DISABLED = 31;
3729 /** @hide */
3730 @TestApi
3731 public static final int OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY = 32;
3732 /** @hide */
3733 @TestApi
3734 public static final int OPERATION_SET_GLOBAL_PRIVATE_DNS = 33;
3735 /** @hide */
3736 @TestApi
3737 public static final int OPERATION_SET_LOGOUT_ENABLED = 34;
3738 /** @hide */
3739 @TestApi
3740 public static final int OPERATION_SET_MASTER_VOLUME_MUTED = 35;
3741 /** @hide */
3742 @TestApi
3743 public static final int OPERATION_SET_OVERRIDE_APNS_ENABLED = 36;
3744 /** @hide */
3745 @TestApi
3746 public static final int OPERATION_SET_PERMISSION_GRANT_STATE = 37;
3747 /** @hide */
3748 @TestApi
3749 public static final int OPERATION_SET_PERMISSION_POLICY = 38;
3750 /** @hide */
3751 @TestApi
3752 public static final int OPERATION_SET_RESTRICTIONS_PROVIDER = 39;
3753 /** @hide */
3754 @TestApi
3755 public static final int OPERATION_UNINSTALL_CA_CERT = 40;
3756
3757 private static final String PREFIX_OPERATION = "OPERATION_";
3758
3759 /** @hide */
3760 @IntDef(prefix = PREFIX_OPERATION, value = {
3761 OPERATION_LOCK_NOW,
3762 OPERATION_SWITCH_USER,
3763 OPERATION_START_USER_IN_BACKGROUND,
3764 OPERATION_STOP_USER,
3765 OPERATION_CREATE_AND_MANAGE_USER,
3766 OPERATION_REMOVE_USER,
3767 OPERATION_REBOOT,
3768 OPERATION_WIPE_DATA,
3769 OPERATION_LOGOUT_USER,
3770 OPERATION_SET_USER_RESTRICTION,
3771 OPERATION_SET_SYSTEM_SETTING,
3772 OPERATION_SET_KEYGUARD_DISABLED,
3773 OPERATION_SET_STATUS_BAR_DISABLED,
3774 OPERATION_SET_SYSTEM_UPDATE_POLICY,
3775 OPERATION_SET_APPLICATION_HIDDEN,
3776 OPERATION_SET_APPLICATION_RESTRICTIONS,
3777 OPERATION_SET_KEEP_UNINSTALLED_PACKAGES,
3778 OPERATION_SET_LOCK_TASK_FEATURES,
3779 OPERATION_SET_LOCK_TASK_PACKAGES,
3780 OPERATION_SET_PACKAGES_SUSPENDED,
3781 OPERATION_SET_TRUST_AGENT_CONFIGURATION,
3782 OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES,
3783 OPERATION_CLEAR_APPLICATION_USER_DATA,
3784 OPERATION_INSTALL_CA_CERT,
3785 OPERATION_INSTALL_KEY_PAIR,
3786 OPERATION_INSTALL_SYSTEM_UPDATE,
3787 OPERATION_REMOVE_ACTIVE_ADMIN,
3788 OPERATION_REMOVE_KEY_PAIR,
3789 OPERATION_REQUEST_BUGREPORT,
3790 OPERATION_SET_ALWAYS_ON_VPN_PACKAGE,
3791 OPERATION_SET_CAMERA_DISABLED,
3792 OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY,
3793 OPERATION_SET_GLOBAL_PRIVATE_DNS,
3794 OPERATION_SET_LOGOUT_ENABLED,
3795 OPERATION_SET_MASTER_VOLUME_MUTED,
3796 OPERATION_SET_OVERRIDE_APNS_ENABLED,
3797 OPERATION_SET_PERMISSION_GRANT_STATE,
3798 OPERATION_SET_PERMISSION_POLICY,
3799 OPERATION_SET_RESTRICTIONS_PROVIDER,
3800 OPERATION_UNINSTALL_CA_CERT
3801 })
3802 @Retention(RetentionPolicy.SOURCE)
3803 public static @interface DevicePolicyOperation {
3804 }
3805
3806 /** @hide */
3807 @TestApi
3808 @NonNull
3809 public static String operationToString(@DevicePolicyOperation int operation) {
3810 return DebugUtils.constantToString(DevicePolicyManager.class, PREFIX_OPERATION, operation);
3811 }
3812
3813 private static final String PREFIX_OPERATION_SAFETY_REASON = "OPERATION_SAFETY_REASON_";
3814
3815 /** @hide */
3816 @IntDef(prefix = PREFIX_OPERATION_SAFETY_REASON, value = {
3817 OPERATION_SAFETY_REASON_NONE,
3818 OPERATION_SAFETY_REASON_DRIVING_DISTRACTION
3819 })
3820 @Retention(RetentionPolicy.SOURCE)
3821 public static @interface OperationSafetyReason {
3822 }
3823
3824 /** @hide */
3825 @TestApi
3826 public static final int OPERATION_SAFETY_REASON_NONE = -1;
3827
3828 /**
3829 * Indicates that a {@link UnsafeStateException} was thrown because the operation would distract
3830 * the driver of the vehicle.
3831 */
3832 public static final int OPERATION_SAFETY_REASON_DRIVING_DISTRACTION = 1;
3833
3834 /**
3835 * Broadcast action: notify system apps (e.g. settings, SysUI, etc) that the device management
3836 * resources with IDs {@link #EXTRA_RESOURCE_IDS} has been updated, the updated resources can be
3837 * retrieved using {@link DevicePolicyResourcesManager#getDrawable} and
3838 * {@link DevicePolicyResourcesManager#getString}.
3839 *
3840 * <p>This broadcast is sent to registered receivers only.
3841 *
3842 * <p> {@link #EXTRA_RESOURCE_TYPE} will be included to identify the type of resource being
3843 * updated.
3844 */
3845 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3846 public static final String ACTION_DEVICE_POLICY_RESOURCE_UPDATED =
3847 "android.app.action.DEVICE_POLICY_RESOURCE_UPDATED";
3848
3849 /**
3850 * An {@code int} extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate the type
3851 * of the resource being updated, the type can be {@link #EXTRA_RESOURCE_TYPE_DRAWABLE} or
3852 * {@link #EXTRA_RESOURCE_TYPE_STRING}
3853 */
3854 public static final String EXTRA_RESOURCE_TYPE =
3855 "android.app.extra.RESOURCE_TYPE";
3856
3857 /**
3858 * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type
3859 * {@link Drawable} is being updated.
3860 */
3861 public static final int EXTRA_RESOURCE_TYPE_DRAWABLE = 1;
3862
3863 /**
3864 * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type
3865 * {@link String} is being updated.
3866 */
3867 public static final int EXTRA_RESOURCE_TYPE_STRING = 2;
3868
3869 /**
3870 * An integer array extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate which
3871 * resource IDs (see {@link DevicePolicyResources.Drawables} and
3872 * {@link DevicePolicyResources.Strings}) have been updated.
3873 */
3874 public static final String EXTRA_RESOURCE_IDS =
3875 "android.app.extra.RESOURCE_IDS";
3876
3877 /**
3878 * This object is a single place to tack on invalidation and disable calls. All
3879 * binder caches in this class derive from this Config, so all can be invalidated or
3880 * disabled through this Config.
3881 */
3882 private static final IpcDataCache.Config sDpmCaches =
3883 new IpcDataCache.Config(8, IpcDataCache.MODULE_SYSTEM, "DevicePolicyManagerCaches");
3884
3885 /** @hide */
3886 public static void invalidateBinderCaches() {
3887 sDpmCaches.invalidateCache();
3888 }
3889
3890 /** @hide */
3891 public static void disableLocalCaches() {
3892 sDpmCaches.disableAllForCurrentProcess();
3893 }
3894
3895 /** @hide */
3896 @NonNull
3897 @TestApi
3898 public static String operationSafetyReasonToString(@OperationSafetyReason int reason) {
3899 return DebugUtils.constantToString(DevicePolicyManager.class,
3900 PREFIX_OPERATION_SAFETY_REASON, reason);
3901 }
3902
3903 /** @hide */
3904 public static boolean isValidOperationSafetyReason(@OperationSafetyReason int reason) {
3905 return reason == OPERATION_SAFETY_REASON_DRIVING_DISTRACTION;
3906 }
3907
3908 /**
3909 * Checks if it's safe to run operations that can be affected by the given {@code reason}.
3910 *
3911 * <p><b>Note:</b> notice that the operation safety state might change between the time this
3912 * method returns and the operation's method is called, so calls to the latter could still throw
3913 * a {@link UnsafeStateException} even when this method returns {@code true}.
3914 *
3915 * @param reason currently, only supported reason is
3916 * {@link #OPERATION_SAFETY_REASON_DRIVING_DISTRACTION}.
3917 *
3918 * @return whether it's safe to run operations that can be affected by the given {@code reason}.
3919 */
3920 // TODO(b/173541467): should it throw SecurityException if caller is not admin?
3921 public boolean isSafeOperation(@OperationSafetyReason int reason) {
3922 throwIfParentInstance("isSafeOperation");
3923 if (mService == null) return false;
3924
3925 try {
3926 return mService.isSafeOperation(reason);
3927 } catch (RemoteException e) {
3928 throw e.rethrowFromSystemServer();
3929 }
3930 }
3931
3932 /**
3933 * Acknoledges that the new managed user disclaimer was viewed by the (human) user
3934 * so that {@link #ACTION_SHOW_NEW_USER_DISCLAIMER broadcast} is not sent again the next time
3935 * this user is switched to.
3936 *
3937 * @hide
3938 */
3939 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
3940 android.Manifest.permission.INTERACT_ACROSS_USERS})
3941 @UserHandleAware
3942 @TestApi
3943 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
3944 public void acknowledgeNewUserDisclaimer() {
3945 if (mService != null) {
3946 try {
3947 mService.acknowledgeNewUserDisclaimer(mContext.getUserId());
3948 } catch (RemoteException e) {
3949 throw e.rethrowFromSystemServer();
3950 }
3951 }
3952 }
3953
3954 /**
3955 * Checks whether the new managed user disclaimer was viewed by the user.
3956 *
3957 * @hide
3958 */
3959 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
3960 android.Manifest.permission.INTERACT_ACROSS_USERS})
3961 @TestApi
3962 @UserHandleAware
3963 public boolean isNewUserDisclaimerAcknowledged() {
3964 if (mService != null) {
3965 try {
3966 return mService.isNewUserDisclaimerAcknowledged(mContext.getUserId());
3967 } catch (RemoteException e) {
3968 throw e.rethrowFromSystemServer();
3969 }
3970 }
3971 return false;
3972 }
3973
3974 /**
3975 * Return true if the given administrator component is currently active (enabled) in the system.
3976 *
3977 * @param admin The administrator component to check for.
3978 * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
3979 * otherwise
3980 */
3981 public boolean isAdminActive(@NonNull ComponentName admin) {
3982 throwIfParentInstance("isAdminActive");
3983 return isAdminActiveAsUser(admin, myUserId());
3984 }
3985
3986 /**
3987 * @see #isAdminActive(ComponentName)
3988 * @hide
3989 */
3990 public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
3991 if (mService != null) {
3992 try {
3993 return mService.isAdminActive(admin, userId);
3994 } catch (RemoteException e) {
3995 throw e.rethrowFromSystemServer();
3996 }
3997 }
3998 return false;
3999 }
4000
4001 /**
4002 * Return true if the given administrator component is currently being removed
4003 * for the user.
4004 * @hide
4005 */
4006 @TestApi
4007 public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
4008 if (mService != null) {
4009 try {
4010 return mService.isRemovingAdmin(admin, userId);
4011 } catch (RemoteException e) {
4012 throw e.rethrowFromSystemServer();
4013 }
4014 }
4015 return false;
4016 }
4017
4018 /**
4019 * Return a list of all currently active device administrators' component
4020 * names. If there are no administrators {@code null} may be
4021 * returned.
4022 */
4023 public @Nullable List<ComponentName> getActiveAdmins() {
4024 throwIfParentInstance("getActiveAdmins");
4025 return getActiveAdminsAsUser(myUserId());
4026 }
4027
4028 /**
4029 * @see #getActiveAdmins()
4030 * @hide
4031 */
4032 @UnsupportedAppUsage
4033 public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
4034 if (mService != null) {
4035 try {
4036 return mService.getActiveAdmins(userId);
4037 } catch (RemoteException e) {
4038 throw e.rethrowFromSystemServer();
4039 }
4040 }
4041 return null;
4042 }
4043
4044 /**
4045 * Used by package administration code to determine if a package can be stopped
4046 * or uninstalled.
4047 * @hide
4048 */
4049 @SystemApi
4050 @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4051 public boolean packageHasActiveAdmins(String packageName) {
4052 return packageHasActiveAdmins(packageName, myUserId());
4053 }
4054
4055 /**
4056 * Used by package administration code to determine if a package can be stopped
4057 * or uninstalled.
4058 * @hide
4059 */
4060 @UnsupportedAppUsage
4061 public boolean packageHasActiveAdmins(String packageName, int userId) {
4062 if (mService != null) {
4063 try {
4064 return mService.packageHasActiveAdmins(packageName, userId);
4065 } catch (RemoteException e) {
4066 throw e.rethrowFromSystemServer();
4067 }
4068 }
4069 return false;
4070 }
4071
4072 /**
4073 * Remove a current administration component. This can only be called
4074 * by the application that owns the administration component; if you
4075 * try to remove someone else's component, a security exception will be
4076 * thrown.
4077 *
4078 * <p>Note that the operation is not synchronous and the admin might still be active (as
4079 * indicated by {@link #getActiveAdmins()}) by the time this method returns.
4080 *
4081 * @param admin The administration compononent to remove.
4082 * @throws SecurityException if the caller is not in the owner application of {@code admin}.
4083 */
4084 public void removeActiveAdmin(@NonNull ComponentName admin) {
4085 throwIfParentInstance("removeActiveAdmin");
4086 if (mService != null) {
4087 try {
4088 mService.removeActiveAdmin(admin, myUserId());
4089 } catch (RemoteException e) {
4090 throw e.rethrowFromSystemServer();
4091 }
4092 }
4093 }
4094
4095 /**
4096 * Returns true if an administrator has been granted a particular device policy. This can be
4097 * used to check whether the administrator was activated under an earlier set of policies, but
4098 * requires additional policies after an upgrade.
4099 *
4100 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
4101 * active administrator, or an exception will be thrown.
4102 * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
4103 * @throws SecurityException if {@code admin} is not an active administrator.
4104 */
4105 public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
4106 throwIfParentInstance("hasGrantedPolicy");
4107 if (mService != null) {
4108 try {
4109 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
4110 } catch (RemoteException e) {
4111 throw e.rethrowFromSystemServer();
4112 }
4113 }
4114 return false;
4115 }
4116
4117 /**
4118 * Constant for {@link #setPasswordQuality}: the policy has no requirements
4119 * for the password. Note that quality constants are ordered so that higher
4120 * values are more restrictive.
4121 */
4122 public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
4123
4124 /**
4125 * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
4126 * recognition technology. This implies technologies that can recognize the identity of
4127 * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
4128 * Note that quality constants are ordered so that higher values are more restrictive.
4129 */
4130 public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
4131
4132 /**
4133 * Constant for {@link #setPasswordQuality}: the policy requires some kind
4134 * of password or pattern, but doesn't care what it is. Note that quality constants
4135 * are ordered so that higher values are more restrictive.
4136 */
4137 public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
4138
4139 /**
4140 * Constant for {@link #setPasswordQuality}: the user must have entered a
4141 * password containing at least numeric characters. Note that quality
4142 * constants are ordered so that higher values are more restrictive.
4143 */
4144 public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
4145
4146 /**
4147 * Constant for {@link #setPasswordQuality}: the user must have entered a
4148 * password containing at least numeric characters with no repeating (4444)
4149 * or ordered (1234, 4321, 2468) sequences. Note that quality
4150 * constants are ordered so that higher values are more restrictive.
4151 */
4152 public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
4153
4154 /**
4155 * Constant for {@link #setPasswordQuality}: the user must have entered a
4156 * password containing at least alphabetic (or other symbol) characters.
4157 * Note that quality constants are ordered so that higher values are more
4158 * restrictive.
4159 */
4160 public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
4161
4162 /**
4163 * Constant for {@link #setPasswordQuality}: the user must have entered a
4164 * password containing at least <em>both></em> numeric <em>and</em>
4165 * alphabetic (or other symbol) characters. Note that quality constants are
4166 * ordered so that higher values are more restrictive.
4167 */
4168 public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
4169
4170 /**
4171 * Constant for {@link #setPasswordQuality}: allows the admin to set precisely how many
4172 * characters of various types the password should contain to satisfy the policy. The admin
4173 * should set these requirements via {@link #setPasswordMinimumLetters},
4174 * {@link #setPasswordMinimumNumeric}, {@link #setPasswordMinimumSymbols},
4175 * {@link #setPasswordMinimumUpperCase}, {@link #setPasswordMinimumLowerCase},
4176 * {@link #setPasswordMinimumNonLetter}, and {@link #setPasswordMinimumLength}.
4177 * Note that quality constants are ordered so that higher values are more restrictive.
4178 */
4179 public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
4180
4181 /**
4182 * Constant for {@link #setPasswordQuality}: the user is not allowed to
4183 * modify password. In case this password quality is set, the password is
4184 * managed by a profile owner. The profile owner can set any password,
4185 * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
4186 * that quality constants are ordered so that higher values are more
4187 * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
4188 * the highest.
4189 * @hide
4190 */
4191 public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
4192
4193 /**
4194 * @hide
4195 *
4196 * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
4197 * a user with accounts. {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
4198 * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
4199 * used by authenticator to exempt their accounts from this:
4200 *
4201 * <ul>
4202 * <li>Non-test-only DO/PO still can't be installed when there are accounts.
4203 * <p>In order to make an apk test-only, add android:testOnly="true" to the
4204 * &lt;application&gt; tag in the manifest.
4205 *
4206 * <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
4207 * accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
4208 * Some authenticators claim to have any features, so to detect it, we also check
4209 * {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
4210 * if any of the accounts have it.
4211 * </ul>
4212 */
4213 @SystemApi
4214 public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
4215 "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
4216
4217 /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
4218 @SystemApi
4219 public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
4220 "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
4221
4222 /**
4223 * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4224 * manifest element, which declares that the module should be considered a required app for
4225 * managed users.
4226 * <p>Being declared as a required app prevents removal of this package during the
4227 * provisioning process.
4228 * @hide
4229 */
4230 @SystemApi
4231 public static final String REQUIRED_APP_MANAGED_USER = "android.app.REQUIRED_APP_MANAGED_USER";
4232
4233 /**
4234 * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4235 * manifest element, which declares that the module should be considered a required app for
4236 * managed devices.
4237 * <p>Being declared as a required app prevents removal of this package during the
4238 * provisioning process.
4239 * @hide
4240 */
4241 @SystemApi
4242 public static final String REQUIRED_APP_MANAGED_DEVICE =
4243 "android.app.REQUIRED_APP_MANAGED_DEVICE";
4244
4245 /**
4246 * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4247 * manifest element, which declares that the module should be considered a required app for
4248 * managed profiles.
4249 * <p>Being declared as a required app prevents removal of this package during the
4250 * provisioning process.
4251 * @hide
4252 */
4253 @SystemApi
4254 public static final String REQUIRED_APP_MANAGED_PROFILE =
4255 "android.app.REQUIRED_APP_MANAGED_PROFILE";
4256
4257 /**
4258 * Called by an application that is administering the device to set the password restrictions it
4259 * is imposing. After setting this, the user will not be able to enter a new password that is
4260 * not at least as restrictive as what has been set. Note that the current password will remain
4261 * until the user has set a new one, so the change does not take place immediately. To prompt
4262 * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4263 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
4264 * <p>
4265 * Quality constants are ordered so that higher values are more restrictive; thus the highest
4266 * requested quality constant (between the policy set here, the user's preference, and any other
4267 * considerations) is the one that is in effect.
4268 * <p>
4269 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4270 * password is always treated as empty.
4271 * <p>
4272 * The calling device admin must have requested
4273 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4274 * not, a security exception will be thrown.
4275 * <p>
4276 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4277 * {@link DevicePolicyManager} instance returned by
4278 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4279 * profile. Apps targeting {@link android.os.Build.VERSION_CODES#S} and above, with the
4280 * exception of a profile owner on an organization-owned device (as can be identified by
4281 * {@link #isOrganizationOwnedDeviceWithManagedProfile}), will get a
4282 * {@code IllegalArgumentException} when calling this method on the parent
4283 * {@link DevicePolicyManager} instance.
4284 *
4285 * <p><strong>Note:</strong> Specifying password requirements using this method clears the
4286 * password complexity requirements set using {@link #setRequiredPasswordComplexity(int)}.
4287 * If this method is called on the {@link DevicePolicyManager} instance returned by
4288 * {@link #getParentProfileInstance(ComponentName)}, then password complexity requirements
4289 * set on the primary {@link DevicePolicyManager} must be cleared first by calling
4290 * {@link #setRequiredPasswordComplexity} with {@link #PASSWORD_COMPLEXITY_NONE) first.
4291 *
4292 * <p><string>Note:</strong> this method is ignored on
4293 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4294 *
4295 * @deprecated Prefer using {@link #setRequiredPasswordComplexity(int)}, to require a password
4296 * that satisfies a complexity level defined by the platform, rather than specifying custom
4297 * password requirement.
4298 * Setting custom, overly-complicated password requirements leads to passwords that are hard
4299 * for users to remember and may not provide any security benefits given as Android uses
4300 * hardware-backed throttling to thwart online and offline brute-forcing of the device's
4301 * screen lock. Company-owned devices (fully-managed and organization-owned managed profile
4302 * devices) are able to continue using this method, though it is recommended that
4303 * {@link #setRequiredPasswordComplexity(int)} should be used instead.
4304 *
4305 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4306 * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
4307 * {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK},
4308 * {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
4309 * {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
4310 * {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
4311 * @throws SecurityException if {@code admin} is not an active administrator, if {@code admin}
4312 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} or if the
4313 * calling app is targeting {@link android.os.Build.VERSION_CODES#S} and above,
4314 * and is calling the method the {@link DevicePolicyManager} instance returned by
4315 * {@link #getParentProfileInstance(ComponentName)}.
4316 * @throws IllegalStateException if the caller is trying to set password quality on the parent
4317 * {@link DevicePolicyManager} instance while password complexity was set on the
4318 * primary {@link DevicePolicyManager} instance.
4319 */
4320 @Deprecated
4321 public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
4322 if (mService != null) {
4323 try {
4324 mService.setPasswordQuality(admin, quality, mParentInstance);
4325 } catch (RemoteException e) {
4326 throw e.rethrowFromSystemServer();
4327 }
4328 }
4329 }
4330
4331 /**
4332 * Retrieve the current minimum password quality for a particular admin or all admins that set
4333 * restrictions on this user and its participating profiles. Restrictions on profiles that have
4334 * a separate challenge are not taken into account.
4335 *
4336 * <p>This method can be called on the {@link DevicePolicyManager} instance
4337 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4338 * restrictions on the parent profile.
4339 *
4340 * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4341 * the password is always treated as empty.
4342 *
4343 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4344 *
4345 * @param admin The name of the admin component to check, or {@code null} to aggregate
4346 * all admins.
4347 */
4348 @Deprecated
4349 public int getPasswordQuality(@Nullable ComponentName admin) {
4350 return getPasswordQuality(admin, myUserId());
4351 }
4352
4353 /** @hide per-user version */
4354 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4355 public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
4356 if (mService != null) {
4357 try {
4358 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
4359 } catch (RemoteException e) {
4360 throw e.rethrowFromSystemServer();
4361 }
4362 }
4363 return PASSWORD_QUALITY_UNSPECIFIED;
4364 }
4365
4366 /**
4367 * Called by an application that is administering the device to set the minimum allowed password
4368 * length. After setting this, the user will not be able to enter a new password that is not at
4369 * least as restrictive as what has been set. Note that the current password will remain until
4370 * the user has set a new one, so the change does not take place immediately. To prompt the user
4371 * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4372 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4373 * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
4374 * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
4375 * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
4376 * {@link #setPasswordQuality}. If an app targeting SDK level
4377 * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4378 * password quality to one of these values first, this method will throw
4379 * {@link IllegalStateException}.
4380 * <p>
4381 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4382 * password is always treated as empty.
4383 * <p>
4384 * The calling device admin must have requested
4385 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4386 * not, a security exception will be thrown.
4387 * <p>
4388 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4389 * {@link DevicePolicyManager} instance returned by
4390 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4391 * profile.
4392 *
4393 * <p><string>Note:</strong> this method is ignored on
4394 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4395 *
4396 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4397 *
4398 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4399 * @param length The new desired minimum password length. A value of 0 means there is no
4400 * restriction.
4401 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4402 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4403 * @throws IllegalStateException if the calling app is targeting SDK level
4404 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4405 * quality requirement prior to calling this method.
4406 */
4407 @Deprecated
4408 public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
4409 if (mService != null) {
4410 try {
4411 mService.setPasswordMinimumLength(admin, length, mParentInstance);
4412 } catch (RemoteException e) {
4413 throw e.rethrowFromSystemServer();
4414 }
4415 }
4416 }
4417
4418 /**
4419 * Retrieve the current minimum password length for a particular admin or all admins that set
4420 * restrictions on this user and its participating profiles. Restrictions on profiles that have
4421 * a separate challenge are not taken into account.
4422 *
4423 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4424 * password is always treated as empty.
4425 *
4426 * <p>This method can be called on the {@link DevicePolicyManager} instance
4427 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4428 * restrictions on the parent profile.
4429 *
4430 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4431 *
4432 * @param admin The name of the admin component to check, or {@code null} to aggregate
4433 * all admins.
4434 */
4435 @Deprecated
4436 public int getPasswordMinimumLength(@Nullable ComponentName admin) {
4437 return getPasswordMinimumLength(admin, myUserId());
4438 }
4439
4440 /** @hide per-user version */
4441 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4442 public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
4443 if (mService != null) {
4444 try {
4445 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
4446 } catch (RemoteException e) {
4447 throw e.rethrowFromSystemServer();
4448 }
4449 }
4450 return 0;
4451 }
4452
4453 /**
4454 * Called by an application that is administering the device to set the minimum number of upper
4455 * case letters required in the password. After setting this, the user will not be able to enter
4456 * a new password that is not at least as restrictive as what has been set. Note that the
4457 * current password will remain until the user has set a new one, so the change does not take
4458 * place immediately. To prompt the user for a new password, use
4459 * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4460 * setting this value. This constraint is only imposed if the administrator has also requested
4461 * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4462 * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4463 * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4464 * {@link IllegalStateException}. The default value is 0.
4465 * <p>
4466 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4467 * password is always treated as empty.
4468 * <p>
4469 * The calling device admin must have requested
4470 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4471 * not, a security exception will be thrown.
4472 * <p>
4473 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4474 * {@link DevicePolicyManager} instance returned by
4475 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4476 * profile.
4477 *
4478 * <p><string>Note:</strong> this method is ignored on
4479 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4480 *
4481 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4482 *
4483 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4484 * @param length The new desired minimum number of upper case letters required in the password.
4485 * A value of 0 means there is no restriction.
4486 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4487 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4488 * @throws IllegalStateException if the calling app is targeting SDK level
4489 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4490 * quality requirement prior to calling this method.
4491 */
4492 @Deprecated
4493 public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
4494 if (mService != null) {
4495 try {
4496 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
4497 } catch (RemoteException e) {
4498 throw e.rethrowFromSystemServer();
4499 }
4500 }
4501 }
4502
4503 /**
4504 * Retrieve the current number of upper case letters required in the password
4505 * for a particular admin or all admins that set restrictions on this user and
4506 * its participating profiles. Restrictions on profiles that have a separate challenge
4507 * are not taken into account.
4508 * This is the same value as set by
4509 * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
4510 * and only applies when the password quality is
4511 * {@link #PASSWORD_QUALITY_COMPLEX}.
4512 *
4513 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4514 * password is always treated as empty.
4515 *
4516 * <p>This method can be called on the {@link DevicePolicyManager} instance
4517 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4518 * restrictions on the parent profile.
4519 *
4520 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4521 *
4522 * @param admin The name of the admin component to check, or {@code null} to
4523 * aggregate all admins.
4524 * @return The minimum number of upper case letters required in the
4525 * password.
4526 */
4527 @Deprecated
4528 public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
4529 return getPasswordMinimumUpperCase(admin, myUserId());
4530 }
4531
4532 /** @hide per-user version */
4533 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4534 public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
4535 if (mService != null) {
4536 try {
4537 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
4538 } catch (RemoteException e) {
4539 throw e.rethrowFromSystemServer();
4540 }
4541 }
4542 return 0;
4543 }
4544
4545 /**
4546 * Called by an application that is administering the device to set the minimum number of lower
4547 * case letters required in the password. After setting this, the user will not be able to enter
4548 * a new password that is not at least as restrictive as what has been set. Note that the
4549 * current password will remain until the user has set a new one, so the change does not take
4550 * place immediately. To prompt the user for a new password, use
4551 * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4552 * setting this value. This constraint is only imposed if the administrator has also requested
4553 * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4554 * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4555 * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4556 * {@link IllegalStateException}. The default value is 0.
4557 * <p>
4558 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4559 * password is always treated as empty.
4560 * <p>
4561 * The calling device admin must have requested
4562 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4563 * not, a security exception will be thrown.
4564 * <p>
4565 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4566 * {@link DevicePolicyManager} instance returned by
4567 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4568 * profile.
4569 *
4570 * <p><string>Note:</strong> this method is ignored on
4571 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4572 *
4573 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4574 *
4575 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4576 * @param length The new desired minimum number of lower case letters required in the password.
4577 * A value of 0 means there is no restriction.
4578 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4579 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4580 * @throws IllegalStateException if the calling app is targeting SDK level
4581 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4582 * quality requirement prior to calling this method.
4583 */
4584 @Deprecated
4585 public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
4586 if (mService != null) {
4587 try {
4588 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
4589 } catch (RemoteException e) {
4590 throw e.rethrowFromSystemServer();
4591 }
4592 }
4593 }
4594
4595 /**
4596 * Retrieve the current number of lower case letters required in the password
4597 * for a particular admin or all admins that set restrictions on this user
4598 * and its participating profiles. Restrictions on profiles that have
4599 * a separate challenge are not taken into account.
4600 * This is the same value as set by
4601 * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
4602 * and only applies when the password quality is
4603 * {@link #PASSWORD_QUALITY_COMPLEX}.
4604 *
4605 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4606 * password is always treated as empty.
4607 *
4608 * <p>This method can be called on the {@link DevicePolicyManager} instance
4609 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4610 * restrictions on the parent profile.
4611 *
4612 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4613 *
4614 * @param admin The name of the admin component to check, or {@code null} to
4615 * aggregate all admins.
4616 * @return The minimum number of lower case letters required in the
4617 * password.
4618 */
4619 @Deprecated
4620 public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
4621 return getPasswordMinimumLowerCase(admin, myUserId());
4622 }
4623
4624 /** @hide per-user version */
4625 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4626 public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
4627 if (mService != null) {
4628 try {
4629 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
4630 } catch (RemoteException e) {
4631 throw e.rethrowFromSystemServer();
4632 }
4633 }
4634 return 0;
4635 }
4636
4637 /**
4638 * Called by an application that is administering the device to set the minimum number of
4639 * letters required in the password. After setting this, the user will not be able to enter a
4640 * new password that is not at least as restrictive as what has been set. Note that the current
4641 * password will remain until the user has set a new one, so the change does not take place
4642 * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4643 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4644 * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
4645 * {@link #setPasswordQuality}. If an app targeting SDK level
4646 * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4647 * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4648 * {@link IllegalStateException}. The default value is 1.
4649 * <p>
4650 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4651 * password is always treated as empty.
4652 * <p>
4653 * The calling device admin must have requested
4654 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4655 * not, a security exception will be thrown.
4656 * <p>
4657 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4658 * {@link DevicePolicyManager} instance returned by
4659 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4660 * profile.
4661 *
4662 * <p><string>Note:</strong> this method is ignored on
4663 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4664 *
4665 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4666 *
4667 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4668 * @param length The new desired minimum number of letters required in the password. A value of
4669 * 0 means there is no restriction.
4670 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4671 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4672 * @throws IllegalStateException if the calling app is targeting SDK level
4673 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4674 * quality requirement prior to calling this method.
4675 */
4676 @Deprecated
4677 public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
4678 if (mService != null) {
4679 try {
4680 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
4681 } catch (RemoteException e) {
4682 throw e.rethrowFromSystemServer();
4683 }
4684 }
4685 }
4686
4687 /**
4688 * Retrieve the current number of letters required in the password
4689 * for a particular admin or all admins that set restrictions on this user
4690 * and its participating profiles. Restrictions on profiles that have
4691 * a separate challenge are not taken into account.
4692 * This is the same value as set by
4693 * {@link #setPasswordMinimumLetters(ComponentName, int)}
4694 * and only applies when the password quality is
4695 * {@link #PASSWORD_QUALITY_COMPLEX}.
4696 *
4697 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4698 * password is always treated as empty.
4699 *
4700 * <p>This method can be called on the {@link DevicePolicyManager} instance
4701 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4702 * restrictions on the parent profile.
4703 *
4704 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4705 *
4706 * @param admin The name of the admin component to check, or {@code null} to
4707 * aggregate all admins.
4708 * @return The minimum number of letters required in the password.
4709 */
4710 @Deprecated
4711 public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
4712 return getPasswordMinimumLetters(admin, myUserId());
4713 }
4714
4715 /** @hide per-user version */
4716 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4717 public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
4718 if (mService != null) {
4719 try {
4720 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
4721 } catch (RemoteException e) {
4722 throw e.rethrowFromSystemServer();
4723 }
4724 }
4725 return 0;
4726 }
4727
4728 /**
4729 * Called by an application that is administering the device to set the minimum number of
4730 * numerical digits required in the password. After setting this, the user will not be able to
4731 * enter a new password that is not at least as restrictive as what has been set. Note that the
4732 * current password will remain until the user has set a new one, so the change does not take
4733 * place immediately. To prompt the user for a new password, use
4734 * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4735 * setting this value. This constraint is only imposed if the administrator has also requested
4736 * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4737 * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4738 * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4739 * {@link IllegalStateException}. The default value is 1.
4740 * <p>
4741 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4742 * password is always treated as empty.
4743 * <p>
4744 * The calling device admin must have requested
4745 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4746 * not, a security exception will be thrown.
4747 * <p>
4748 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4749 * {@link DevicePolicyManager} instance returned by
4750 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4751 * profile.
4752 *
4753 * <p><string>Note:</strong> this method is ignored on
4754 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4755 *
4756 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4757 *
4758 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4759 * @param length The new desired minimum number of numerical digits required in the password. A
4760 * value of 0 means there is no restriction.
4761 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4762 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4763 * @throws IllegalStateException if the calling app is targeting SDK level
4764 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4765 * quality requirement prior to calling this method.
4766 */
4767 @Deprecated
4768 public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
4769 if (mService != null) {
4770 try {
4771 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
4772 } catch (RemoteException e) {
4773 throw e.rethrowFromSystemServer();
4774 }
4775 }
4776 }
4777
4778 /**
4779 * Retrieve the current number of numerical digits required in the password
4780 * for a particular admin or all admins that set restrictions on this user
4781 * and its participating profiles. Restrictions on profiles that have
4782 * a separate challenge are not taken into account.
4783 * This is the same value as set by
4784 * {@link #setPasswordMinimumNumeric(ComponentName, int)}
4785 * and only applies when the password quality is
4786 * {@link #PASSWORD_QUALITY_COMPLEX}.
4787 *
4788 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4789 * password is always treated as empty.
4790 *
4791 * <p>This method can be called on the {@link DevicePolicyManager} instance
4792 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4793 * restrictions on the parent profile.
4794 *
4795 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4796 *
4797 * @param admin The name of the admin component to check, or {@code null} to
4798 * aggregate all admins.
4799 * @return The minimum number of numerical digits required in the password.
4800 */
4801 @Deprecated
4802 public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
4803 return getPasswordMinimumNumeric(admin, myUserId());
4804 }
4805
4806 /** @hide per-user version */
4807 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4808 public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
4809 if (mService != null) {
4810 try {
4811 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
4812 } catch (RemoteException e) {
4813 throw e.rethrowFromSystemServer();
4814 }
4815 }
4816 return 0;
4817 }
4818
4819 /**
4820 * Called by an application that is administering the device to set the minimum number of
4821 * symbols required in the password. After setting this, the user will not be able to enter a
4822 * new password that is not at least as restrictive as what has been set. Note that the current
4823 * password will remain until the user has set a new one, so the change does not take place
4824 * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4825 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4826 * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
4827 * {@link #setPasswordQuality}. If an app targeting SDK level
4828 * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4829 * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4830 * {@link IllegalStateException}. The default value is 1.
4831 * <p>
4832 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4833 * password is always treated as empty.
4834 * <p>
4835 * The calling device admin must have requested
4836 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4837 * not, a security exception will be thrown.
4838 * <p>
4839 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4840 * {@link DevicePolicyManager} instance returned by
4841 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4842 * profile.
4843 *
4844 * <p><string>Note:</strong> this method is ignored on
4845 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4846 *
4847 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4848 *
4849 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4850 * @param length The new desired minimum number of symbols required in the password. A value of
4851 * 0 means there is no restriction.
4852 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4853 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4854 * @throws IllegalStateException if the calling app is targeting SDK level
4855 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4856 * quality requirement prior to calling this method.
4857 */
4858 @Deprecated
4859 public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
4860 if (mService != null) {
4861 try {
4862 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
4863 } catch (RemoteException e) {
4864 throw e.rethrowFromSystemServer();
4865 }
4866 }
4867 }
4868
4869 /**
4870 * Retrieve the current number of symbols required in the password
4871 * for a particular admin or all admins that set restrictions on this user
4872 * and its participating profiles. Restrictions on profiles that have
4873 * a separate challenge are not taken into account. This is the same value as
4874 * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
4875 * and only applies when the password quality is
4876 * {@link #PASSWORD_QUALITY_COMPLEX}.
4877 *
4878 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4879 * password is always treated as empty.
4880 *
4881 * <p>This method can be called on the {@link DevicePolicyManager} instance
4882 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4883 * restrictions on the parent profile.
4884 *
4885 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4886 *
4887 * @param admin The name of the admin component to check, or {@code null} to
4888 * aggregate all admins.
4889 * @return The minimum number of symbols required in the password.
4890 */
4891 @Deprecated
4892 public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
4893 return getPasswordMinimumSymbols(admin, myUserId());
4894 }
4895
4896 /** @hide per-user version */
4897 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4898 public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
4899 if (mService != null) {
4900 try {
4901 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
4902 } catch (RemoteException e) {
4903 throw e.rethrowFromSystemServer();
4904 }
4905 }
4906 return 0;
4907 }
4908
4909 /**
4910 * Called by an application that is administering the device to set the minimum number of
4911 * non-letter characters (numerical digits or symbols) required in the password. After setting
4912 * this, the user will not be able to enter a new password that is not at least as restrictive
4913 * as what has been set. Note that the current password will remain until the user has set a new
4914 * one, so the change does not take place immediately. To prompt the user for a new password,
4915 * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4916 * setting this value. This constraint is only imposed if the administrator has also requested
4917 * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4918 * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4919 * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4920 * {@link IllegalStateException}. The default value is 0.
4921 * <p>
4922 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4923 * password is always treated as empty.
4924 * <p>
4925 * The calling device admin must have requested
4926 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4927 * not, a security exception will be thrown.
4928 * <p>
4929 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4930 * {@link DevicePolicyManager} instance returned by
4931 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4932 * profile.
4933 *
4934 * <p><string>Note:</strong> this method is ignored on
4935 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4936 *
4937 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4938 *
4939 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4940 * @param length The new desired minimum number of letters required in the password. A value of
4941 * 0 means there is no restriction.
4942 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4943 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4944 * @throws IllegalStateException if the calling app is targeting SDK level
4945 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4946 * quality requirement prior to calling this method.
4947 */
4948 @Deprecated
4949 public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
4950 if (mService != null) {
4951 try {
4952 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
4953 } catch (RemoteException e) {
4954 throw e.rethrowFromSystemServer();
4955 }
4956 }
4957 }
4958
4959 /**
4960 * Retrieve the current number of non-letter characters required in the password
4961 * for a particular admin or all admins that set restrictions on this user
4962 * and its participating profiles. Restrictions on profiles that have
4963 * a separate challenge are not taken into account.
4964 * This is the same value as set by
4965 * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
4966 * and only applies when the password quality is
4967 * {@link #PASSWORD_QUALITY_COMPLEX}.
4968 *
4969 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4970 * password is always treated as empty.
4971 *
4972 * <p>This method can be called on the {@link DevicePolicyManager} instance
4973 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4974 * restrictions on the parent profile.
4975 *
4976 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4977 *
4978 * @param admin The name of the admin component to check, or {@code null} to
4979 * aggregate all admins.
4980 * @return The minimum number of letters required in the password.
4981 */
4982 @Deprecated
4983 public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
4984 return getPasswordMinimumNonLetter(admin, myUserId());
4985 }
4986
4987 /** @hide per-user version */
4988 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4989 public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
4990 if (mService != null) {
4991 try {
4992 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
4993 } catch (RemoteException e) {
4994 throw e.rethrowFromSystemServer();
4995 }
4996 }
4997 return 0;
4998 }
4999
5000 /**
5001 * Returns minimum PasswordMetrics that satisfies all admin policies.
5002 *
5003 * @hide
5004 */
5005 public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle) {
5006 return getPasswordMinimumMetrics(userHandle, false);
5007 }
5008
5009 /**
5010 * Returns minimum PasswordMetrics that satisfies all admin policies.
5011 * If requested, only consider device-wide admin policies and ignore policies set on the
5012 * managed profile instance (as if the managed profile had separate work challenge).
5013 *
5014 * @hide
5015 */
5016 public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
5017 boolean deviceWideOnly) {
5018 if (mService != null) {
5019 try {
5020 return mService.getPasswordMinimumMetrics(userHandle, deviceWideOnly);
5021 } catch (RemoteException e) {
5022 throw e.rethrowFromSystemServer();
5023 }
5024 }
5025 return null;
5026 }
5027
5028 /**
5029 * Called by an application that is administering the device to set the length of the password
5030 * history. After setting this, the user will not be able to enter a new password that is the
5031 * same as any password in the history. Note that the current password will remain until the
5032 * user has set a new one, so the change does not take place immediately. To prompt the user for
5033 * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
5034 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value.
5035 * <p>
5036 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5037 * password history length is always 0.
5038 * <p>
5039 * The calling device admin must have requested
5040 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5041 * not, a security exception will be thrown.
5042 * <p>
5043 * This method can be called on the {@link DevicePolicyManager} instance returned by
5044 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5045 * profile.
5046 *
5047 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5048 * @param length The new desired length of password history. A value of 0 means there is no
5049 * restriction.
5050 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5051 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5052 */
5053 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5054 public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
5055 if (mService != null) {
5056 try {
5057 mService.setPasswordHistoryLength(admin, length, mParentInstance);
5058 } catch (RemoteException e) {
5059 throw e.rethrowFromSystemServer();
5060 }
5061 }
5062 }
5063
5064 /**
5065 * Called by a device admin to set the password expiration timeout. Calling this method will
5066 * restart the countdown for password expiration for the given admin, as will changing the
5067 * device password (for all admins).
5068 * <p>
5069 * The provided timeout is the time delta in ms and will be added to the current time. For
5070 * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
5071 * 432000000 ms for timeout.
5072 * <p>
5073 * To disable password expiration, a value of 0 may be used for timeout.
5074 * <p>
5075 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5076 * password expiration is always disabled.
5077 * <p>
5078 * The calling device admin must have requested
5079 * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
5080 * not, a security exception will be thrown.
5081 * <p>
5082 * Note that setting the password will automatically reset the expiration time for all active
5083 * admins. Active admins do not need to explicitly call this method in that case.
5084 * <p>
5085 * This method can be called on the {@link DevicePolicyManager} instance returned by
5086 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5087 * profile.
5088 *
5089 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5090 * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
5091 * there is no restriction (unlimited).
5092 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5093 * does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
5094 */
5095 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5096 public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
5097 if (mService != null) {
5098 try {
5099 mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
5100 } catch (RemoteException e) {
5101 throw e.rethrowFromSystemServer();
5102 }
5103 }
5104 }
5105
5106 /**
5107 * Get the password expiration timeout for the given admin. The expiration timeout is the
5108 * recurring expiration timeout provided in the call to
5109 * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
5110 * aggregate of all participating policy administrators if {@code admin} is null. Admins that
5111 * have set restrictions on profiles that have a separate challenge are not taken into account.
5112 *
5113 * <p>This method can be called on the {@link DevicePolicyManager} instance
5114 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5115 * restrictions on the parent profile.
5116 *
5117 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5118 * password expiration is always disabled and this method always returns 0.
5119 *
5120 * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
5121 * @return The timeout for the given admin or the minimum of all timeouts
5122 */
5123 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5124 public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
5125 if (mService != null) {
5126 try {
5127 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
5128 } catch (RemoteException e) {
5129 throw e.rethrowFromSystemServer();
5130 }
5131 }
5132 return 0;
5133 }
5134
5135 /**
5136 * Get the current password expiration time for a particular admin or all admins that set
5137 * restrictions on this user and its participating profiles. Restrictions on profiles that have
5138 * a separate challenge are not taken into account. If admin is {@code null}, then a composite
5139 * of all expiration times is returned - which will be the minimum of all of them.
5140 *
5141 * <p>This method can be called on the {@link DevicePolicyManager} instance
5142 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5143 * the password expiration for the parent profile.
5144 *
5145 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5146 * password expiration is always disabled and this method always returns 0.
5147 *
5148 * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
5149 * @return The password expiration time, in milliseconds since epoch.
5150 */
5151 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5152 public long getPasswordExpiration(@Nullable ComponentName admin) {
5153 if (mService != null) {
5154 try {
5155 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
5156 } catch (RemoteException e) {
5157 throw e.rethrowFromSystemServer();
5158 }
5159 }
5160 return 0;
5161 }
5162
5163 /**
5164 * Retrieve the current password history length for a particular admin or all admins that
5165 * set restrictions on this user and its participating profiles. Restrictions on profiles that
5166 * have a separate challenge are not taken into account.
5167 *
5168 * <p>This method can be called on the {@link DevicePolicyManager} instance
5169 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5170 * restrictions on the parent profile.
5171 *
5172 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5173 * password history length is always 0.
5174 *
5175 * @param admin The name of the admin component to check, or {@code null} to aggregate
5176 * all admins.
5177 * @return The length of the password history
5178 */
5179 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5180 public int getPasswordHistoryLength(@Nullable ComponentName admin) {
5181 return getPasswordHistoryLength(admin, myUserId());
5182 }
5183
5184 /** @hide per-user version */
5185 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
5186 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5187 public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
5188 if (mService != null) {
5189 try {
5190 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
5191 } catch (RemoteException e) {
5192 throw e.rethrowFromSystemServer();
5193 }
5194 }
5195 return 0;
5196 }
5197
5198 /**
5199 * Return the maximum password length that the device supports for a
5200 * particular password quality.
5201 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5202 * password is always empty and this method always returns 0.
5203 * @param quality The quality being interrogated.
5204 * @return Returns the maximum length that the user can enter.
5205 */
5206 public int getPasswordMaximumLength(int quality) {
5207 PackageManager pm = mContext.getPackageManager();
5208 if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) {
5209 return 0;
5210 }
5211 return MAX_PASSWORD_LENGTH;
5212 }
5213
5214 /**
5215 * Determines whether the calling user's current password meets policy requirements
5216 * (e.g. quality, minimum length). The user must be unlocked to perform this check.
5217 *
5218 * <p>Policy requirements which affect this check can be set by admins of the user, but also
5219 * by the admin of a managed profile associated with the calling user (when the managed profile
5220 * doesn't have a separate work challenge). When a managed profile has a separate work
5221 * challenge, its policy requirements only affect the managed profile.
5222 *
5223 * <p>Depending on the user, this method checks the policy requirement against one of the
5224 * following passwords:
5225 * <ul>
5226 * <li>For the primary user or secondary users: the personal keyguard password.
5227 * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal
5228 * keyguard password.
5229 * <ul/>
5230 * In other words, it's always checking the requirement against the password that is protecting
5231 * the calling user.
5232 *
5233 * <p>Note that this method considers all policy requirements targeting the password in
5234 * question. For example a profile owner might set a requirement on the parent profile i.e.
5235 * personal keyguard but not on the profile itself. When the device has a weak personal keyguard
5236 * password and no separate work challenge, calling this method will return {@code false}
5237 * despite the profile owner not setting a policy on the profile itself. This is because the
5238 * profile's current password is the personal keyguard password, and it does not meet all policy
5239 * requirements.
5240 *
5241 * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before
5242 * calling this method. Note, this policy type is deprecated for device admins in Android 9.0
5243 * (API level 28) or higher.
5244 *
5245 * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
5246 * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
5247 * the parent profile is sufficient.
5248 *
5249 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5250 * password is always treated as empty - i.e. this method will always return false on such
5251 * devices, provided any password requirements were set.
5252 *
5253 * @return {@code true} if the password meets the policy requirements, {@code false} otherwise
5254 * @throws SecurityException if the calling application isn't an active admin that uses
5255 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5256 * @throws IllegalStateException if the user isn't unlocked
5257 */
5258 public boolean isActivePasswordSufficient() {
5259 if (mService != null) {
5260 try {
5261 return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
5262 } catch (RemoteException e) {
5263 throw e.rethrowFromSystemServer();
5264 }
5265 }
5266 return false;
5267 }
5268
5269 /**
5270 * Called by profile owner of a managed profile to determine whether the current device password
5271 * meets policy requirements set explicitly device-wide.
5272 * <p> This API is similar to {@link #isActivePasswordSufficient()}, with two notable
5273 * differences:
5274 * <ul>
5275 * <li>this API always targets the device password. As a result it should always be called on
5276 * the {@link #getParentProfileInstance(ComponentName)} instance.</li>
5277 * <li>password policy requirement set on the managed profile is not taken into consideration
5278 * by this API, even if the device currently does not have a separate work challenge set.</li>
5279 * </ul>
5280 *
5281 * <p>This API is designed to facilite progressive password enrollment flows when the DPC
5282 * imposes both device and profile password policies. DPC applies profile password policy by
5283 * calling {@link #setPasswordQuality(ComponentName, int)} or
5284 * {@link #setRequiredPasswordComplexity} on the regular {@link DevicePolicyManager} instance,
5285 * while it applies device-wide policy by calling {@link #setRequiredPasswordComplexity} on the
5286 * {@link #getParentProfileInstance(ComponentName)} instance. The DPC can utilize this check to
5287 * guide the user to set a device password first taking into consideration the device-wide
5288 * policy only, and then prompt the user to either upgrade it to be fully compliant, or enroll a
5289 * separate work challenge to satisfy the profile password policy only.
5290 *
5291 * <p>The device user must be unlocked (@link {@link UserManager#isUserUnlocked(UserHandle)})
5292 * to perform this check.
5293 *
5294 * @return {@code true} if the device password meets explicit requirement set on it,
5295 * {@code false} otherwise.
5296 * @throws SecurityException if the calling application is not a profile owner of a managed
5297 * profile, or if this API is not called on the parent DevicePolicyManager instance.
5298 * @throws IllegalStateException if the user isn't unlocked
5299 * @see #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY
5300 */
5301 public boolean isActivePasswordSufficientForDeviceRequirement() {
5302 if (!mParentInstance) {
5303 throw new SecurityException("only callable on the parent instance");
5304 }
5305 if (mService != null) {
5306 try {
5307 return mService.isActivePasswordSufficientForDeviceRequirement();
5308 } catch (RemoteException e) {
5309 throw e.rethrowFromSystemServer();
5310 }
5311 }
5312 return false;
5313 }
5314
5315 /**
5316 * Returns how complex the current user's screen lock is.
5317 *
5318 * <p>Note that when called from a profile which uses an unified challenge with its parent, the
5319 * screen lock complexity of the parent will be returned.
5320 *
5321 * <p>Apps need the {@link permission#REQUEST_PASSWORD_COMPLEXITY} permission to call this
5322 * method. On Android {@link android.os.Build.VERSION_CODES#S} and above, the calling
5323 * application does not need this permission if it is a device owner or a profile owner.
5324 *
5325 * <p>This method can be called on the {@link DevicePolicyManager} instance
5326 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5327 * restrictions on the parent profile.
5328 *
5329 * @throws IllegalStateException if the user is not unlocked.
5330 * @throws SecurityException if the calling application does not have the permission
5331 * {@link permission#REQUEST_PASSWORD_COMPLEXITY}, and is not a
5332 * device owner or a profile owner.
5333 */
5334 @PasswordComplexity
5335 @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
5336 public int getPasswordComplexity() {
5337 if (mService == null) {
5338 return PASSWORD_COMPLEXITY_NONE;
5339 }
5340
5341 try {
5342 return mService.getPasswordComplexity(mParentInstance);
5343 } catch (RemoteException e) {
5344 throw e.rethrowFromSystemServer();
5345 }
5346 }
5347
5348 /**
5349 * Sets a minimum password complexity requirement for the user's screen lock.
5350 * The complexity level is one of the pre-defined levels, and the user is unable to set a
5351 * password with a lower complexity level.
5352 *
5353 * <p>Note that when called on a profile which uses an unified challenge with its parent, the
5354 * complexity would apply to the unified challenge.
5355 *
5356 * <p>This method can be called on the {@link DevicePolicyManager} instance
5357 * returned by {@link #getParentProfileInstance(ComponentName)} in order to set
5358 * restrictions on the parent profile.
5359 *
5360 * <p><strong>Note:</strong> Specifying password requirements using this method clears any
5361 * password requirements set using the obsolete {@link #setPasswordQuality(ComponentName, int)}
5362 * and any of its associated methods.
5363 * Additionally, if there are password requirements set using the obsolete
5364 * {@link #setPasswordQuality(ComponentName, int)} on the parent {@code DevicePolicyManager}
5365 * instance, they must be cleared by calling {@link #setPasswordQuality(ComponentName, int)}
5366 * with {@link #PASSWORD_QUALITY_UNSPECIFIED} on that instance prior to setting complexity
5367 * requirement for the managed profile.
5368 *
5369 * @throws SecurityException if the calling application is not a device owner or a profile
5370 * owner.
5371 * @throws IllegalArgumentException if the complexity level is not one of the four above.
5372 * @throws IllegalStateException if the caller is trying to set password complexity while there
5373 * are password requirements specified using {@link #setPasswordQuality(ComponentName, int)}
5374 * on the parent {@code DevicePolicyManager} instance.
5375 */
5376 public void setRequiredPasswordComplexity(@PasswordComplexity int passwordComplexity) {
5377 if (mService == null) {
5378 return;
5379 }
5380
5381 try {
5382 mService.setRequiredPasswordComplexity(passwordComplexity, mParentInstance);
5383 } catch (RemoteException e) {
5384 throw e.rethrowFromSystemServer();
5385 }
5386 }
5387
5388
5389 /**
5390 * Gets the password complexity requirement set by {@link #setRequiredPasswordComplexity(int)},
5391 * for the current user.
5392 *
5393 * <p>The difference between this method and {@link #getPasswordComplexity()} is that this
5394 * method simply returns the value set by {@link #setRequiredPasswordComplexity(int)} while
5395 * {@link #getPasswordComplexity()} returns the complexity of the actual password.
5396 *
5397 * <p>This method can be called on the {@link DevicePolicyManager} instance
5398 * returned by {@link #getParentProfileInstance(ComponentName)} in order to get
5399 * restrictions on the parent profile.
5400 *
5401 * @throws SecurityException if the calling application is not a device owner or a profile
5402 * owner.
5403 */
5404 @PasswordComplexity
5405 public int getRequiredPasswordComplexity() {
5406 if (mService == null) {
5407 return PASSWORD_COMPLEXITY_NONE;
5408 }
5409
5410 try {
5411 return mService.getRequiredPasswordComplexity(mParentInstance);
5412 } catch (RemoteException e) {
5413 throw e.rethrowFromSystemServer();
5414 }
5415 }
5416
5417 /**
5418 * Returns the password complexity that applies to this user, aggregated from other users if
5419 * necessary (for example, if the DPC has set password complexity requirements on the parent
5420 * profile DPM instance of a managed profile user, they would apply to the primary user on the
5421 * device).
5422 * @hide
5423 */
5424 @PasswordComplexity
5425 public int getAggregatedPasswordComplexityForUser(int userId) {
5426 return getAggregatedPasswordComplexityForUser(userId, false);
5427 }
5428
5429 /**
5430 * Returns the password complexity that applies to this user, aggregated from other users if
5431 * necessary (for example, if the DPC has set password complexity requirements on the parent
5432 * profile DPM instance of a managed profile user, they would apply to the primary user on the
5433 * device). If {@code deviceWideOnly} is {@code true}, ignore policies set on the
5434 * managed profile DPM instance (as if the managed profile had separate work challenge).
5435 * @hide
5436 */
5437 @PasswordComplexity
5438 public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
5439 if (mService == null) {
5440 return PASSWORD_COMPLEXITY_NONE;
5441 }
5442
5443 try {
5444 return mService.getAggregatedPasswordComplexityForUser(userId, deviceWideOnly);
5445 } catch (RemoteException e) {
5446 throw e.rethrowFromSystemServer();
5447 }
5448 }
5449
5450
5451 /**
5452 * When called by a profile owner of a managed profile returns true if the profile uses unified
5453 * challenge with its parent user.
5454 *
5455 * <strong>Note</strong>: This method is not concerned with password quality and will return
5456 * false if the profile has empty password as a separate challenge.
5457 *
5458 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5459 * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
5460 * @see UserManager#DISALLOW_UNIFIED_PASSWORD
5461 */
5462 public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
5463 throwIfParentInstance("isUsingUnifiedPassword");
5464 if (mService != null) {
5465 try {
5466 return mService.isUsingUnifiedPassword(admin);
5467 } catch (RemoteException e) {
5468 throw e.rethrowFromSystemServer();
5469 }
5470 }
5471 return true;
5472 }
5473
5474 /**
5475 * Returns whether the given user's credential will be sufficient for all password policy
5476 * requirement, once the user's profile has switched to unified challenge.
5477 *
5478 * <p>This is different from {@link #isActivePasswordSufficient()} since once the profile
5479 * switches to unified challenge, policies set explicitly on the profile will start to affect
5480 * the parent user.
5481 * @param userHandle the user whose password requirement will be checked
5482 * @param profileUser the profile user whose lockscreen challenge will be unified.
5483 * @hide
5484 */
5485 public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
5486 if (mService != null) {
5487 try {
5488 return mService.isPasswordSufficientAfterProfileUnification(userHandle,
5489 profileUser);
5490 } catch (RemoteException e) {
5491 throw e.rethrowFromSystemServer();
5492 }
5493 }
5494 return false;
5495 }
5496 /**
5497 * Retrieve the number of times the user has failed at entering a password since that last
5498 * successful password entry.
5499 * <p>
5500 * This method can be called on the {@link DevicePolicyManager} instance returned by
5501 * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
5502 * password attemts for the parent user.
5503 * <p>
5504 * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
5505 * to be able to call this method; if it has not, a security exception will be thrown.
5506 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5507 * password is always empty and this method always returns 0.
5508 *
5509 * @return The number of times user has entered an incorrect password since the last correct
5510 * password entry.
5511 * @throws SecurityException if the calling application does not own an active administrator
5512 * that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
5513 */
5514 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5515 public int getCurrentFailedPasswordAttempts() {
5516 return getCurrentFailedPasswordAttempts(myUserId());
5517 }
5518
5519 /**
5520 * Retrieve the number of times the given user has failed at entering a
5521 * password since that last successful password entry.
5522 *
5523 * <p>The calling device admin must have requested
5524 * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
5525 * not and it is not the system uid, a security exception will be thrown.
5526 *
5527 * @hide
5528 */
5529 @UnsupportedAppUsage
5530 public int getCurrentFailedPasswordAttempts(int userHandle) {
5531 if (mService != null) {
5532 try {
5533 return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
5534 } catch (RemoteException e) {
5535 throw e.rethrowFromSystemServer();
5536 }
5537 }
5538 return -1;
5539 }
5540
5541 /**
5542 * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
5543 *
5544 * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
5545 * @hide
5546 */
5547 public boolean getDoNotAskCredentialsOnBoot() {
5548 if (mService != null) {
5549 try {
5550 return mService.getDoNotAskCredentialsOnBoot();
5551 } catch (RemoteException e) {
5552 throw e.rethrowFromSystemServer();
5553 }
5554 }
5555 return false;
5556 }
5557
5558 /**
5559 * Setting this to a value greater than zero enables a built-in policy that will perform a
5560 * device or profile wipe after too many incorrect device-unlock passwords have been entered.
5561 * This built-in policy combines watching for failed passwords and wiping the device, and
5562 * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
5563 * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
5564 * <p>
5565 * When this policy is set by a device owner, profile owner of an organization-owned device or
5566 * an admin on the primary user, the device will be factory reset after too many incorrect
5567 * password attempts. When set by a profile owner or an admin on a secondary user or a managed
5568 * profile, only the corresponding user or profile will be wiped.
5569 * <p>
5570 * To implement any other policy (e.g. wiping data for a particular application only, erasing or
5571 * revoking credentials, or reporting the failure to a server), you should implement
5572 * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
5573 * use this API, because if the maximum count is reached, the device or profile will be wiped
5574 * immediately, and your callback will not be invoked.
5575 * <p>
5576 * This method can be called on the {@link DevicePolicyManager} instance returned by
5577 * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
5578 * profile.
5579 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5580 * password is always empty and this method has no effect - i.e. the policy is not set.
5581 *
5582 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5583 * @param num The number of failed password attempts at which point the device or profile will
5584 * be wiped.
5585 * @throws SecurityException if {@code admin} is not an active administrator or does not use
5586 * both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
5587 * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
5588 */
5589 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5590 public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
5591 if (mService != null) {
5592 try {
5593 mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
5594 } catch (RemoteException e) {
5595 throw e.rethrowFromSystemServer();
5596 }
5597 }
5598 }
5599
5600 /**
5601 * Retrieve the current maximum number of login attempts that are allowed before the device
5602 * or profile is wiped, for a particular admin or all admins that set restrictions on this user
5603 * and its participating profiles. Restrictions on profiles that have a separate challenge are
5604 * not taken into account.
5605 *
5606 * <p>This method can be called on the {@link DevicePolicyManager} instance
5607 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5608 * the value for the parent profile.
5609 *
5610 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5611 * password is always empty and this method returns a default value (0) indicating that the
5612 * policy is not set.
5613 *
5614 * @param admin The name of the admin component to check, or {@code null} to aggregate
5615 * all admins.
5616 */
5617 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5618 public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
5619 return getMaximumFailedPasswordsForWipe(admin, myUserId());
5620 }
5621
5622 /** @hide per-user version */
5623 @UnsupportedAppUsage
5624 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5625 public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
5626 if (mService != null) {
5627 try {
5628 return mService.getMaximumFailedPasswordsForWipe(
5629 admin, userHandle, mParentInstance);
5630 } catch (RemoteException e) {
5631 throw e.rethrowFromSystemServer();
5632 }
5633 }
5634 return 0;
5635 }
5636
5637 /**
5638 * Returns the user that will be wiped first when too many failed attempts are made to unlock
5639 * user {@code userHandle}. That user is either the same as {@code userHandle} or belongs to the
5640 * same profile group. When there is no such policy, returns {@code UserHandle.USER_NULL}.
5641 * E.g. managed profile user may be wiped as a result of failed primary profile password
5642 * attempts when using unified challenge. Primary user may be wiped as a result of failed
5643 * password attempts on the managed profile on an organization-owned device.
5644 * @hide Used only by Keyguard
5645 */
5646 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5647 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
5648 if (mService != null) {
5649 try {
5650 return mService.getProfileWithMinimumFailedPasswordsForWipe(
5651 userHandle, mParentInstance);
5652 } catch (RemoteException e) {
5653 throw e.rethrowFromSystemServer();
5654 }
5655 }
5656 return UserHandle.USER_NULL;
5657 }
5658
5659 /**
5660 * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
5661 * to change the password again until the user has entered it.
5662 */
5663 public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
5664
5665 /**
5666 * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
5667 * credentials on device boot.
5668 * If the flag is set, the device can be booted without asking for user password.
5669 * The absence of this flag does not change the current boot requirements. This flag
5670 * can be set by the device owner only. If the app is not the device owner, the flag
5671 * is ignored. Once the flag is set, it cannot be reverted back without resetting the
5672 * device to factory defaults.
5673 */
5674 public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
5675
5676 /**
5677 * Force a new password for device unlock (the password needed to access the entire device) or
5678 * the work profile challenge on the current user. This takes effect immediately.
5679 *
5680 * <p> Before {@link android.os.Build.VERSION_CODES#N}, this API is available to device admin,
5681 * profile owner and device owner. Starting from {@link android.os.Build.VERSION_CODES#N},
5682 * legacy device admin (who is not also profile owner or device owner) can only call this
5683 * API to set a new password if there is currently no password set. Profile owner and device
5684 * owner can continue to force change an existing password as long as the target user is
5685 * unlocked, although device owner will not be able to call this API at all if there is also a
5686 * managed profile on the device.
5687 *
5688 * <p> Between {@link android.os.Build.VERSION_CODES#O},
5689 * {@link android.os.Build.VERSION_CODES#P} and {@link android.os.Build.VERSION_CODES#Q},
5690 * profile owner and devices owner targeting SDK level {@link android.os.Build.VERSION_CODES#O}
5691 * or above who attempt to call this API will receive {@link SecurityException}; they are
5692 * encouraged to migrate to the new {@link #resetPasswordWithToken} API instead.
5693 * Profile owner and device owner targeting older SDK levels are not affected: they continue
5694 * to experience the existing behaviour described in the previous paragraph.
5695 *
5696 * <p><em>Starting from {@link android.os.Build.VERSION_CODES#R}, this API is no longer
5697 * supported in most cases.</em> Device owner and profile owner calling
5698 * this API will receive {@link SecurityException} if they target SDK level
5699 * {@link android.os.Build.VERSION_CODES#O} or above, or they will receive a silent failure
5700 * (API returning {@code false}) if they target lower SDK level.
5701 * For legacy device admins, this API throws {@link SecurityException} if they target SDK level
5702 * {@link android.os.Build.VERSION_CODES#N} or above, and returns {@code false} otherwise. Only
5703 * privileged apps holding RESET_PASSWORD permission which are part of
5704 * the system factory image can still call this API to set a new password if there is currently
5705 * no password set. In this case, if the device already has a password, this API will throw
5706 * {@link SecurityException}.
5707 *
5708 * <p>
5709 * The given password must be sufficient for the current password quality and length constraints
5710 * as returned by {@link #getPasswordQuality(ComponentName)} and
5711 * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
5712 * it will be rejected and false returned. Note that the password may be a stronger quality
5713 * (containing alphanumeric characters when the requested quality is only numeric), in which
5714 * case the currently active quality will be increased to match.
5715 *
5716 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
5717 * methods does nothing.
5718 * <p>
5719 * The calling device admin must have requested
5720 * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
5721 * not, a security exception will be thrown.
5722 *
5723 * @param password The new password for the user. Null or empty clears the password.
5724 * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
5725 * {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
5726 * @return Returns true if the password was applied, or false if it is not acceptable for the
5727 * current constraints.
5728 * @throws SecurityException if the calling application does not own an active administrator
5729 * that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
5730 * @throws IllegalStateException if the calling user is locked or has a managed profile.
5731 * @deprecated Please use {@link #resetPasswordWithToken} instead.
5732 */
5733 @Deprecated
5734 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5735 public boolean resetPassword(String password, int flags) {
5736 throwIfParentInstance("resetPassword");
5737 if (mService != null) {
5738 try {
5739 return mService.resetPassword(password, flags);
5740 } catch (RemoteException e) {
5741 throw e.rethrowFromSystemServer();
5742 }
5743 }
5744 return false;
5745 }
5746
5747 /**
5748 * Called by a profile or device owner to provision a token which can later be used to reset the
5749 * device lockscreen password (if called by device owner), or managed profile challenge (if
5750 * called by profile owner), via {@link #resetPasswordWithToken}.
5751 * <p>
5752 * If the user currently has a lockscreen password, the provisioned token will not be
5753 * immediately usable; it only becomes active after the user performs a confirm credential
5754 * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
5755 * If the user has no lockscreen password, the token is activated immediately. In all cases,
5756 * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
5757 * For security reasons, un-activated tokens are only stored in memory and will be lost once
5758 * the device reboots. In this case a new token needs to be provisioned again.
5759 * <p>
5760 * Once provisioned and activated, the token will remain effective even if the user changes
5761 * or clears the lockscreen password.
5762 * <p>
5763 * <em>This token is highly sensitive and should be treated at the same level as user
5764 * credentials. In particular, NEVER store this token on device in plaintext. Do not store
5765 * the plaintext token in device-encrypted storage if it will be needed to reset password on
5766 * file-based encryption devices before user unlocks. Consider carefully how any password token
5767 * will be stored on your server and who will need access to them. Tokens may be the subject of
5768 * legal access requests.
5769 * </em>
5770 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5771 * reset token is not set and this method returns false.
5772 *
5773 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5774 * @param token a secure token a least 32-byte long, which must be generated by a
5775 * cryptographically strong random number generator.
5776 * @return true if the operation is successful, false otherwise.
5777 * @throws SecurityException if admin is not a device or profile owner.
5778 * @throws IllegalArgumentException if the supplied token is invalid.
5779 */
5780 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5781 public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
5782 throwIfParentInstance("setResetPasswordToken");
5783 if (mService != null) {
5784 try {
5785 return mService.setResetPasswordToken(admin, token);
5786 } catch (RemoteException e) {
5787 throw e.rethrowFromSystemServer();
5788 }
5789 }
5790 return false;
5791 }
5792
5793 /**
5794 * Called by a profile or device owner to revoke the current password reset token.
5795 *
5796 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
5797 * method has no effect - the reset token should not have been set in the first place - and
5798 * false is returned.
5799 *
5800 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5801 * @return true if the operation is successful, false otherwise.
5802 * @throws SecurityException if admin is not a device or profile owner.
5803 */
5804 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5805 public boolean clearResetPasswordToken(ComponentName admin) {
5806 throwIfParentInstance("clearResetPasswordToken");
5807 if (mService != null) {
5808 try {
5809 return mService.clearResetPasswordToken(admin);
5810 } catch (RemoteException e) {
5811 throw e.rethrowFromSystemServer();
5812 }
5813 }
5814 return false;
5815 }
5816
5817 /**
5818 * Called by a profile or device owner to check if the current reset password token is active.
5819 *
5820 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5821 * false is always returned.
5822 *
5823 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5824 * @return true if the token is active, false otherwise.
5825 * @throws SecurityException if admin is not a device or profile owner.
5826 * @throws IllegalStateException if no token has been set.
5827 */
5828 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5829 public boolean isResetPasswordTokenActive(ComponentName admin) {
5830 throwIfParentInstance("isResetPasswordTokenActive");
5831 if (mService != null) {
5832 try {
5833 return mService.isResetPasswordTokenActive(admin);
5834 } catch (RemoteException e) {
5835 throw e.rethrowFromSystemServer();
5836 }
5837 }
5838 return false;
5839 }
5840
5841 /**
5842 * Called by device or profile owner to force set a new device unlock password or a managed
5843 * profile challenge on current user. This takes effect immediately.
5844 * <p>
5845 * Unlike {@link #resetPassword}, this API can change the password even before the user or
5846 * device is unlocked or decrypted. The supplied token must have been previously provisioned via
5847 * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
5848 * <p>
5849 * The given password must be sufficient for the current password quality and length constraints
5850 * as returned by {@link #getPasswordQuality(ComponentName)} and
5851 * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
5852 * it will be rejected and false returned. Note that the password may be a stronger quality, for
5853 * example, a password containing alphanumeric characters when the requested quality is only
5854 * numeric.
5855 * <p>
5856 * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
5857 * password if the current password constraints allow it.
5858 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5859 * calling this methods has no effect - the password is always empty - and false is returned.
5860 *
5861 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5862 * @param password The new password for the user. {@code null} or empty clears the password.
5863 * @param token the password reset token previously provisioned by
5864 * {@link #setResetPasswordToken}.
5865 * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
5866 * {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
5867 * @return Returns true if the password was applied, or false if it is not acceptable for the
5868 * current constraints.
5869 * @throws SecurityException if admin is not a device or profile owner.
5870 * @throws IllegalStateException if the provided token is not valid.
5871 */
5872 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5873 public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
5874 byte[] token, int flags) {
5875 throwIfParentInstance("resetPassword");
5876 if (mService != null) {
5877 try {
5878 return mService.resetPasswordWithToken(admin, password, token, flags);
5879 } catch (RemoteException e) {
5880 throw e.rethrowFromSystemServer();
5881 }
5882 }
5883 return false;
5884 }
5885
5886 /**
5887 * Called by an application that is administering the device to set the maximum time for user
5888 * activity until the device will lock. This limits the length that the user can set. It takes
5889 * effect immediately.
5890 * <p>
5891 * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5892 * to be able to call this method; if it has not, a security exception will be thrown.
5893 * <p>
5894 * This method can be called on the {@link DevicePolicyManager} instance returned by
5895 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5896 * profile.
5897 *
5898 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5899 * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
5900 * is no restriction.
5901 * @throws SecurityException if {@code admin} is not an active administrator or it does not use
5902 * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5903 */
5904 public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
5905 if (mService != null) {
5906 try {
5907 mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
5908 } catch (RemoteException e) {
5909 throw e.rethrowFromSystemServer();
5910 }
5911 }
5912 }
5913
5914 /**
5915 * Retrieve the current maximum time to unlock for a particular admin or all admins that set
5916 * restrictions on this user and its participating profiles. Restrictions on profiles that have
5917 * a separate challenge are not taken into account.
5918 *
5919 * <p>This method can be called on the {@link DevicePolicyManager} instance
5920 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5921 * restrictions on the parent profile.
5922 *
5923 * @param admin The name of the admin component to check, or {@code null} to aggregate
5924 * all admins.
5925 * @return time in milliseconds for the given admin or the minimum value (strictest) of
5926 * all admins if admin is null. Returns 0 if there are no restrictions.
5927 */
5928 public long getMaximumTimeToLock(@Nullable ComponentName admin) {
5929 return getMaximumTimeToLock(admin, myUserId());
5930 }
5931
5932 /** @hide per-user version */
5933 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5934 public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
5935 if (mService != null) {
5936 try {
5937 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
5938 } catch (RemoteException e) {
5939 throw e.rethrowFromSystemServer();
5940 }
5941 }
5942 return 0;
5943 }
5944
5945 /**
5946 * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
5947 * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a
5948 * strong authentication method like password, pin or pattern.
5949 *
5950 * <p>This timeout is used internally to reset the timer to require strong auth again after
5951 * specified timeout each time it has been successfully used.
5952 *
5953 * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
5954 *
5955 * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
5956 *
5957 * <p>The calling device admin must be a device or profile owner. If it is not,
5958 * a {@link SecurityException} will be thrown.
5959 *
5960 * <p>The calling device admin can verify the value it has set by calling
5961 * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
5962 *
5963 * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
5964 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5965 * profile.
5966 *
5967 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5968 * calling this methods has no effect - i.e. the timeout is not set.
5969 *
5970 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5971 * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
5972 * with strong authentication method. A value of 0 means the admin is not participating
5973 * in controlling the timeout.
5974 * The minimum and maximum timeouts are platform-defined and are typically 1 hour and
5975 * 72 hours, respectively. Though discouraged, the admin may choose to require strong
5976 * auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
5977 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
5978 *
5979 * @throws SecurityException if {@code admin} is not a device or profile owner.
5980 */
5981 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5982 public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
5983 long timeoutMs) {
5984 if (mService != null) {
5985 try {
5986 mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
5987 } catch (RemoteException e) {
5988 throw e.rethrowFromSystemServer();
5989 }
5990 }
5991 }
5992
5993 /**
5994 * Determine for how long the user will be able to use secondary, non strong auth for
5995 * authentication, since last strong method authentication (password, pin or pattern) was used.
5996 * After the returned timeout the user is required to use strong authentication method.
5997 *
5998 * <p>This method can be called on the {@link DevicePolicyManager} instance
5999 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
6000 * restrictions on the parent profile.
6001 *
6002 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6003 * 0 is returned to indicate that no timeout is configured.
6004 *
6005 * @param admin The name of the admin component to check, or {@code null} to aggregate
6006 * across all participating admins.
6007 * @return The timeout in milliseconds or 0 if not configured for the provided admin.
6008 */
6009 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6010 public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
6011 return getRequiredStrongAuthTimeout(admin, myUserId());
6012 }
6013
6014 /** @hide per-user version */
6015 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
6016 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6017 public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
6018 if (mService != null) {
6019 try {
6020 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
6021 } catch (RemoteException e) {
6022 throw e.rethrowFromSystemServer();
6023 }
6024 }
6025 return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
6026 }
6027
6028 /**
6029 * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
6030 * keyring. The user's credential will need to be entered again in order to derive the
6031 * credential encryption key that will be stored back in the keyring for future use.
6032 * <p>
6033 * This flag can only be used by a profile owner when locking a managed profile when
6034 * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6035 * <p>
6036 * In order to secure user data, the user will be stopped and restarted so apps should wait
6037 * until they are next run to perform further actions.
6038 */
6039 public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
6040
6041 /** @hide */
6042 @Retention(RetentionPolicy.SOURCE)
6043 @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
6044 FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
6045 })
6046 public @interface LockNowFlag {}
6047
6048 /**
6049 * Make the device lock immediately, as if the lock screen timeout has expired at the point of
6050 * this call.
6051 * <p>
6052 * This method secures the device in response to an urgent situation, such as a lost or stolen
6053 * device. After this method is called, the device must be unlocked using strong authentication
6054 * (PIN, pattern, or password). This API is intended for use only by device admins.
6055 * <p>
6056 * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
6057 * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
6058 * true, then the method will return without completing any action. Before version
6059 * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
6060 * regardless of the caller's permissions.
6061 * <p>
6062 * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6063 * to be able to call this method; if it has not, a security exception will be thrown.
6064 * <p>
6065 * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
6066 * the device. Device admins who find the device in this state can lock an otherwise-insecure
6067 * device by first calling {@link #resetPassword} to set the password and then lock the device.
6068 * <p>
6069 * This method can be called on the {@link DevicePolicyManager} instance returned by
6070 * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
6071 * <p>
6072 * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
6073 * method doesn't turn off the screen as it would be a driving safety distraction.
6074 * <p>
6075 * Equivalent to calling {@link #lockNow(int)} with no flags.
6076 *
6077 * @throws SecurityException if the calling application does not own an active administrator
6078 * that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6079 */
6080 public void lockNow() {
6081 lockNow(0);
6082 }
6083
6084 /**
6085 * Make the device lock immediately, as if the lock screen timeout has expired at the point of
6086 * this call.
6087 * <p>
6088 * This method secures the device in response to an urgent situation, such as a lost or stolen
6089 * device. After this method is called, the device must be unlocked using strong authentication
6090 * (PIN, pattern, or password). This API is intended for use only by device admins.
6091 * <p>
6092 * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
6093 * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
6094 * true, then the method will return without completing any action. Before version
6095 * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
6096 * regardless of the caller's permissions.
6097 * <p>
6098 * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6099 * to be able to call this method; if it has not, a security exception will be thrown.
6100 * <p>
6101 * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
6102 * the device. Device admins who find the device in this state can lock an otherwise-insecure
6103 * device by first calling {@link #resetPassword} to set the password and then lock the device.
6104 * <p>
6105 * This method can be called on the {@link DevicePolicyManager} instance returned by
6106 * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile as
6107 * well as the managed profile.
6108 * <p>
6109 * NOTE: In order to lock the parent profile and evict the encryption key of the managed
6110 * profile, {@link #lockNow()} must be called twice: First, {@link #lockNow()} should be called
6111 * on the {@link DevicePolicyManager} instance returned by
6112 * {@link #getParentProfileInstance(ComponentName)}, then {@link #lockNow(int)} should be
6113 * called on the {@link DevicePolicyManager} instance associated with the managed profile,
6114 * with the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag.
6115 * Calling the method twice in this order ensures that all users are locked and does not
6116 * stop the device admin on the managed profile from issuing a second call to lock its own
6117 * profile.
6118 * <p>
6119 * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
6120 * method doesn't turn off the screen as it would be a driving safety distraction.
6121 *
6122 * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
6123 * @throws SecurityException if the calling application does not own an active administrator
6124 * that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
6125 * {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
6126 * that is not a profile
6127 * owner of a managed profile.
6128 * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
6129 * passed when locking the parent profile.
6130 * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
6131 * flag is passed when {@link #getStorageEncryptionStatus} does not return
6132 * {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6133 */
6134 public void lockNow(@LockNowFlag int flags) {
6135 if (mService != null) {
6136 try {
6137 mService.lockNow(flags, mParentInstance);
6138 } catch (RemoteException e) {
6139 throw e.rethrowFromSystemServer();
6140 }
6141 }
6142 }
6143
6144 /**
6145 * Flag for {@link #wipeData(int)}: also erase the device's external
6146 * storage (such as SD cards).
6147 */
6148 public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
6149
6150 /**
6151 * Flag for {@link #wipeData(int)}: also erase the factory reset protection
6152 * data.
6153 *
6154 * <p>This flag may only be set by device owner admins; if it is set by
6155 * other admins a {@link SecurityException} will be thrown.
6156 */
6157 public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
6158
6159 /**
6160 * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
6161 */
6162 public static final int WIPE_EUICC = 0x0004;
6163
6164 /**
6165 * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
6166 */
6167 public static final int WIPE_SILENTLY = 0x0008;
6168
6169 /**
6170 * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
6171 * other users will remain unaffected. Calling from the primary user will cause the device to
6172 * reboot, erasing all device data - including all the secondary users and their data - while
6173 * booting up.
6174 * <p>
6175 * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
6176 * be able to call this method; if it has not, a security exception will be thrown.
6177 *
6178 * If the caller is a profile owner of an organization-owned managed profile, it may
6179 * additionally call this method on the parent instance.
6180 * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
6181 * entire device, while calling it on the current profile instance would relinquish the device
6182 * for personal use, removing the managed profile and all policies set by the profile owner.
6183 *
6184 * @param flags Bit mask of additional options: currently supported flags are
6185 * {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
6186 * {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
6187 * @throws SecurityException if the calling application does not own an active administrator
6188 * that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} or is not granted the
6189 * {@link android.Manifest.permission#MASTER_CLEAR} permission.
6190 */
6191 public void wipeData(int flags) {
6192 wipeDataInternal(flags, "");
6193 }
6194
6195 /**
6196 * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
6197 * other users will remain unaffected, the provided reason for wiping data can be shown to
6198 * user. Calling from the primary user will cause the device to reboot, erasing all device data
6199 * - including all the secondary users and their data - while booting up. In this case, we don't
6200 * show the reason to the user since the device would be factory reset.
6201 * <p>
6202 * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
6203 * be able to call this method; if it has not, a security exception will be thrown.
6204 *
6205 * If the caller is a profile owner of an organization-owned managed profile, it may
6206 * additionally call this method on the parent instance.
6207 * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
6208 * entire device, while calling it on the current profile instance would relinquish the device
6209 * for personal use, removing the managed profile and all policies set by the profile owner.
6210 *
6211 * @param flags Bit mask of additional options: currently supported flags are
6212 * {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
6213 * {@link #WIPE_EUICC}.
6214 * @param reason a string that contains the reason for wiping data, which can be
6215 * presented to the user.
6216 * @throws SecurityException if the calling application does not own an active administrator
6217 * that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} or is not granted the
6218 * {@link android.Manifest.permission#MASTER_CLEAR} permission.
6219 * @throws IllegalArgumentException if the input reason string is null or empty, or if
6220 * {@link #WIPE_SILENTLY} is set.
6221 */
6222 public void wipeData(int flags, @NonNull CharSequence reason) {
6223 Objects.requireNonNull(reason, "reason string is null");
6224 Preconditions.checkStringNotEmpty(reason, "reason string is empty");
6225 Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
6226 wipeDataInternal(flags, reason.toString());
6227 }
6228
6229 /**
6230 * Internal function for both {@link #wipeData(int)} and
6231 * {@link #wipeData(int, CharSequence)} to call.
6232 *
6233 * @see #wipeData(int)
6234 * @see #wipeData(int, CharSequence)
6235 * @hide
6236 */
6237 private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
6238 if (mService != null) {
6239 try {
6240 mService.wipeDataWithReason(flags, wipeReasonForUser, mParentInstance);
6241 } catch (RemoteException e) {
6242 throw e.rethrowFromSystemServer();
6243 }
6244 }
6245 }
6246
6247 /**
6248 * Callable by device owner or profile owner of an organization-owned device, to set a
6249 * factory reset protection (FRP) policy. When a new policy is set, the system
6250 * notifies the FRP management agent of a policy change by broadcasting
6251 * {@code ACTION_RESET_PROTECTION_POLICY_CHANGED}.
6252 *
6253 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6254 * @param policy the new FRP policy, or {@code null} to clear the current policy.
6255 * @throws SecurityException if {@code admin} is not a device owner or a profile owner of
6256 * an organization-owned device.
6257 * @throws UnsupportedOperationException if factory reset protection is not
6258 * supported on the device.
6259 */
6260 public void setFactoryResetProtectionPolicy(@NonNull ComponentName admin,
6261 @Nullable FactoryResetProtectionPolicy policy) {
6262 throwIfParentInstance("setFactoryResetProtectionPolicy");
6263 if (mService != null) {
6264 try {
6265 mService.setFactoryResetProtectionPolicy(admin, policy);
6266 } catch (RemoteException e) {
6267 throw e.rethrowFromSystemServer();
6268 }
6269 }
6270 }
6271
6272 /**
6273 * Callable by device owner or profile owner of an organization-owned device, to retrieve
6274 * the current factory reset protection (FRP) policy set previously by
6275 * {@link #setFactoryResetProtectionPolicy}.
6276 * <p>
6277 * This method can also be called by the FRP management agent on device or with the permission
6278 * {@link android.Manifest.permission#MASTER_CLEAR}, in which case, it can pass {@code null}
6279 * as the ComponentName.
6280 *
6281 * @param admin Which {@link DeviceAdminReceiver} this request is associated with or
6282 * {@code null} if called by the FRP management agent on device or with the
6283 * permission {@link android.Manifest.permission#MASTER_CLEAR}.
6284 * @return The current FRP policy object or {@code null} if no policy is set.
6285 * @throws SecurityException if {@code admin} is not a device owner, a profile owner of
6286 * an organization-owned device or the FRP management agent.
6287 * @throws UnsupportedOperationException if factory reset protection is not
6288 * supported on the device.
6289 */
6290 public @Nullable FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
6291 @Nullable ComponentName admin) {
6292 throwIfParentInstance("getFactoryResetProtectionPolicy");
6293 if (mService != null) {
6294 try {
6295 return mService.getFactoryResetProtectionPolicy(admin);
6296 } catch (RemoteException e) {
6297 throw e.rethrowFromSystemServer();
6298 }
6299 }
6300 return null;
6301 }
6302
6303 /**
6304 * Send a lost mode location update to the admin. This API is limited to organization-owned
6305 * devices, which includes devices with a device owner or devices with a profile owner on an
6306 * organization-owned managed profile.
6307 *
6308 * <p>The caller must hold the
6309 * {@link android.Manifest.permission#TRIGGER_LOST_MODE} permission.
6310 *
6311 * <p> Not for use by third-party applications.
6312 *
6313 * @param executor The executor through which the callback should be invoked.
6314 * @param callback A callback object that will inform the caller whether a lost mode location
6315 * update was successfully sent
6316 * @hide
6317 */
6318 @SystemApi
6319 @RequiresPermission(android.Manifest.permission.TRIGGER_LOST_MODE)
6320 public void sendLostModeLocationUpdate(@NonNull @CallbackExecutor Executor executor,
6321 @NonNull Consumer<Boolean> callback) {
6322 throwIfParentInstance("sendLostModeLocationUpdate");
6323 if (mService == null) {
6324 executeCallback(AndroidFuture.completedFuture(false), executor, callback);
6325 return;
6326 }
6327 try {
6328 final AndroidFuture<Boolean> future = new AndroidFuture<>();
6329 mService.sendLostModeLocationUpdate(future);
6330 executeCallback(future, executor, callback);
6331 } catch (RemoteException e) {
6332 throw e.rethrowFromSystemServer();
6333 }
6334 }
6335
6336 private void executeCallback(AndroidFuture<Boolean> future,
6337 @CallbackExecutor @NonNull Executor executor,
6338 Consumer<Boolean> callback) {
6339 future.whenComplete((result, error) -> executor.execute(() -> {
6340 final long token = Binder.clearCallingIdentity();
6341 try {
6342 if (error != null) {
6343 callback.accept(false);
6344 } else {
6345 callback.accept(result);
6346 }
6347 } finally {
6348 Binder.restoreCallingIdentity(token);
6349 }
6350 }));
6351 }
6352
6353 /**
6354 * Called by an application that is administering the device to set the
6355 * global proxy and exclusion list.
6356 * <p>
6357 * The calling device admin must have requested
6358 * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
6359 * this method; if it has not, a security exception will be thrown.
6360 * Only the first device admin can set the proxy. If a second admin attempts
6361 * to set the proxy, the {@link ComponentName} of the admin originally setting the
6362 * proxy will be returned. If successful in setting the proxy, {@code null} will
6363 * be returned.
6364 * The method can be called repeatedly by the device admin alrady setting the
6365 * proxy to update the proxy and exclusion list.
6366 *
6367 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6368 * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
6369 * Pass Proxy.NO_PROXY to reset the proxy.
6370 * @param exclusionList a list of domains to be excluded from the global proxy.
6371 * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
6372 * of the device admin that sets the proxy.
6373 * @hide
6374 */
6375 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
6376 public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
6377 List<String> exclusionList ) {
6378 throwIfParentInstance("setGlobalProxy");
6379 if (proxySpec == null) {
6380 throw new NullPointerException();
6381 }
6382 if (mService != null) {
6383 try {
6384 String hostSpec;
6385 String exclSpec;
6386 if (proxySpec.equals(Proxy.NO_PROXY)) {
6387 hostSpec = null;
6388 exclSpec = null;
6389 } else {
6390 if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
6391 throw new IllegalArgumentException();
6392 }
6393 final Pair<String, String> proxyParams =
6394 getProxyParameters(proxySpec, exclusionList);
6395 hostSpec = proxyParams.first;
6396 exclSpec = proxyParams.second;
6397 }
6398 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
6399 } catch (RemoteException e) {
6400 throw e.rethrowFromSystemServer();
6401 }
6402 }
6403 return null;
6404 }
6405
6406 /**
6407 * Build HTTP proxy parameters for {@link IDevicePolicyManager#setGlobalProxy}.
6408 * @throws IllegalArgumentException Invalid proxySpec
6409 * @hide
6410 */
6411 @VisibleForTesting
6412 public Pair<String, String> getProxyParameters(Proxy proxySpec, List<String> exclusionList) {
6413 InetSocketAddress sa = (InetSocketAddress) proxySpec.address();
6414 String hostName = sa.getHostName();
6415 int port = sa.getPort();
6416 final List<String> trimmedExclList;
6417 if (exclusionList == null) {
6418 trimmedExclList = Collections.emptyList();
6419 } else {
6420 trimmedExclList = new ArrayList<>(exclusionList.size());
6421 for (String exclDomain : exclusionList) {
6422 trimmedExclList.add(exclDomain.trim());
6423 }
6424 }
6425 final ProxyInfo info = ProxyInfo.buildDirectProxy(hostName, port, trimmedExclList);
6426 // The hostSpec is built assuming that there is a specified port and hostname,
6427 // but ProxyInfo.isValid() accepts 0 / empty as unspecified: also reject them.
6428 if (port == 0 || TextUtils.isEmpty(hostName) || !info.isValid()) {
6429 throw new IllegalArgumentException();
6430 }
6431
6432 return new Pair<>(hostName + ":" + port, TextUtils.join(",", trimmedExclList));
6433 }
6434
6435 /**
6436 * Set a network-independent global HTTP proxy. This is not normally what you want for typical
6437 * HTTP proxies - they are generally network dependent. However if you're doing something
6438 * unusual like general internal filtering this may be useful. On a private network where the
6439 * proxy is not accessible, you may break HTTP using this.
6440 * <p>
6441 * This method requires the caller to be the device owner.
6442 * <p>
6443 * This proxy is only a recommendation and it is possible that some apps will ignore it.
6444 * <p>
6445 * Note: The device owner won't be able to set a global HTTP proxy if there are unaffiliated
6446 * secondary users or profiles on the device. It's recommended that affiliation ids are set for
6447 * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
6448 *
6449 * @see ProxyInfo
6450 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6451 * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
6452 * {@code null} value will clear the global HTTP proxy.
6453 * @throws SecurityException if {@code admin} is not the device owner.
6454 */
6455 public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
6456 proxyInfo) {
6457 throwIfParentInstance("setRecommendedGlobalProxy");
6458 if (mService != null) {
6459 try {
6460 mService.setRecommendedGlobalProxy(admin, proxyInfo);
6461 } catch (RemoteException e) {
6462 throw e.rethrowFromSystemServer();
6463 }
6464 }
6465 }
6466
6467 /**
6468 * Returns the component name setting the global proxy.
6469 * @return ComponentName object of the device admin that set the global proxy, or {@code null}
6470 * if no admin has set the proxy.
6471 * @hide
6472 */
6473 public @Nullable ComponentName getGlobalProxyAdmin() {
6474 if (mService != null) {
6475 try {
6476 return mService.getGlobalProxyAdmin(myUserId());
6477 } catch (RemoteException e) {
6478 throw e.rethrowFromSystemServer();
6479 }
6480 }
6481 return null;
6482 }
6483
6484 /**
6485 * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
6486 * indicating that encryption is not supported.
6487 */
6488 public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
6489
6490 /**
6491 * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
6492 * indicating that encryption is supported, but is not currently active.
6493 */
6494 public static final int ENCRYPTION_STATUS_INACTIVE = 1;
6495
6496 /**
6497 * Result code for {@link #getStorageEncryptionStatus}:
6498 * indicating that encryption is not currently active, but is currently
6499 * being activated. This is only reported by devices that support
6500 * encryption of data and only when the storage is currently
6501 * undergoing a process of becoming encrypted. A device that must reboot and/or wipe data
6502 * to become encrypted will never return this value.
6503 */
6504 public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
6505
6506 /**
6507 * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
6508 * indicating that encryption is active.
6509 * <p>
6510 * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6511 */
6512 public static final int ENCRYPTION_STATUS_ACTIVE = 3;
6513
6514 /**
6515 * Result code for {@link #getStorageEncryptionStatus}:
6516 * indicating that encryption is active, but an encryption key has not
6517 * been set by the user.
6518 */
6519 public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
6520
6521 /**
6522 * Result code for {@link #getStorageEncryptionStatus}:
6523 * indicating that encryption is active and the encryption key is tied to the user or profile.
6524 * <p>
6525 * This value is only returned to apps targeting API level 24 and above. For apps targeting
6526 * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
6527 * encryption key is specific to the user or profile.
6528 */
6529 public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
6530
6531 /**
6532 * Activity action: begin the process of encrypting data on the device. This activity should
6533 * be launched after using {@link #setStorageEncryption} to request encryption be activated.
6534 * After resuming from this activity, use {@link #getStorageEncryption}
6535 * to check encryption status. However, on some devices this activity may never return, as
6536 * it may trigger a reboot and in some cases a complete data wipe of the device.
6537 */
6538 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
6539 public static final String ACTION_START_ENCRYPTION
6540 = "android.app.action.START_ENCRYPTION";
6541
6542 /**
6543 * Activity action: launch the DPC to check policy compliance. This intent is launched when
6544 * the user taps on the notification about personal apps suspension. When handling this intent
6545 * the DPC must check if personal apps should still be suspended and either unsuspend them or
6546 * instruct the user on how to resolve the noncompliance causing the suspension.
6547 *
6548 * @see #setPersonalAppsSuspended
6549 */
6550 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
6551 public static final String ACTION_CHECK_POLICY_COMPLIANCE =
6552 "android.app.action.CHECK_POLICY_COMPLIANCE";
6553
6554 /**
6555 * Broadcast action: notify managed provisioning that PO/DO provisioning has completed.
6556 *
6557 * @hide
6558 */
6559 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
6560 public static final String ACTION_PROVISIONING_COMPLETED =
6561 "android.app.action.PROVISIONING_COMPLETED";
6562
6563 /**
6564 * Extra for {@link #ACTION_PROVISIONING_COMPLETED} to indicate the provisioning action that has
6565 * been completed, this can either be {@link #ACTION_PROVISION_MANAGED_PROFILE},
6566 * {@link #ACTION_PROVISION_MANAGED_DEVICE}, or {@link #ACTION_PROVISION_MANAGED_USER}.
6567 *
6568 * @hide
6569 */
6570 public static final String EXTRA_PROVISIONING_ACTION =
6571 "android.app.extra.PROVISIONING_ACTION";
6572
6573 /**
6574 * Broadcast action: notify system that a new (Android) user was added when the device is
6575 * managed by a device owner, so receivers can show the proper disclaimer to the (human) user.
6576 *
6577 * @hide
6578 */
6579 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
6580 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
6581 public static final String ACTION_SHOW_NEW_USER_DISCLAIMER =
6582 "android.app.action.SHOW_NEW_USER_DISCLAIMER";
6583
6584 /**
6585 * Widgets are enabled in keyguard
6586 */
6587 public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
6588
6589 /**
6590 * Disable all keyguard widgets. Has no effect starting from
6591 * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
6592 * on Android versions lower than 5.0.
6593 */
6594 public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
6595
6596 /**
6597 * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
6598 */
6599 public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
6600
6601 /**
6602 * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
6603 */
6604 public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
6605
6606 /**
6607 * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
6608 */
6609 public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
6610
6611 /**
6612 * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
6613 * By setting this flag alone, all trust agents are disabled. If the admin then wants to
6614 * allowlist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
6615 * used in conjuction to set trust-agent-specific configurations.
6616 */
6617 public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
6618
6619 /**
6620 * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6621 */
6622 public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
6623
6624 /**
6625 * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
6626 * @deprecated This flag was added in version {@link android.os.Build.VERSION_CODES#N}, but it
6627 * never had any effect.
6628 */
6629 @Deprecated
6630 public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
6631
6632 /**
6633 * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6634 */
6635 public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
6636
6637 /**
6638 * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6639 */
6640 public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
6641
6642 /**
6643 * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
6644 * CTS test when adding to the list above.
6645 */
6646
6647 /**
6648 * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6649 */
6650 public static final int KEYGUARD_DISABLE_BIOMETRICS =
6651 DevicePolicyManager.KEYGUARD_DISABLE_FACE
6652 | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
6653 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
6654
6655 /**
6656 * Disable all current and future keyguard customizations.
6657 */
6658 public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
6659
6660 /**
6661 * Keyguard features that when set on a non-organization-owned managed profile that doesn't
6662 * have its own challenge will affect the profile's parent user. These can also be set on the
6663 * managed profile's parent {@link DevicePolicyManager} instance to explicitly control the
6664 * parent user.
6665 *
6666 * <p>
6667 * Organization-owned managed profile supports disabling additional keyguard features on the
6668 * parent user as defined in {@link #ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY}.
6669 *
6670 * @hide
6671 */
6672 public static final int NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
6673 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
6674 | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
6675
6676 /**
6677 * Keyguard features that when set by the profile owner of an organization-owned managed
6678 * profile will affect the profile's parent user if set on the managed profile's parent
6679 * {@link DevicePolicyManager} instance.
6680 *
6681 * @hide
6682 */
6683 public static final int ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY =
6684 DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA
6685 | DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS;
6686
6687 /**
6688 * Keyguard features that when set on a normal or organization-owned managed profile, have
6689 * the potential to affect the profile's parent user.
6690 *
6691 * @hide
6692 */
6693 public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
6694 DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
6695 | DevicePolicyManager.ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY;
6696
6697 /**
6698 * @deprecated This method does not actually modify the storage encryption of the device.
6699 * It has never affected the encryption status of a device.
6700 *
6701 * Called by an application that is administering the device to request that the storage system
6702 * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
6703 * <p>
6704 * When multiple device administrators attempt to control device encryption, the most secure,
6705 * supported setting will always be used. If any device administrator requests device
6706 * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
6707 * device encryption while another device administrator has enabled it, the call to disable will
6708 * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
6709 * <p>
6710 * This policy controls encryption of the secure (application data) storage area. Data written
6711 * to other storage areas may or may not be encrypted, and this policy does not require or
6712 * control the encryption of any other storage areas. There is one exception: If
6713 * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
6714 * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
6715 * written to disk within the encrypted storage area.
6716 * <p>
6717 * Important Note: On some devices, it is possible to encrypt storage without requiring the user
6718 * to create a device PIN or Password. In this case, the storage is encrypted, but the
6719 * encryption key may not be fully secured. For maximum security, the administrator should also
6720 * require (and check for) a pattern, PIN, or password.
6721 *
6722 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6723 * @param encrypt true to request encryption, false to release any previous request
6724 * @return the new total request status (for all active admins), or {@link
6725 * DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
6726 * Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
6727 * #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
6728 * of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
6729 * state.
6730 *
6731 * @throws SecurityException if {@code admin} is not an active administrator or does not use
6732 * {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
6733 */
6734 @Deprecated
6735 public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
6736 throwIfParentInstance("setStorageEncryption");
6737 if (mService != null) {
6738 try {
6739 return mService.setStorageEncryption(admin, encrypt);
6740 } catch (RemoteException e) {
6741 throw e.rethrowFromSystemServer();
6742 }
6743 }
6744 return ENCRYPTION_STATUS_UNSUPPORTED;
6745 }
6746
6747 /**
6748 * @deprecated This method only returns the value set by {@link #setStorageEncryption}.
6749 * It does not actually reflect the storage encryption status.
6750 * Use {@link #getStorageEncryptionStatus} for that.
6751 *
6752 * Called by an application that is administering the device to
6753 * determine the requested setting for secure storage.
6754 *
6755 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
6756 * this will return the requested encryption setting as an aggregate of all active
6757 * administrators.
6758 * @return true if the admin(s) are requesting encryption, false if not.
6759 */
6760 @Deprecated
6761 public boolean getStorageEncryption(@Nullable ComponentName admin) {
6762 throwIfParentInstance("getStorageEncryption");
6763 if (mService != null) {
6764 try {
6765 return mService.getStorageEncryption(admin, myUserId());
6766 } catch (RemoteException e) {
6767 throw e.rethrowFromSystemServer();
6768 }
6769 }
6770 return false;
6771 }
6772
6773 /**
6774 * Called by an application that is administering the device to
6775 * determine the current encryption status of the device.
6776 * <p>
6777 * Depending on the returned status code, the caller may proceed in different
6778 * ways. If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
6779 * storage system does not support encryption. If the
6780 * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
6781 * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
6782 * storage. If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
6783 * storage system has enabled encryption but no password is set so further action
6784 * may be required. If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
6785 * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
6786 * no further action is required.
6787 *
6788 * @return current status of encryption. The value will be one of
6789 * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
6790 * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
6791 * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6792 */
6793 public int getStorageEncryptionStatus() {
6794 throwIfParentInstance("getStorageEncryptionStatus");
6795 return getStorageEncryptionStatus(myUserId());
6796 }
6797
6798 /** @hide per-user version */
6799 @UnsupportedAppUsage
6800 public int getStorageEncryptionStatus(int userHandle) {
6801 if (mService != null) {
6802 try {
6803 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
6804 } catch (RemoteException e) {
6805 throw e.rethrowFromSystemServer();
6806 }
6807 }
6808 return ENCRYPTION_STATUS_UNSUPPORTED;
6809 }
6810
6811 /**
6812 * Mark a CA certificate as approved by the device user. This means that they have been notified
6813 * of the installation, were made aware of the risks, viewed the certificate and still wanted to
6814 * keep the certificate on the device.
6815 *
6816 * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
6817 * this certificate.
6818 *
6819 * @hide
6820 */
6821 public boolean approveCaCert(String alias, int userHandle, boolean approval) {
6822 if (mService != null) {
6823 try {
6824 return mService.approveCaCert(alias, userHandle, approval);
6825 } catch (RemoteException e) {
6826 throw e.rethrowFromSystemServer();
6827 }
6828 }
6829 return false;
6830 }
6831
6832 /**
6833 * Check whether a CA certificate has been approved by the device user.
6834 *
6835 * @hide
6836 */
6837 public boolean isCaCertApproved(String alias, int userHandle) {
6838 if (mService != null) {
6839 try {
6840 return mService.isCaCertApproved(alias, userHandle);
6841 } catch (RemoteException e) {
6842 throw e.rethrowFromSystemServer();
6843 }
6844 }
6845 return false;
6846 }
6847
6848 /**
6849 * Installs the given certificate as a user CA.
6850 * <p>
6851 * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
6852 * higher. App developers can change the default behavior for an app by adding a
6853 * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
6854 * File</a> to the app manifest file.
6855 *
6856 * The caller must be a profile or device owner on that user, or a delegate package given the
6857 * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
6858 * security exception will be thrown.
6859 *
6860 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6861 * {@code null} if calling from a delegated certificate installer.
6862 * @param certBuffer encoded form of the certificate to install.
6863 *
6864 * @return false if the certBuffer cannot be parsed or installation is
6865 * interrupted, true otherwise.
6866 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6867 * owner.
6868 * @see #setDelegatedScopes
6869 * @see #DELEGATION_CERT_INSTALL
6870 */
6871 public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
6872 throwIfParentInstance("installCaCert");
6873 if (mService != null) {
6874 try {
6875 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
6876 } catch (RemoteException e) {
6877 throw e.rethrowFromSystemServer();
6878 }
6879 }
6880 return false;
6881 }
6882
6883 /**
6884 * Uninstalls the given certificate from trusted user CAs, if present.
6885 *
6886 * The caller must be a profile or device owner on that user, or a delegate package given the
6887 * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
6888 * security exception will be thrown.
6889 *
6890 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6891 * {@code null} if calling from a delegated certificate installer.
6892 * @param certBuffer encoded form of the certificate to remove.
6893 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6894 * owner.
6895 * @see #setDelegatedScopes
6896 * @see #DELEGATION_CERT_INSTALL
6897 */
6898 public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
6899 throwIfParentInstance("uninstallCaCert");
6900 if (mService != null) {
6901 try {
6902 final String alias = getCaCertAlias(certBuffer);
6903 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
6904 } catch (CertificateException e) {
6905 Log.w(TAG, "Unable to parse certificate", e);
6906 } catch (RemoteException e) {
6907 throw e.rethrowFromSystemServer();
6908 }
6909 }
6910 }
6911
6912 /**
6913 * Returns all CA certificates that are currently trusted, excluding system CA certificates.
6914 * If a user has installed any certificates by other means than device policy these will be
6915 * included too.
6916 *
6917 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6918 * {@code null} if calling from a delegated certificate installer.
6919 * @return a List of byte[] arrays, each encoding one user CA certificate.
6920 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6921 * owner.
6922 */
6923 public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
6924 final List<byte[]> certs = new ArrayList<byte[]>();
6925 throwIfParentInstance("getInstalledCaCerts");
6926 if (mService != null) {
6927 try {
6928 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
6929 final TrustedCertificateStore certStore = new TrustedCertificateStore();
6930 for (String alias : certStore.userAliases()) {
6931 try {
6932 certs.add(certStore.getCertificate(alias).getEncoded());
6933 } catch (CertificateException ce) {
6934 Log.w(TAG, "Could not encode certificate: " + alias, ce);
6935 }
6936 }
6937 } catch (RemoteException re) {
6938 throw re.rethrowFromSystemServer();
6939 }
6940 }
6941 return certs;
6942 }
6943
6944 /**
6945 * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
6946 * means other than device policy will also be removed, except for system CA certificates.
6947 *
6948 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6949 * {@code null} if calling from a delegated certificate installer.
6950 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6951 * owner.
6952 */
6953 public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
6954 throwIfParentInstance("uninstallAllUserCaCerts");
6955 if (mService != null) {
6956 try {
6957 mService.uninstallCaCerts(admin, mContext.getPackageName(),
6958 new TrustedCertificateStore().userAliases() .toArray(new String[0]));
6959 } catch (RemoteException re) {
6960 throw re.rethrowFromSystemServer();
6961 }
6962 }
6963 }
6964
6965 /**
6966 * Returns whether this certificate is installed as a trusted CA.
6967 *
6968 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6969 * {@code null} if calling from a delegated certificate installer.
6970 * @param certBuffer encoded form of the certificate to look up.
6971 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6972 * owner.
6973 */
6974 public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
6975 throwIfParentInstance("hasCaCertInstalled");
6976 if (mService != null) {
6977 try {
6978 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
6979 return getCaCertAlias(certBuffer) != null;
6980 } catch (RemoteException re) {
6981 throw re.rethrowFromSystemServer();
6982 } catch (CertificateException ce) {
6983 Log.w(TAG, "Could not parse certificate", ce);
6984 }
6985 }
6986 return false;
6987 }
6988
6989 /**
6990 * This API can be called by the following to install a certificate and corresponding
6991 * private key:
6992 * <ul>
6993 * <li>Device owner</li>
6994 * <li>Profile owner</li>
6995 * <li>Delegated certificate installer</li>
6996 * <li>Credential management app</li>
6997 * </ul>
6998 * All apps within the profile will be able to access the certificate and use the private key,
6999 * given direct user approval.
7000 *
7001 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7002 * can call this API. However, this API sets the key pair as user selectable by default,
7003 * which is not permitted when called by the credential management app. Instead,
7004 * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
7005 * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
7006 *
7007 * <p>Access to the installed credentials will not be granted to the caller of this API without
7008 * direct user approval. This is for security - should a certificate installer become
7009 * compromised, certificates it had already installed will be protected.
7010 *
7011 * <p>If the installer must have access to the credentials, call
7012 * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
7013 *
7014 * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7015 * have been given to access the key and certificates associated with this alias will be
7016 * revoked.
7017 *
7018 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7019 * {@code null} if calling from a delegated certificate installer.
7020 * @param privKey The private key to install.
7021 * @param cert The certificate to install.
7022 * @param alias The private key alias under which to install the certificate. If a certificate
7023 * with that alias already exists, it will be overwritten.
7024 * @return {@code true} if the keys were installed, {@code false} otherwise.
7025 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7026 * owner.
7027 * @see #setDelegatedScopes
7028 * @see #DELEGATION_CERT_INSTALL
7029 */
7030 public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7031 @NonNull Certificate cert, @NonNull String alias) {
7032 return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
7033 }
7034
7035 /**
7036 * This API can be called by the following to install a certificate chain and corresponding
7037 * private key for the leaf certificate:
7038 * <ul>
7039 * <li>Device owner</li>
7040 * <li>Profile owner</li>
7041 * <li>Delegated certificate installer</li>
7042 * <li>Credential management app</li>
7043 * </ul>
7044 * All apps within the profile will be able to access the certificate chain and use the private
7045 * key, given direct user approval.
7046 *
7047 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7048 * can call this API. However, this API sets the key pair as user selectable by default,
7049 * which is not permitted when called by the credential management app. Instead,
7050 * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
7051 * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
7052 * Note, there can only be a credential management app on an unmanaged device.
7053 *
7054 * <p>The caller of this API may grant itself access to the certificate and private key
7055 * immediately, without user approval. It is a best practice not to request this unless strictly
7056 * necessary since it opens up additional security vulnerabilities.
7057 *
7058 * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7059 * have been given to access the key and certificates associated with this alias will be
7060 * revoked.
7061 *
7062 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7063 * {@code null} if calling from a delegated certificate installer.
7064 * @param privKey The private key to install.
7065 * @param certs The certificate chain to install. The chain should start with the leaf
7066 * certificate and include the chain of trust in order. This will be returned by
7067 * {@link android.security.KeyChain#getCertificateChain}.
7068 * @param alias The private key alias under which to install the certificate. If a certificate
7069 * with that alias already exists, it will be overwritten.
7070 * @param requestAccess {@code true} to request that the calling app be granted access to the
7071 * credentials immediately. Otherwise, access to the credentials will be gated by user
7072 * approval.
7073 * @return {@code true} if the keys were installed, {@code false} otherwise.
7074 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7075 * owner.
7076 * @see android.security.KeyChain#getCertificateChain
7077 * @see #setDelegatedScopes
7078 * @see #DELEGATION_CERT_INSTALL
7079 */
7080 public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7081 @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
7082 int flags = INSTALLKEY_SET_USER_SELECTABLE;
7083 if (requestAccess) {
7084 flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
7085 }
7086 return installKeyPair(admin, privKey, certs, alias, flags);
7087 }
7088
7089 /**
7090 * This API can be called by the following to install a certificate chain and corresponding
7091 * private key for the leaf certificate:
7092 * <ul>
7093 * <li>Device owner</li>
7094 * <li>Profile owner</li>
7095 * <li>Delegated certificate installer</li>
7096 * <li>Credential management app</li>
7097 * </ul>
7098 * All apps within the profile will be able to access the certificate chain and use the
7099 * private key, given direct user approval (if the user is allowed to select the private key).
7100 *
7101 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7102 * can call this API. If called by the credential management app:
7103 * <ul>
7104 * <li>The componentName must be {@code null}r</li>
7105 * <li>The alias must exist in the credential management app's
7106 * {@link android.security.AppUriAuthenticationPolicy}</li>
7107 * <li>The key pair must not be user selectable</li>
7108 * </ul>
7109 * Note, there can only be a credential management app on an unmanaged device.
7110 *
7111 * <p>The caller of this API may grant itself access to the certificate and private key
7112 * immediately, without user approval. It is a best practice not to request this unless strictly
7113 * necessary since it opens up additional security vulnerabilities.
7114 *
7115 * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
7116 * the user to select the key from a dialog.
7117 *
7118 * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7119 * have been given to access the key and certificates associated with this alias will be
7120 * revoked.
7121 *
7122 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7123 * {@code null} if calling from a delegated certificate installer.
7124 * @param privKey The private key to install.
7125 * @param certs The certificate chain to install. The chain should start with the leaf
7126 * certificate and include the chain of trust in order. This will be returned by
7127 * {@link android.security.KeyChain#getCertificateChain}.
7128 * @param alias The private key alias under which to install the certificate. If a certificate
7129 * with that alias already exists, it will be overwritten.
7130 * @param flags Flags to request that the calling app be granted access to the credentials
7131 * and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
7132 * {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
7133 * @return {@code true} if the keys were installed, {@code false} otherwise.
7134 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7135 * owner, or {@code admin} is null but the calling application is not a delegated
7136 * certificate installer or credential management app.
7137 * @see android.security.KeyChain#getCertificateChain
7138 * @see #setDelegatedScopes
7139 * @see #DELEGATION_CERT_INSTALL
7140 */
7141 public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7142 @NonNull Certificate[] certs, @NonNull String alias, int flags) {
7143 throwIfParentInstance("installKeyPair");
7144 boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
7145 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
7146 boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
7147 == INSTALLKEY_SET_USER_SELECTABLE;
7148 try {
7149 final byte[] pemCert = Credentials.convertToPem(certs[0]);
7150 byte[] pemChain = null;
7151 if (certs.length > 1) {
7152 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
7153 }
7154 final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
7155 .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
7156 return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
7157 pemChain, alias, requestAccess, isUserSelectable);
7158 } catch (RemoteException e) {
7159 throw e.rethrowFromSystemServer();
7160 } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
7161 Log.w(TAG, "Failed to obtain private key material", e);
7162 } catch (CertificateException | IOException e) {
7163 Log.w(TAG, "Could not pem-encode certificate", e);
7164 }
7165 return false;
7166 }
7167
7168 /**
7169 * This API can be called by the following to remove a certificate and private key pair
7170 * installed under a given alias:
7171 * <ul>
7172 * <li>Device owner</li>
7173 * <li>Profile owner</li>
7174 * <li>Delegated certificate installer</li>
7175 * <li>Credential management app</li>
7176 * </ul>
7177 *
7178 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7179 * can call this API. If called by the credential management app, the componentName must be
7180 * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7181 *
7182 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7183 * {@code null} if calling from a delegated certificate installer.
7184 * @param alias The private key alias under which the certificate is installed.
7185 * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
7186 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7187 * owner, or {@code admin} is null but the calling application is not a delegated
7188 * certificate installer or credential management app.
7189 * @see #setDelegatedScopes
7190 * @see #DELEGATION_CERT_INSTALL
7191 */
7192 public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
7193 throwIfParentInstance("removeKeyPair");
7194 try {
7195 return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
7196 } catch (RemoteException e) {
7197 throw e.rethrowFromSystemServer();
7198 }
7199 }
7200
7201 // STOPSHIP(b/174298501): clarify the expected return value following generateKeyPair call.
7202 /**
7203 * This API can be called by the following to query whether a certificate and private key are
7204 * installed under a given alias:
7205 * <ul>
7206 * <li>Device owner</li>
7207 * <li>Profile owner</li>
7208 * <li>Delegated certificate installer</li>
7209 * <li>Credential management app</li>
7210 * </ul>
7211 *
7212 * If called by the credential management app, the alias must exist in the credential
7213 * management app's {@link android.security.AppUriAuthenticationPolicy}.
7214 *
7215 * @param alias The alias under which the key pair is installed.
7216 * @return {@code true} if a key pair with this alias exists, {@code false} otherwise.
7217 * @throws SecurityException if the caller is not a device or profile owner, a delegated
7218 * certificate installer or the credential management app.
7219 * @see #setDelegatedScopes
7220 * @see #DELEGATION_CERT_INSTALL
7221 */
7222 public boolean hasKeyPair(@NonNull String alias) {
7223 throwIfParentInstance("hasKeyPair");
7224 try {
7225 return mService.hasKeyPair(mContext.getPackageName(), alias);
7226 } catch (RemoteException e) {
7227 throw e.rethrowFromSystemServer();
7228 }
7229 }
7230
7231 /**
7232 * This API can be called by the following to generate a new private/public key pair:
7233 * <ul>
7234 * <li>Device owner</li>
7235 * <li>Profile owner</li>
7236 * <li>Delegated certificate installer</li>
7237 * <li>Credential management app</li>
7238 * </ul>
7239 * If the device supports key generation via secure hardware, this method is useful for
7240 * creating a key in KeyChain that never left the secure hardware. Access to the key is
7241 * controlled the same way as in {@link #installKeyPair}.
7242 *
7243 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7244 * can call this API. If called by the credential management app, the componentName must be
7245 * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7246 *
7247 * <p>Because this method might take several seconds to complete, it should only be called from
7248 * a worker thread. This method returns {@code null} when called from the main thread.
7249 *
7250 * <p>This method is not thread-safe, calling it from multiple threads at the same time will
7251 * result in undefined behavior. If the calling thread is interrupted while the invocation is
7252 * in-flight, it will eventually terminate and return {@code null}.
7253 *
7254 * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7255 * have been given to access the key and certificates associated with this alias will be
7256 * revoked.
7257 *
7258 * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via
7259 * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the
7260 * {@code idAttestationFlags} parameter, it is possible to request the device's unique
7261 * identity to be included in the attestation record.
7262 *
7263 * <p>Specific identifiers can be included in the attestation record, and an individual
7264 * attestation certificate can be used to sign the attestation record. To find out if the device
7265 * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and
7266 * {@link #isUniqueDeviceAttestationSupported()}.
7267 *
7268 * <p>Device owner, profile owner, their delegated certificate installer and the credential
7269 * management app can use {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device
7270 * information including manufacturer, model, brand, device and product in the attestation
7271 * record.
7272 * Only device owner, profile owner on an organization-owned device or affiliated user, and
7273 * their delegated certificate installers can use {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI}
7274 * and {@link #ID_TYPE_MEID} to request unique device identifiers to be attested (the serial
7275 * number, IMEI and MEID correspondingly), if supported by the device
7276 * (see {@link #isDeviceIdAttestationSupported()}).
7277 * Additionally, device owner, profile owner on an organization-owned device and their delegated
7278 * certificate installers can also request the attestation record to be signed using an
7279 * individual attestation certificate by specifying the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION}
7280 * flag (if supported by the device, see {@link #isUniqueDeviceAttestationSupported()}).
7281 * <p>
7282 * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
7283 * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
7284 * <p>
7285 * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if
7286 * key generation is done in StrongBox.
7287 *
7288 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7289 * {@code null} if calling from a delegated certificate installer.
7290 * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
7291 * @param keySpec Specification of the key to generate, see
7292 * {@link java.security.KeyPairGenerator}.
7293 * @param idAttestationFlags A bitmask of the identifiers that should be included in the
7294 * attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
7295 * {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and
7296 * {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed
7297 * using an individual attestation certificate.
7298 * <p>
7299 * {@code 0} should be passed in if no device identification is required in the
7300 * attestation record and the batch attestation certificate should be used.
7301 * <p>
7302 * If any flag is specified, then an attestation challenge must be included in the
7303 * {@code keySpec}.
7304 * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
7305 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7306 * owner, or {@code admin} is null but the calling application is not a delegated
7307 * certificate installer or credential management app. If Device ID attestation is
7308 * requested (using {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} or
7309 * {@link #ID_TYPE_MEID}), the caller must be the Device Owner or the Certificate
7310 * Installer delegate.
7311 * @throws IllegalArgumentException in the following cases:
7312 * <p>
7313 * <ul>
7314 * <li>The alias in {@code keySpec} is empty.</li>
7315 * <li>The algorithm specification in {@code keySpec} is not
7316 * {@code RSAKeyGenParameterSpec} or {@code ECGenParameterSpec}.</li>
7317 * <li>Device ID attestation was requested but the {@code keySpec} does not contain an
7318 * attestation challenge.</li>
7319 * </ul>
7320 * @throws UnsupportedOperationException if Device ID attestation or individual attestation
7321 * was requested but the underlying hardware does not support it.
7322 * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
7323 * specified in {@code keySpec} but the device does not have one.
7324 * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
7325 */
7326 public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
7327 @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
7328 @AttestationIdType int idAttestationFlags) {
7329 throwIfParentInstance("generateKeyPair");
7330 try {
7331 final ParcelableKeyGenParameterSpec parcelableSpec =
7332 new ParcelableKeyGenParameterSpec(keySpec);
7333 KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
7334
7335 // Translate ID attestation flags to values used by AttestationUtils
7336 final boolean success = mService.generateKeyPair(
7337 admin, mContext.getPackageName(), algorithm, parcelableSpec,
7338 idAttestationFlags, attestationChain);
7339 if (!success) {
7340 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
7341 return null;
7342 }
7343
7344 final String alias = keySpec.getKeystoreAlias();
7345 final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
7346 Certificate[] outputChain = null;
7347 try {
7348 if (AttestationUtils.isChainValid(attestationChain)) {
7349 outputChain = AttestationUtils.parseCertificateChain(attestationChain);
7350 }
7351 } catch (KeyAttestationException e) {
7352 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
7353 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
7354 return null;
7355 }
7356 return new AttestedKeyPair(keyPair, outputChain);
7357 } catch (RemoteException e) {
7358 throw e.rethrowFromSystemServer();
7359 } catch (KeyChainException e) {
7360 Log.w(TAG, "Failed to generate key", e);
7361 } catch (InterruptedException e) {
7362 Log.w(TAG, "Interrupted while generating key", e);
7363 Thread.currentThread().interrupt();
7364 } catch (ServiceSpecificException e) {
7365 Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
7366 switch (e.errorCode) {
7367 case KEY_GEN_STRONGBOX_UNAVAILABLE:
7368 throw new StrongBoxUnavailableException("No StrongBox for key generation.");
7369 default:
7370 throw new RuntimeException(
7371 String.format("Unknown error while generating key: %d", e.errorCode));
7372 }
7373 }
7374 return null;
7375 }
7376
7377 /**
7378 * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7379 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to grant an application access
7380 * to an already-installed (or generated) KeyChain key.
7381 * This is useful (in combination with {@link #installKeyPair} or {@link #generateKeyPair}) to
7382 * let an application call {@link android.security.KeyChain#getPrivateKey} without having to
7383 * call {@link android.security.KeyChain#choosePrivateKeyAlias} first.
7384 *
7385 * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
7386 * broadcast when access to a key is granted.
7387 *
7388 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7389 * {@code null} if calling from a delegated certificate chooser.
7390 * @param alias The alias of the key to grant access to.
7391 * @param packageName The name of the (already installed) package to grant access to.
7392 * @return {@code true} if the grant was set successfully, {@code false} otherwise.
7393 *
7394 * @throws SecurityException if the caller is not a device owner, a profile owner or
7395 * delegated certificate chooser.
7396 * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
7397 * {@code packageName} is not a name of an installed package.
7398 * @see #revokeKeyPairFromApp
7399 */
7400 public boolean grantKeyPairToApp(@Nullable ComponentName admin, @NonNull String alias,
7401 @NonNull String packageName) {
7402 throwIfParentInstance("grantKeyPairToApp");
7403 try {
7404 return mService.setKeyGrantForApp(
7405 admin, mContext.getPackageName(), alias, packageName, true);
7406 } catch (RemoteException e) {
7407 e.rethrowFromSystemServer();
7408 }
7409 return false;
7410 }
7411
7412 /**
7413 * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7414 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query which apps have access
7415 * to a given KeyChain key.
7416 *
7417 * Key are granted on a per-UID basis, so if several apps share the same UID, granting access to
7418 * one of them automatically grants it to others. This method returns a map containing one entry
7419 * per grantee UID. Entries have UIDs as keys and sets of corresponding package names as values.
7420 * In particular, grantee packages that don't share UID with other packages are represented by
7421 * entries having singleton sets as values.
7422 *
7423 * @param alias The alias of the key to grant access to.
7424 * @return apps that have access to a given key, arranged in a map from UID to sets of
7425 * package names.
7426 *
7427 * @throws SecurityException if the caller is not a device owner, a profile owner or
7428 * delegated certificate chooser.
7429 * @throws IllegalArgumentException if {@code alias} doesn't correspond to an existing key.
7430 *
7431 * @see #grantKeyPairToApp(ComponentName, String, String)
7432 */
7433 public @NonNull Map<Integer, Set<String>> getKeyPairGrants(@NonNull String alias) {
7434 throwIfParentInstance("getKeyPairGrants");
7435 try {
7436 // The result is wrapped into intermediate parcelable representation.
7437 return mService.getKeyPairGrants(mContext.getPackageName(), alias).getPackagesByUid();
7438 } catch (RemoteException e) {
7439 e.rethrowFromSystemServer();
7440 }
7441 return null;
7442 }
7443
7444 /**
7445 * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7446 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to revoke an application's
7447 * grant to a KeyChain key pair.
7448 * Calls by the application to {@link android.security.KeyChain#getPrivateKey}
7449 * will fail after the grant is revoked.
7450 *
7451 * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
7452 * broadcast when access to a key is revoked.
7453 *
7454 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7455 * {@code null} if calling from a delegated certificate chooser.
7456 * @param alias The alias of the key to revoke access from.
7457 * @param packageName The name of the (already installed) package to revoke access from.
7458 * @return {@code true} if the grant was revoked successfully, {@code false} otherwise.
7459 *
7460 * @throws SecurityException if the caller is not a device owner, a profile owner or
7461 * delegated certificate chooser.
7462 * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
7463 * {@code packageName} is not a name of an installed package.
7464 * @see #grantKeyPairToApp
7465 */
7466 public boolean revokeKeyPairFromApp(@Nullable ComponentName admin, @NonNull String alias,
7467 @NonNull String packageName) {
7468 throwIfParentInstance("revokeKeyPairFromApp");
7469 try {
7470 return mService.setKeyGrantForApp(
7471 admin, mContext.getPackageName(), alias, packageName, false);
7472 } catch (RemoteException e) {
7473 e.rethrowFromSystemServer();
7474 }
7475 return false;
7476 }
7477
7478 /**
7479 * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7480 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to allow using a KeyChain key
7481 * pair for authentication to Wifi networks. The key can then be used in configurations passed
7482 * to {@link android.net.wifi.WifiManager#addNetwork}.
7483 *
7484 * @param alias The alias of the key pair.
7485 * @return {@code true} if the operation was set successfully, {@code false} otherwise.
7486 *
7487 * @throws SecurityException if the caller is not a device owner, a profile owner or
7488 * delegated certificate chooser.
7489 * @see #revokeKeyPairFromWifiAuth
7490 */
7491 public boolean grantKeyPairToWifiAuth(@NonNull String alias) {
7492 throwIfParentInstance("grantKeyPairToWifiAuth");
7493 try {
7494 return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, true);
7495 } catch (RemoteException e) {
7496 e.rethrowFromSystemServer();
7497 }
7498 return false;
7499 }
7500
7501 /**
7502 * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7503 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to deny using a KeyChain key
7504 * pair for authentication to Wifi networks. Configured networks using this key won't be able to
7505 * authenticate.
7506 *
7507 * @param alias The alias of the key pair.
7508 * @return {@code true} if the operation was set successfully, {@code false} otherwise.
7509 *
7510 * @throws SecurityException if the caller is not a device owner, a profile owner or
7511 * delegated certificate chooser.
7512 * @see #grantKeyPairToWifiAuth
7513 */
7514 public boolean revokeKeyPairFromWifiAuth(@NonNull String alias) {
7515 throwIfParentInstance("revokeKeyPairFromWifiAuth");
7516 try {
7517 return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, false);
7518 } catch (RemoteException e) {
7519 e.rethrowFromSystemServer();
7520 }
7521 return false;
7522 }
7523
7524 /**
7525 * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7526 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query whether a KeyChain key
7527 * pair can be used for authentication to Wifi networks.
7528 *
7529 * @param alias The alias of the key pair.
7530 * @return {@code true} if the key pair can be used, {@code false} otherwise.
7531 *
7532 * @throws SecurityException if the caller is not a device owner, a profile owner or
7533 * delegated certificate chooser.
7534 * @see #grantKeyPairToWifiAuth
7535 */
7536 public boolean isKeyPairGrantedToWifiAuth(@NonNull String alias) {
7537 throwIfParentInstance("isKeyPairGrantedToWifiAuth");
7538 try {
7539 return mService.isKeyPairGrantedToWifiAuth(mContext.getPackageName(), alias);
7540 } catch (RemoteException e) {
7541 e.rethrowFromSystemServer();
7542 }
7543 return false;
7544 }
7545
7546 /**
7547 * Returns {@code true} if the device supports attestation of device identifiers in addition
7548 * to key attestation. See
7549 * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}
7550 * @return {@code true} if Device ID attestation is supported.
7551 */
7552 public boolean isDeviceIdAttestationSupported() {
7553 PackageManager pm = mContext.getPackageManager();
7554 return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
7555 }
7556
7557 /**
7558 * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned
7559 * with an individual attestation certificate and can sign attestation records using it (as
7560 * attestation using an individual attestation certificate is a feature only Keymaster
7561 * implementations with StrongBox security level can implement).
7562 * For use prior to calling
7563 * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}.
7564 * @return {@code true} if individual attestation is supported.
7565 */
7566 public boolean isUniqueDeviceAttestationSupported() {
7567 PackageManager pm = mContext.getPackageManager();
7568 return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION);
7569 }
7570
7571 /**
7572 * This API can be called by the following to associate certificates with a key pair that was
7573 * generated using {@link #generateKeyPair}, and set whether the key is available for the user
7574 * to choose in the certificate selection prompt:
7575 * <ul>
7576 * <li>Device owner</li>
7577 * <li>Profile owner</li>
7578 * <li>Delegated certificate installer</li>
7579 * <li>Credential management app</li>
7580 * </ul>
7581 *
7582 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7583 * can call this API. If called by the credential management app, the componentName must be
7584 * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7585 *
7586 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7587 * {@code null} if calling from a delegated certificate installer.
7588 * @param alias The private key alias under which to install the certificate. The {@code alias}
7589 * should denote an existing private key. If a certificate with that alias already
7590 * exists, it will be overwritten.
7591 * @param certs The certificate chain to install. The chain should start with the leaf
7592 * certificate and include the chain of trust in order. This will be returned by
7593 * {@link android.security.KeyChain#getCertificateChain}.
7594 * @param isUserSelectable {@code true} to indicate that a user can select this key via the
7595 * certificate selection prompt, {@code false} to indicate that this key can only be
7596 * granted access by implementing
7597 * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
7598 * @return {@code true} if the provided {@code alias} exists and the certificates has been
7599 * successfully associated with it, {@code false} otherwise.
7600 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7601 * owner, or {@code admin} is null but the calling application is not a delegated
7602 * certificate installer or credential management app.
7603 */
7604 public boolean setKeyPairCertificate(@Nullable ComponentName admin,
7605 @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
7606 throwIfParentInstance("setKeyPairCertificate");
7607 try {
7608 final byte[] pemCert = Credentials.convertToPem(certs.get(0));
7609 byte[] pemChain = null;
7610 if (certs.size() > 1) {
7611 pemChain = Credentials.convertToPem(
7612 certs.subList(1, certs.size()).toArray(new Certificate[0]));
7613 }
7614 return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
7615 pemChain, isUserSelectable);
7616 } catch (RemoteException e) {
7617 throw e.rethrowFromSystemServer();
7618 } catch (CertificateException | IOException e) {
7619 Log.w(TAG, "Could not pem-encode certificate", e);
7620 }
7621 return false;
7622 }
7623
7624
7625 /**
7626 * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
7627 * doesn't exist.
7628 */
7629 private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
7630 final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
7631 final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
7632 new ByteArrayInputStream(certBuffer));
7633 return new TrustedCertificateStore().getCertificateAlias(cert);
7634 }
7635
7636 /**
7637 * Called by a profile owner or device owner to grant access to privileged certificate
7638 * manipulation APIs to a third-party certificate installer app. Granted APIs include
7639 * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
7640 * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
7641 * <p>
7642 * Delegated certificate installer is a per-user state. The delegated access is persistent until
7643 * it is later cleared by calling this method with a null value or uninstallling the certificate
7644 * installer.
7645 * <p>
7646 * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
7647 * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
7648 * supplied certificate installer package must be installed when calling this API, otherwise an
7649 * {@link IllegalArgumentException} will be thrown.
7650 *
7651 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7652 * @param installerPackage The package name of the certificate installer which will be given
7653 * access. If {@code null} is given the current package will be cleared.
7654 * @throws SecurityException if {@code admin} is not a device or a profile owner.
7655 *
7656 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
7657 * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
7658 */
7659 @Deprecated
7660 public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
7661 installerPackage) throws SecurityException {
7662 throwIfParentInstance("setCertInstallerPackage");
7663 if (mService != null) {
7664 try {
7665 mService.setCertInstallerPackage(admin, installerPackage);
7666 } catch (RemoteException e) {
7667 throw e.rethrowFromSystemServer();
7668 }
7669 }
7670 }
7671
7672 /**
7673 * Called by a profile owner or device owner to retrieve the certificate installer for the user,
7674 * or {@code null} if none is set. If there are multiple delegates this function will return one
7675 * of them.
7676 *
7677 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7678 * @return The package name of the current delegated certificate installer, or {@code null} if
7679 * none is set.
7680 * @throws SecurityException if {@code admin} is not a device or a profile owner.
7681 *
7682 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
7683 * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
7684 */
7685 @Deprecated
7686 public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
7687 throws SecurityException {
7688 throwIfParentInstance("getCertInstallerPackage");
7689 if (mService != null) {
7690 try {
7691 return mService.getCertInstallerPackage(admin);
7692 } catch (RemoteException e) {
7693 throw e.rethrowFromSystemServer();
7694 }
7695 }
7696 return null;
7697 }
7698
7699 /**
7700 * Called by a profile owner or device owner to grant access to privileged APIs to another app.
7701 * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
7702 * constants.
7703 * <p>
7704 * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
7705 * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
7706 * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
7707 * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
7708 * <p>
7709 * Delegated scopes are a per-user state. The delegated access is persistent until it is later
7710 * cleared by calling this method with an empty {@code scopes} list or uninstalling the
7711 * {@code delegatePackage}.
7712 *
7713 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7714 * @param delegatePackage The package name of the app which will be given access.
7715 * @param scopes The groups of privileged APIs whose access should be granted to
7716 * {@code delegatedPackage}.
7717 * @throws SecurityException if {@code admin} is not a device or a profile owner.
7718 */
7719 public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
7720 @NonNull List<String> scopes) {
7721 throwIfParentInstance("setDelegatedScopes");
7722 if (mService != null) {
7723 try {
7724 mService.setDelegatedScopes(admin, delegatePackage, scopes);
7725 } catch (RemoteException e) {
7726 throw e.rethrowFromSystemServer();
7727 }
7728 }
7729 }
7730
7731 /**
7732 * Called by a profile owner or device owner to retrieve a list of the scopes given to a
7733 * delegate package. Other apps can use this method to retrieve their own delegated scopes by
7734 * passing {@code null} for {@code admin} and their own package name as
7735 * {@code delegatedPackage}.
7736 *
7737 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7738 * {@code null} if the caller is {@code delegatedPackage}.
7739 * @param delegatedPackage The package name of the app whose scopes should be retrieved.
7740 * @return A list containing the scopes given to {@code delegatedPackage}.
7741 * @throws SecurityException if {@code admin} is not a device or a profile owner.
7742 */
7743 @NonNull
7744 public List<String> getDelegatedScopes(@Nullable ComponentName admin,
7745 @NonNull String delegatedPackage) {
7746 throwIfParentInstance("getDelegatedScopes");
7747 if (mService != null) {
7748 try {
7749 return mService.getDelegatedScopes(admin, delegatedPackage);
7750 } catch (RemoteException e) {
7751 throw e.rethrowFromSystemServer();
7752 }
7753 }
7754 return null;
7755 }
7756
7757 /**
7758 * Called by a profile owner or device owner to retrieve a list of delegate packages that were
7759 * granted a delegation scope.
7760 *
7761 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7762 * @param delegationScope The scope whose delegates should be retrieved.
7763 * @return A list of package names of the current delegated packages for
7764 {@code delegationScope}.
7765 * @throws SecurityException if {@code admin} is not a device or a profile owner.
7766 */
7767 @Nullable
7768 public List<String> getDelegatePackages(@NonNull ComponentName admin,
7769 @NonNull String delegationScope) {
7770 throwIfParentInstance("getDelegatePackages");
7771 if (mService != null) {
7772 try {
7773 return mService.getDelegatePackages(admin, delegationScope);
7774 } catch (RemoteException e) {
7775 throw e.rethrowFromSystemServer();
7776 }
7777 }
7778 return null;
7779 }
7780
7781 /**
7782 * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
7783 * @hide
7784 */
7785 public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
7786
7787 /**
7788 * Called by a device or profile owner to configure an always-on VPN connection through a
7789 * specific application for the current user. This connection is automatically granted and
7790 * persisted after a reboot.
7791 * <p> To support the always-on feature, an app must
7792 * <ul>
7793 * <li>declare a {@link android.net.VpnService} in its manifest, guarded by
7794 * {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
7795 * <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
7796 * <li><i>not</i> explicitly opt out of the feature through
7797 * {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
7798 * </ul>
7799 * The call will fail if called with the package name of an unsupported VPN app.
7800 * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
7801 * of the VPN provider could break networking for all apps. This method clears any lockdown
7802 * allowlist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
7803 * <p> Starting from {@link android.os.Build.VERSION_CODES#S API 31} calling this method with
7804 * {@code vpnPackage} set to {@code null} only removes the existing configuration if it was
7805 * previously created by this admin. To remove VPN configuration created by the user use
7806 * {@link UserManager#DISALLOW_CONFIG_VPN}.
7807 *
7808 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
7809 * remove an existing always-on VPN configuration.
7810 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
7811 * {@code false} otherwise. This has no effect when clearing.
7812 * @throws SecurityException if {@code admin} is not a device or a profile owner.
7813 * @throws NameNotFoundException if {@code vpnPackage} is not installed.
7814 * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
7815 * set as always-on, or if always-on VPN is not available.
7816 * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
7817 */
7818 public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
7819 boolean lockdownEnabled) throws NameNotFoundException {
7820 setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
7821 }
7822
7823 /**
7824 * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
7825 * admin to specify a set of apps that should be able to access the network directly when VPN
7826 * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
7827 * System apps can always bypass VPN.
7828 * <p> Note that the system doesn't update the allowlist when packages are installed or
7829 * uninstalled, the admin app must call this method to keep the list up to date.
7830 * <p> When {@code lockdownEnabled} is false {@code lockdownAllowlist} is ignored . When
7831 * {@code lockdownEnabled} is {@code true} and {@code lockdownAllowlist} is {@code null} or
7832 * empty, only system apps can bypass VPN.
7833 * <p> Setting always-on VPN package to {@code null} or using
7834 * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown allowlist.
7835 *
7836 * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
7837 * to remove an existing always-on VPN configuration
7838 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
7839 * {@code false} otherwise. This has no effect when clearing.
7840 * @param lockdownAllowlist Packages that will be able to access the network directly when VPN
7841 * is in lockdown mode but not connected. Has no effect when clearing.
7842 * @throws SecurityException if {@code admin} is not a device or a profile
7843 * owner.
7844 * @throws NameNotFoundException if {@code vpnPackage} or one of
7845 * {@code lockdownAllowlist} is not installed.
7846 * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
7847 * not support being set as always-on, or if always-on VPN is not
7848 * available.
7849 */
7850 public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
7851 boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)
7852 throws NameNotFoundException {
7853 throwIfParentInstance("setAlwaysOnVpnPackage");
7854 if (mService != null) {
7855 try {
7856 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
7857 lockdownAllowlist == null ? null : new ArrayList<>(lockdownAllowlist));
7858 } catch (ServiceSpecificException e) {
7859 switch (e.errorCode) {
7860 case ERROR_VPN_PACKAGE_NOT_FOUND:
7861 throw new NameNotFoundException(e.getMessage());
7862 default:
7863 throw new RuntimeException(
7864 "Unknown error setting always-on VPN: " + e.errorCode, e);
7865 }
7866 } catch (RemoteException e) {
7867 throw e.rethrowFromSystemServer();
7868 }
7869 }
7870 }
7871
7872 /**
7873 * Called by device or profile owner to query whether current always-on VPN is configured in
7874 * lockdown mode. Returns {@code false} when no always-on configuration is set.
7875 *
7876 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7877 *
7878 * @throws SecurityException if {@code admin} is not a device or a profile owner.
7879 *
7880 * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
7881 */
7882 public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
7883 throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
7884 if (mService != null) {
7885 try {
7886 // Starting from Android R, the caller can pass the permission check in
7887 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
7888 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
7889 // which is used by the NetworkStack mainline module.
7890 return mService.isAlwaysOnVpnLockdownEnabled(admin);
7891 } catch (RemoteException e) {
7892 throw e.rethrowFromSystemServer();
7893 }
7894 }
7895 return false;
7896 }
7897
7898 /**
7899 * Returns whether the admin has enabled always-on VPN lockdown for the current user.
7900 *
7901 * Only callable by the system.
7902 * @hide
7903 */
7904 @UserHandleAware
7905 public boolean isAlwaysOnVpnLockdownEnabled() {
7906 throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
7907 if (mService != null) {
7908 try {
7909 return mService.isAlwaysOnVpnLockdownEnabledForUser(myUserId());
7910 } catch (RemoteException e) {
7911 throw e.rethrowFromSystemServer();
7912 }
7913 }
7914 return false;
7915 }
7916
7917 /**
7918 * Called by device or profile owner to query the set of packages that are allowed to access
7919 * the network directly when always-on VPN is in lockdown mode but not connected. Returns
7920 * {@code null} when always-on VPN is not active or not in lockdown mode.
7921 *
7922 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7923 *
7924 * @throws SecurityException if {@code admin} is not a device or a profile owner.
7925 *
7926 * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
7927 */
7928 public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
7929 throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
7930 if (mService != null) {
7931 try {
7932 final List<String> allowlist =
7933 mService.getAlwaysOnVpnLockdownAllowlist(admin);
7934 return allowlist == null ? null : new HashSet<>(allowlist);
7935 } catch (RemoteException e) {
7936 throw e.rethrowFromSystemServer();
7937 }
7938 }
7939 return null;
7940 }
7941
7942 /**
7943 * Called by a device or profile owner to read the name of the package administering an
7944 * always-on VPN connection for the current user. If there is no such package, or the always-on
7945 * VPN is provided by the system instead of by an application, {@code null} will be returned.
7946 *
7947 * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
7948 * is set.
7949 * @throws SecurityException if {@code admin} is not a device or a profile owner.
7950 */
7951 public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
7952 throwIfParentInstance("getAlwaysOnVpnPackage");
7953 if (mService != null) {
7954 try {
7955 return mService.getAlwaysOnVpnPackage(admin);
7956 } catch (RemoteException e) {
7957 throw e.rethrowFromSystemServer();
7958 }
7959 }
7960 return null;
7961 }
7962
7963 /**
7964 * Returns the VPN package name if the admin has enabled always-on VPN on the current user,
7965 * or {@code null} if none is set.
7966 *
7967 * Only callable by the system.
7968 * @hide
7969 */
7970 @UserHandleAware
7971 public @Nullable String getAlwaysOnVpnPackage() {
7972 throwIfParentInstance("getAlwaysOnVpnPackage");
7973 if (mService != null) {
7974 try {
7975 return mService.getAlwaysOnVpnPackageForUser(myUserId());
7976 } catch (RemoteException e) {
7977 throw e.rethrowFromSystemServer();
7978 }
7979 }
7980 return null;
7981 }
7982
7983 /**
7984 * Called by an application that is administering the device to disable all cameras on the
7985 * device, for this user. After setting this, no applications running as this user will be able
7986 * to access any cameras on the device.
7987 * <p>
7988 * This method can be called on the {@link DevicePolicyManager} instance,
7989 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
7990 * the profile owner of an organization-owned managed profile.
7991 * <p>
7992 * If the caller is device owner, then the restriction will be applied to all users. If
7993 * called on the parent instance, then the restriction will be applied on the personal profile.
7994 * <p>
7995 * The calling device admin must have requested
7996 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
7997 * not, a security exception will be thrown.
7998 * <p>
7999 * <b>Note</b>, this policy type is deprecated for legacy device admins since
8000 * {@link android.os.Build.VERSION_CODES#Q}. On Android
8001 * {@link android.os.Build.VERSION_CODES#Q} devices, legacy device admins targeting SDK
8002 * version {@link android.os.Build.VERSION_CODES#P} or below can still call this API to
8003 * disable camera, while legacy device admins targeting SDK version
8004 * {@link android.os.Build.VERSION_CODES#Q} will receive a SecurityException. Starting
8005 * from Android {@link android.os.Build.VERSION_CODES#R}, requests to disable camera from
8006 * legacy device admins targeting SDK version {@link android.os.Build.VERSION_CODES#P} or
8007 * below will be silently ignored.
8008 *
8009 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8010 * @param disabled Whether or not the camera should be disabled.
8011 * @throws SecurityException if {@code admin} is not an active administrator or does not use
8012 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
8013 */
8014 public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
8015 if (mService != null) {
8016 try {
8017 mService.setCameraDisabled(admin, disabled, mParentInstance);
8018 } catch (RemoteException e) {
8019 throw e.rethrowFromSystemServer();
8020 }
8021 }
8022 }
8023
8024 /**
8025 * Determine whether or not the device's cameras have been disabled for this user,
8026 * either by the calling admin, if specified, or all admins.
8027 * <p>
8028 * This method can be called on the {@link DevicePolicyManager} instance,
8029 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8030 * the profile owner of an organization-owned managed profile.
8031 *
8032 * @param admin The name of the admin component to check, or {@code null} to check whether any admins
8033 * have disabled the camera
8034 */
8035 public boolean getCameraDisabled(@Nullable ComponentName admin) {
8036 return getCameraDisabled(admin, myUserId());
8037 }
8038
8039 /** @hide per-user version */
8040 @UnsupportedAppUsage
8041 public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
8042 if (mService != null) {
8043 try {
8044 return mService.getCameraDisabled(admin, userHandle, mParentInstance);
8045 } catch (RemoteException e) {
8046 throw e.rethrowFromSystemServer();
8047 }
8048 }
8049 return false;
8050 }
8051
8052 /**
8053 * Called by a device owner to request a bugreport.
8054 * <p>
8055 * If the device contains secondary users or profiles, they must be affiliated with the device.
8056 * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8057 *
8058 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8059 * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
8060 * wasn't triggered because a previous bugreport operation is still active (either the
8061 * bugreport is still running or waiting for the user to share or decline)
8062 * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8063 * profile or secondary user that is not affiliated with the device.
8064 * @see #isAffiliatedUser
8065 */
8066 public boolean requestBugreport(@NonNull ComponentName admin) {
8067 throwIfParentInstance("requestBugreport");
8068 if (mService != null) {
8069 try {
8070 return mService.requestBugreport(admin);
8071 } catch (RemoteException e) {
8072 throw e.rethrowFromSystemServer();
8073 }
8074 }
8075 return false;
8076 }
8077
8078 /**
8079 * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
8080 * screen capture also prevents the content from being shown on display devices that do not have
8081 * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
8082 * secure surfaces and secure displays.
8083 * <p>
8084 * This method can be called on the {@link DevicePolicyManager} instance, returned by
8085 * {@link #getParentProfileInstance(ComponentName)}, where the calling device admin must be
8086 * the profile owner of an organization-owned managed profile. If it is not, a security
8087 * exception will be thrown.
8088 * <p>
8089 * If the caller is device owner or called on the parent instance by a profile owner of an
8090 * organization-owned managed profile, then the restriction will be applied to all users.
8091 * <p>
8092 * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
8093 * assist requests for all activities of the relevant user.
8094 *
8095 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8096 * @param disabled Whether screen capture is disabled or not.
8097 * @throws SecurityException if {@code admin} is not a device or profile owner or if
8098 * called on the parent profile and the {@code admin} is not a
8099 * profile owner of an organization-owned managed profile.
8100 */
8101 public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
8102 if (mService != null) {
8103 try {
8104 mService.setScreenCaptureDisabled(admin, disabled, mParentInstance);
8105 } catch (RemoteException e) {
8106 throw e.rethrowFromSystemServer();
8107 }
8108 }
8109 }
8110
8111 /**
8112 * Determine whether or not screen capture has been disabled by the calling
8113 * admin, if specified, or all admins.
8114 * <p>
8115 * This method can be called on the {@link DevicePolicyManager} instance,
8116 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8117 * the profile owner of an organization-owned managed profile (the calling admin must be
8118 * specified).
8119 *
8120 * @param admin The name of the admin component to check, or {@code null} to check whether any
8121 * admins have disabled screen capture.
8122 */
8123 public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
8124 return getScreenCaptureDisabled(admin, myUserId());
8125 }
8126
8127 /** @hide per-user version */
8128 public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
8129 if (mService != null) {
8130 try {
8131 return mService.getScreenCaptureDisabled(admin, userHandle, mParentInstance);
8132 } catch (RemoteException e) {
8133 throw e.rethrowFromSystemServer();
8134 }
8135 }
8136 return false;
8137 }
8138
8139 /**
8140 * Called by a device/profile owner to set nearby notification streaming policy. Notification
8141 * streaming is sending notification data from pre-installed apps to nearby devices.
8142 *
8143 * @param policy One of the {@code NearbyStreamingPolicy} constants.
8144 * @throws SecurityException if caller is not a device or profile owner
8145 */
8146 public void setNearbyNotificationStreamingPolicy(@NearbyStreamingPolicy int policy) {
8147 throwIfParentInstance("setNearbyNotificationStreamingPolicy");
8148 if (mService == null) {
8149 return;
8150 }
8151 try {
8152 mService.setNearbyNotificationStreamingPolicy(policy);
8153 } catch (RemoteException e) {
8154 throw e.rethrowFromSystemServer();
8155 }
8156 }
8157
8158 /**
8159 * Returns the current runtime nearby notification streaming policy set by the device or profile
8160 * owner.
8161 * <p>
8162 * The caller must be the target user's device owner/profile owner or hold the
8163 * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY}
8164 * permission.
8165 */
8166 @RequiresPermission(
8167 value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY,
8168 conditional = true)
8169 public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy() {
8170 return getNearbyNotificationStreamingPolicy(myUserId());
8171 }
8172
8173 /** @hide per-user version */
8174 public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy(int userId) {
8175 throwIfParentInstance("getNearbyNotificationStreamingPolicy");
8176 if (mService == null) {
8177 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8178 }
8179 try {
8180 return mService.getNearbyNotificationStreamingPolicy(userId);
8181 } catch (RemoteException re) {
8182 throw re.rethrowFromSystemServer();
8183 }
8184 }
8185
8186 /**
8187 * Called by a device/profile owner to set nearby app streaming policy. App streaming is when
8188 * the device starts an app on a virtual display and sends a video stream of the app to nearby
8189 * devices.
8190 *
8191 * @param policy One of the {@code NearbyStreamingPolicy} constants.
8192 * @throws SecurityException if caller is not a device or profile owner.
8193 */
8194 public void setNearbyAppStreamingPolicy(@NearbyStreamingPolicy int policy) {
8195 throwIfParentInstance("setNearbyAppStreamingPolicy");
8196 if (mService == null) {
8197 return;
8198 }
8199 try {
8200 mService.setNearbyAppStreamingPolicy(policy);
8201 } catch (RemoteException e) {
8202 throw e.rethrowFromSystemServer();
8203 }
8204 }
8205
8206 /**
8207 * Returns the current runtime nearby app streaming policy set by the device or profile owner.
8208 * <p>
8209 * The caller must be the target user's device owner/profile owner or hold the
8210 * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY}
8211 * permission.
8212 */
8213 @RequiresPermission(
8214 value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY,
8215 conditional = true)
8216 public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy() {
8217 return getNearbyAppStreamingPolicy(myUserId());
8218 }
8219
8220 /** @hide per-user version */
8221 public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy(int userId) {
8222 throwIfParentInstance("getNearbyAppStreamingPolicy");
8223 if (mService == null) {
8224 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8225 }
8226 try {
8227 return mService.getNearbyAppStreamingPolicy(userId);
8228 } catch (RemoteException re) {
8229 throw re.rethrowFromSystemServer();
8230 }
8231 }
8232
8233 /**
8234 * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
8235 * higher, to set whether auto time is required. If auto time is required, no user will be able
8236 * set the date and time and network date and time will be used.
8237 * <p>
8238 * Note: if auto time is required the user can still manually set the time zone.
8239 * <p>
8240 * The calling device admin must be a device owner, or alternatively a profile owner from
8241 * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
8242 * <p>
8243 * Staring from Android 11, this API switches to use
8244 * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to enforce the auto time settings. Calling
8245 * this API to enforce auto time will result in
8246 * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being set, while calling this API to lift
8247 * the requirement will result in {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being cleared.
8248 * From Android 11, this API can also no longer be called on a managed profile.
8249 *
8250 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8251 * @param required Whether auto time is set required or not.
8252 * @throws SecurityException if {@code admin} is not a device owner, not a profile owner or
8253 * if this API is called on a managed profile.
8254 * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled}
8255 * to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8256 * to prevent the user from changing this setting.
8257 */
8258 @Deprecated
8259 public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
8260 throwIfParentInstance("setAutoTimeRequired");
8261 if (mService != null) {
8262 try {
8263 mService.setAutoTimeRequired(admin, required);
8264 } catch (RemoteException e) {
8265 throw e.rethrowFromSystemServer();
8266 }
8267 }
8268 }
8269
8270 /**
8271 * @return true if auto time is required.
8272 * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled}
8273 */
8274 @Deprecated
8275 public boolean getAutoTimeRequired() {
8276 throwIfParentInstance("getAutoTimeRequired");
8277 if (mService != null) {
8278 try {
8279 return mService.getAutoTimeRequired();
8280 } catch (RemoteException e) {
8281 throw e.rethrowFromSystemServer();
8282 }
8283 }
8284 return false;
8285 }
8286
8287 /**
8288 * Called by a device owner, a profile owner for the primary user or a profile
8289 * owner of an organization-owned managed profile to turn auto time on and off.
8290 * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8291 * to prevent the user from changing this setting.
8292 * <p>
8293 * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
8294 * no user will be able set the date and time. Instead, the network date
8295 * and time will be used.
8296 *
8297 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8298 * @param enabled Whether time should be obtained automatically from the network or not.
8299 * @throws SecurityException if caller is not a device owner, a profile owner for the
8300 * primary user, or a profile owner of an organization-owned managed profile.
8301 */
8302 public void setAutoTimeEnabled(@NonNull ComponentName admin, boolean enabled) {
8303 if (mService != null) {
8304 try {
8305 mService.setAutoTimeEnabled(admin, enabled);
8306 } catch (RemoteException e) {
8307 throw e.rethrowFromSystemServer();
8308 }
8309 }
8310 }
8311
8312 /**
8313 * @return true if auto time is enabled on the device.
8314 * @throws SecurityException if caller is not a device owner, a profile owner for the
8315 * primary user, or a profile owner of an organization-owned managed profile.
8316 */
8317 public boolean getAutoTimeEnabled(@NonNull ComponentName admin) {
8318 if (mService != null) {
8319 try {
8320 return mService.getAutoTimeEnabled(admin);
8321 } catch (RemoteException e) {
8322 throw e.rethrowFromSystemServer();
8323 }
8324 }
8325 return false;
8326 }
8327
8328 /**
8329 * Called by a device owner, a profile owner for the primary user or a profile
8330 * owner of an organization-owned managed profile to turn auto time zone on and off.
8331 * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8332 * to prevent the user from changing this setting.
8333 * <p>
8334 * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
8335 * no user will be able set the date and time zone. Instead, the network date
8336 * and time zone will be used.
8337 *
8338 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8339 * @param enabled Whether time zone should be obtained automatically from the network or not.
8340 * @throws SecurityException if caller is not a device owner, a profile owner for the
8341 * primary user, or a profile owner of an organization-owned managed profile.
8342 */
8343 public void setAutoTimeZoneEnabled(@NonNull ComponentName admin, boolean enabled) {
8344 throwIfParentInstance("setAutoTimeZone");
8345 if (mService != null) {
8346 try {
8347 mService.setAutoTimeZoneEnabled(admin, enabled);
8348 } catch (RemoteException e) {
8349 throw e.rethrowFromSystemServer();
8350 }
8351 }
8352 }
8353
8354 /**
8355 * @return true if auto time zone is enabled on the device.
8356 * @throws SecurityException if caller is not a device owner, a profile owner for the
8357 * primary user, or a profile owner of an organization-owned managed profile.
8358 */
8359 public boolean getAutoTimeZoneEnabled(@NonNull ComponentName admin) {
8360 throwIfParentInstance("getAutoTimeZone");
8361 if (mService != null) {
8362 try {
8363 return mService.getAutoTimeZoneEnabled(admin);
8364 } catch (RemoteException e) {
8365 throw e.rethrowFromSystemServer();
8366 }
8367 }
8368 return false;
8369 }
8370
8371 /**
8372 * TODO (b/137101239): remove this method in follow-up CL
8373 * since it's only used for split system user.
8374 * Called by a device owner to set whether all users created on the device should be ephemeral.
8375 * @hide
8376 */
8377 public void setForceEphemeralUsers(
8378 @NonNull ComponentName admin, boolean forceEphemeralUsers) {
8379 throwIfParentInstance("setForceEphemeralUsers");
8380 if (mService != null) {
8381 try {
8382 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
8383 } catch (RemoteException e) {
8384 throw e.rethrowFromSystemServer();
8385 }
8386 }
8387 }
8388
8389 /**
8390 * TODO (b/137101239): remove this method in follow-up CL
8391 * since it's only used for split system user.
8392 * @return true if all users are created ephemeral.
8393 * @throws SecurityException if {@code admin} is not a device owner.
8394 * @hide
8395 */
8396 public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
8397 throwIfParentInstance("getForceEphemeralUsers");
8398 if (mService != null) {
8399 try {
8400 return mService.getForceEphemeralUsers(admin);
8401 } catch (RemoteException e) {
8402 throw e.rethrowFromSystemServer();
8403 }
8404 }
8405 return false;
8406 }
8407
8408 /**
8409 * Called by an application that is administering the device to disable keyguard customizations,
8410 * such as widgets. After setting this, keyguard features will be disabled according to the
8411 * provided feature list.
8412 * <p>
8413 * The calling device admin must have requested
8414 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
8415 * if it has not, a security exception will be thrown.
8416 * <p>
8417 * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
8418 * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
8419 * profile owner of a managed profile can set:
8420 * <ul>
8421 * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
8422 * is no separate challenge set on the managed profile.
8423 * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
8424 * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
8425 * there is one, or the parent user otherwise.
8426 * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
8427 * by applications in the managed profile.
8428 * </ul>
8429 * <p>
8430 * From version {@link android.os.Build.VERSION_CODES#R} the profile owner of an
8431 * organization-owned managed profile can set:
8432 * <ul>
8433 * <li>{@link #KEYGUARD_DISABLE_SECURE_CAMERA} which affects the parent user when called on the
8434 * parent profile.
8435 * <li>{@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} which affects the parent user when called
8436 * on the parent profile.
8437 * </ul>
8438 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
8439 * {@link #KEYGUARD_DISABLE_FACE}, {@link #KEYGUARD_DISABLE_IRIS},
8440 * {@link #KEYGUARD_DISABLE_SECURE_CAMERA} and {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}
8441 * can also be set on the {@link DevicePolicyManager} instance returned by
8442 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
8443 * profile. {@link #KEYGUARD_DISABLE_SECURE_CAMERA} can only be set on the parent profile
8444 * instance if the calling device admin is the profile owner of an organization-owned
8445 * managed profile.
8446 * <p>
8447 * Requests to disable other features on a managed profile will be ignored.
8448 * <p>
8449 * The admin can check which features have been disabled by calling
8450 * {@link #getKeyguardDisabledFeatures(ComponentName)}
8451 *
8452 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8453 * @param which The disabled features flag which can be either
8454 * {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
8455 * {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
8456 * {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
8457 * {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
8458 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
8459 * {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
8460 * {@link #KEYGUARD_DISABLE_FINGERPRINT},
8461 * {@link #KEYGUARD_DISABLE_FACE},
8462 * {@link #KEYGUARD_DISABLE_IRIS}.
8463 * @throws SecurityException if {@code admin} is not an active administrator or does not user
8464 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
8465 */
8466 public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
8467 if (mService != null) {
8468 try {
8469 mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
8470 } catch (RemoteException e) {
8471 throw e.rethrowFromSystemServer();
8472 }
8473 }
8474 }
8475
8476 /**
8477 * Determine whether or not features have been disabled in keyguard either by the calling
8478 * admin, if specified, or all admins that set restrictions on this user and its participating
8479 * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
8480 *
8481 * <p>This method can be called on the {@link DevicePolicyManager} instance
8482 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
8483 * restrictions on the parent profile.
8484 *
8485 * @param admin The name of the admin component to check, or {@code null} to check whether any
8486 * admins have disabled features in keyguard.
8487 * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
8488 * for a list.
8489 */
8490 public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
8491 return getKeyguardDisabledFeatures(admin, myUserId());
8492 }
8493
8494 private IpcDataCache<Pair<ComponentName, Integer>, Integer> mGetKeyGuardDisabledFeaturesCache =
8495 new IpcDataCache<>(sDpmCaches.child("getKeyguardDisabledFeatures"),
8496 (query) -> getService().getKeyguardDisabledFeatures(
8497 query.first, query.second, isParentInstance()));
8498
8499 /** @hide per-user version */
8500 @UnsupportedAppUsage
8501 public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
8502 if (mService != null) {
8503 return mGetKeyGuardDisabledFeaturesCache.query(new Pair<>(admin, userHandle));
8504 } else {
8505 return KEYGUARD_DISABLE_FEATURES_NONE;
8506 }
8507 }
8508
8509 /**
8510 * @hide
8511 */
8512 @TestApi
8513 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8514 @RequiresPermission(allOf = {
8515 android.Manifest.permission.MANAGE_DEVICE_ADMINS,
8516 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL
8517 })
8518 public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
8519 int userHandle) {
8520 if (mService != null) {
8521 try {
8522 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
8523 } catch (RemoteException e) {
8524 throw e.rethrowFromSystemServer();
8525 }
8526 }
8527 }
8528
8529 /**
8530 * @hide
8531 */
8532 @UnsupportedAppUsage
8533 public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
8534 setActiveAdmin(policyReceiver, refreshing, myUserId());
8535 }
8536
8537 /**
8538 * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
8539 * the remove warning for the given device admin.
8540 * @hide
8541 */
8542 public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
8543 if (mService != null) {
8544 try {
8545 mService.getRemoveWarning(admin, result, myUserId());
8546 } catch (RemoteException e) {
8547 throw e.rethrowFromSystemServer();
8548 }
8549 }
8550 }
8551
8552 /**
8553 * @hide
8554 */
8555 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
8556 public void reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId) {
8557 if (mService != null) {
8558 try {
8559 mService.reportPasswordChanged(metrics, userId);
8560 } catch (RemoteException e) {
8561 throw e.rethrowFromSystemServer();
8562 }
8563 }
8564 }
8565
8566 /**
8567 * @hide
8568 */
8569 @UnsupportedAppUsage
8570 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
8571 public void reportFailedPasswordAttempt(int userHandle) {
8572 if (mService != null) {
8573 try {
8574 mService.reportFailedPasswordAttempt(userHandle);
8575 } catch (RemoteException e) {
8576 throw e.rethrowFromSystemServer();
8577 }
8578 }
8579 }
8580
8581 /**
8582 * @hide
8583 */
8584 @UnsupportedAppUsage
8585 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
8586 public void reportSuccessfulPasswordAttempt(int userHandle) {
8587 if (mService != null) {
8588 try {
8589 mService.reportSuccessfulPasswordAttempt(userHandle);
8590 } catch (RemoteException e) {
8591 throw e.rethrowFromSystemServer();
8592 }
8593 }
8594 }
8595
8596 /**
8597 * @hide
8598 */
8599 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
8600 public void reportFailedBiometricAttempt(int userHandle) {
8601 if (mService != null) {
8602 try {
8603 mService.reportFailedBiometricAttempt(userHandle);
8604 } catch (RemoteException e) {
8605 throw e.rethrowFromSystemServer();
8606 }
8607 }
8608 }
8609
8610 /**
8611 * @hide
8612 */
8613 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
8614 public void reportSuccessfulBiometricAttempt(int userHandle) {
8615 if (mService != null) {
8616 try {
8617 mService.reportSuccessfulBiometricAttempt(userHandle);
8618 } catch (RemoteException e) {
8619 throw e.rethrowFromSystemServer();
8620 }
8621 }
8622 }
8623
8624 /**
8625 * Should be called when keyguard has been dismissed.
8626 * @hide
8627 */
8628 public void reportKeyguardDismissed(int userHandle) {
8629 if (mService != null) {
8630 try {
8631 mService.reportKeyguardDismissed(userHandle);
8632 } catch (RemoteException e) {
8633 throw e.rethrowFromSystemServer();
8634 }
8635 }
8636 }
8637
8638 /**
8639 * Should be called when keyguard view has been shown to the user.
8640 * @hide
8641 */
8642 public void reportKeyguardSecured(int userHandle) {
8643 if (mService != null) {
8644 try {
8645 mService.reportKeyguardSecured(userHandle);
8646 } catch (RemoteException e) {
8647 throw e.rethrowFromSystemServer();
8648 }
8649 }
8650 }
8651
8652 /**
8653 * Sets the given package as the device owner.
8654 *
8655 * <p>Preconditions:
8656 * <ul>
8657 * <li>The package must already be installed.
8658 * <li>There must not already be a device owner.
8659 * <li>Only apps with the {@code MANAGE_PROFILE_AND_DEVICE_OWNERS} permission or the
8660 * {@link Process#SHELL_UID Shell UID} can call this method.
8661 * </ul>
8662 *
8663 * <p>Calling this after the setup phase of the device owner user has completed is allowed only
8664 * if the caller is the {@link Process#SHELL_UID Shell UID}, and there are no additional users
8665 * (except when the device runs on headless system user mode, in which case it could have exact
8666 * one extra user, which is the current user - the device owner will be set in the
8667 * {@link UserHandle#SYSTEM system} user and a profile owner will be set in the current user)
8668 * and no accounts.
8669 *
8670 * @param who the component name to be registered as device owner.
8671 * @param ownerName the human readable name of the institution that owns this device.
8672 * @param userId ID of the user on which the device owner runs.
8673 *
8674 * @return whether the package was successfully registered as the device owner.
8675 *
8676 * @throws IllegalArgumentException if the package name is {@code null} or invalid.
8677 * @throws IllegalStateException If the preconditions mentioned are not met.
8678 *
8679 * @hide
8680 */
8681 @TestApi
8682 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
8683 public boolean setDeviceOwner(@NonNull ComponentName who, @Nullable String ownerName,
8684 @UserIdInt int userId) {
8685 if (mService != null) {
8686 try {
8687 return mService.setDeviceOwner(who, ownerName, userId,
8688 /* setProfileOwnerOnCurrentUserIfNecessary= */ true);
8689 } catch (RemoteException re) {
8690 throw re.rethrowFromSystemServer();
8691 }
8692 }
8693 return false;
8694 }
8695
8696 /**
8697 * Same as {@link #setDeviceOwner(ComponentName, String, int)}, but without setting the profile
8698 * owner on current user when running on headless system user mode - should be used only by
8699 * testing infra.
8700 *
8701 * @hide
8702 */
8703 @TestApi
8704 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
8705 public boolean setDeviceOwnerOnly(
8706 @NonNull ComponentName who, @Nullable String ownerName, @UserIdInt int userId) {
8707 if (mService != null) {
8708 try {
8709 return mService.setDeviceOwner(who, ownerName, userId,
8710 /* setProfileOwnerOnCurrentUserIfNecessary= */ false);
8711 } catch (RemoteException re) {
8712 throw re.rethrowFromSystemServer();
8713 }
8714 }
8715 return false;
8716 }
8717
8718 /**
8719 * Used to determine if a particular package has been registered as a Device Owner app.
8720 * A device owner app is a special device admin that cannot be deactivated by the user, once
8721 * activated as a device admin. It also cannot be uninstalled. To check whether a particular
8722 * package is currently registered as the device owner app, pass in the package name from
8723 * {@link Context#getPackageName()} to this method.<p/>This is useful for device
8724 * admin apps that want to check whether they are also registered as the device owner app. The
8725 * exact mechanism by which a device admin app is registered as a device owner app is defined by
8726 * the setup process.
8727 * @param packageName the package name of the app, to compare with the registered device owner
8728 * app, if any.
8729 * @return whether or not the package is registered as the device owner app.
8730 */
8731 public boolean isDeviceOwnerApp(String packageName) {
8732 throwIfParentInstance("isDeviceOwnerApp");
8733 return isDeviceOwnerAppOnCallingUser(packageName);
8734 }
8735
8736 /**
8737 * @return true if a package is registered as device owner, only when it's running on the
8738 * calling user.
8739 *
8740 * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
8741 * @hide
8742 */
8743 public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
8744 return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
8745 }
8746
8747 /**
8748 * @return true if a package is registered as device owner, even if it's running on a different
8749 * user.
8750 *
8751 * <p>Requires the MANAGE_USERS permission.
8752 *
8753 * @hide
8754 */
8755 public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
8756 return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
8757 }
8758
8759 /**
8760 * @return device owner component name, only when it's running on the calling user.
8761 *
8762 * @hide
8763 */
8764 public ComponentName getDeviceOwnerComponentOnCallingUser() {
8765 return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
8766 }
8767
8768 /**
8769 * @return device owner component name, even if it's running on a different user.
8770 *
8771 * @hide
8772 */
8773 @SystemApi
8774 @RequiresPermission(anyOf = {
8775 android.Manifest.permission.MANAGE_USERS,
8776 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
8777 })
8778 public ComponentName getDeviceOwnerComponentOnAnyUser() {
8779 return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
8780 }
8781
8782 private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
8783 if (packageName == null) {
8784 return false;
8785 }
8786 final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
8787 if (deviceOwner == null) {
8788 return false;
8789 }
8790 return packageName.equals(deviceOwner.getPackageName());
8791 }
8792
8793 private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
8794 if (mService != null) {
8795 try {
8796 return mService.getDeviceOwnerComponent(callingUserOnly);
8797 } catch (RemoteException re) {
8798 throw re.rethrowFromSystemServer();
8799 }
8800 }
8801 return null;
8802 }
8803
8804 /**
8805 * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
8806 *
8807 * @hide
8808 */
8809 @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8810 @SystemApi
8811 public @Nullable UserHandle getDeviceOwnerUser() {
8812 if (mService != null) {
8813 try {
8814 int userId = mService.getDeviceOwnerUserId();
8815
8816 if (userId != UserHandle.USER_NULL) {
8817 return UserHandle.of(userId);
8818 }
8819 } catch (RemoteException re) {
8820 throw re.rethrowFromSystemServer();
8821 }
8822 }
8823 return null;
8824 }
8825
8826 /**
8827 * @hide
8828 */
8829 public int getDeviceOwnerUserId() {
8830 if (mService != null) {
8831 try {
8832 return mService.getDeviceOwnerUserId();
8833 } catch (RemoteException re) {
8834 throw re.rethrowFromSystemServer();
8835 }
8836 }
8837 return UserHandle.USER_NULL;
8838 }
8839
8840 /**
8841 * Clears the current device owner. The caller must be the device owner. This function should be
8842 * used cautiously as once it is called it cannot be undone. The device owner can only be set as
8843 * a part of device setup, before it completes.
8844 * <p>
8845 * While some policies previously set by the device owner will be cleared by this method, it is
8846 * a best-effort process and some other policies will still remain in place after the device
8847 * owner is cleared.
8848 *
8849 * @param packageName The package name of the device owner.
8850 * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
8851 * does not own the current device owner component.
8852 *
8853 * @deprecated This method is expected to be used for testing purposes only. The device owner
8854 * will lose control of the device and its data after calling it. In order to protect any
8855 * sensitive data that remains on the device, it is advised that the device owner factory resets
8856 * the device instead of calling this method. See {@link #wipeData(int)}.
8857 */
8858 @Deprecated
8859 public void clearDeviceOwnerApp(String packageName) {
8860 throwIfParentInstance("clearDeviceOwnerApp");
8861 if (mService != null) {
8862 try {
8863 mService.clearDeviceOwner(packageName);
8864 } catch (RemoteException re) {
8865 throw re.rethrowFromSystemServer();
8866 }
8867 }
8868 }
8869
8870 /**
8871 * Returns the device owner package name, only if it's running on the calling user.
8872 *
8873 * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
8874 *
8875 * @hide
8876 */
8877 @SystemApi
8878 @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8879 public @Nullable String getDeviceOwner() {
8880 throwIfParentInstance("getDeviceOwner");
8881 final ComponentName name = getDeviceOwnerComponentOnCallingUser();
8882 return name != null ? name.getPackageName() : null;
8883 }
8884
8885 private IpcDataCache<Void, Boolean> mHasDeviceOwnerCache =
8886 new IpcDataCache<>(sDpmCaches.child("hasDeviceOwner"),
8887 (query) -> getService().hasDeviceOwner());
8888
8889 /**
8890 * Called by the system to find out whether the device is managed by a Device Owner.
8891 *
8892 * @return whether the device is managed by a Device Owner.
8893 * @throws SecurityException if the caller is not the device owner, does not hold
8894 * MANAGE_USERS or MANAGE_PROFILE_AND_DEVICE_OWNERS permissions and is not the system.
8895 *
8896 * @hide
8897 */
8898 @SystemApi
8899 @SuppressLint("RequiresPermission")
8900 public boolean isDeviceManaged() {
8901 return mHasDeviceOwnerCache.query(null);
8902 }
8903
8904 /**
8905 * Returns the device owner name. Note this method *will* return the device owner
8906 * name when it's running on a different user.
8907 *
8908 * @hide
8909 */
8910 @SystemApi
8911 @RequiresPermission(anyOf = {
8912 android.Manifest.permission.MANAGE_USERS,
8913 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
8914 })
8915 public String getDeviceOwnerNameOnAnyUser() {
8916 throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
8917 if (mService != null) {
8918 try {
8919 return mService.getDeviceOwnerName();
8920 } catch (RemoteException re) {
8921 throw re.rethrowFromSystemServer();
8922 }
8923 }
8924 return null;
8925 }
8926
8927 /**
8928 * @hide
8929 * @deprecated Use #ACTION_SET_PROFILE_OWNER
8930 * Sets the given component as an active admin and registers the package as the profile
8931 * owner for this user. The package must already be installed and there shouldn't be
8932 * an existing profile owner registered for this user. Also, this method must be called
8933 * before the user setup has been completed.
8934 * <p>
8935 * This method can only be called by system apps that hold MANAGE_USERS permission and
8936 * MANAGE_DEVICE_ADMINS permission.
8937 * @param admin The component to register as an active admin and profile owner.
8938 * @param ownerName The user-visible name of the entity that is managing this user.
8939 * @return whether the admin was successfully registered as the profile owner.
8940 * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
8941 * the user has already been set up.
8942 */
8943 @Deprecated
8944 @SystemApi
8945 @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
8946 public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
8947 throws IllegalArgumentException {
8948 throwIfParentInstance("setActiveProfileOwner");
8949 if (mService != null) {
8950 try {
8951 final int myUserId = myUserId();
8952 mService.setActiveAdmin(admin, false, myUserId);
8953 return mService.setProfileOwner(admin, ownerName, myUserId);
8954 } catch (RemoteException re) {
8955 throw re.rethrowFromSystemServer();
8956 }
8957 }
8958 return false;
8959 }
8960
8961 /**
8962 * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
8963 * a SecurityException will be thrown. This method is not available to managed profile owners.
8964 * <p>
8965 * While some policies previously set by the profile owner will be cleared by this method, it is
8966 * a best-effort process and some other policies will still remain in place after the profile
8967 * owner is cleared.
8968 *
8969 * @param admin The component to remove as the profile owner.
8970 * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
8971 * being called from a managed profile.
8972 *
8973 * @deprecated This method is expected to be used for testing purposes only. The profile owner
8974 * will lose control of the user and its data after calling it. In order to protect any
8975 * sensitive data that remains on this user, it is advised that the profile owner deletes it
8976 * instead of calling this method. See {@link #wipeData(int)}.
8977 */
8978 @Deprecated
8979 public void clearProfileOwner(@NonNull ComponentName admin) {
8980 throwIfParentInstance("clearProfileOwner");
8981 if (mService != null) {
8982 try {
8983 mService.clearProfileOwner(admin);
8984 } catch (RemoteException re) {
8985 throw re.rethrowFromSystemServer();
8986 }
8987 }
8988 }
8989
8990 /**
8991 * @hide
8992 * Checks whether the user was already setup.
8993 */
8994 public boolean hasUserSetupCompleted() {
8995 if (mService != null) {
8996 try {
8997 return mService.hasUserSetupCompleted();
8998 } catch (RemoteException re) {
8999 throw re.rethrowFromSystemServer();
9000 }
9001 }
9002 return true;
9003 }
9004
9005 /**
9006 * @hide
9007 * Sets the given component as the profile owner of the given user profile. The package must
9008 * already be installed. There must not already be a profile owner for this user.
9009 * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
9010 * this method.
9011 * Calling this after the setup phase of the specified user has completed is allowed only if:
9012 * - the caller is SYSTEM_UID.
9013 * - or the caller is the shell uid, and there are no accounts on the specified user.
9014 * @param admin the component name to be registered as profile owner.
9015 * @param ownerName the human readable name of the organisation associated with this DPM.
9016 * @param userHandle the userId to set the profile owner for.
9017 * @return whether the component was successfully registered as the profile owner.
9018 * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
9019 * preconditions mentioned are not met.
9020 */
9021 public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
9022 int userHandle) throws IllegalArgumentException {
9023 if (mService != null) {
9024 try {
9025 if (ownerName == null) {
9026 ownerName = "";
9027 }
9028 return mService.setProfileOwner(admin, ownerName, userHandle);
9029 } catch (RemoteException re) {
9030 throw re.rethrowFromSystemServer();
9031 }
9032 }
9033 return false;
9034 }
9035
9036 /**
9037 * Sets the device owner information to be shown on the lock screen.
9038 * <p>
9039 * Device owner information set using this method overrides any owner information manually set
9040 * by the user and prevents the user from further changing it.
9041 * <p>
9042 * If the device owner information is {@code null} or empty then the device owner info is
9043 * cleared and the user owner info is shown on the lock screen if it is set.
9044 * <p>
9045 * If the device owner information contains only whitespaces then the message on the lock screen
9046 * will be blank and the user will not be allowed to change it.
9047 * <p>
9048 * If the device owner information needs to be localized, it is the responsibility of the
9049 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9050 * and set a new version of this string accordingly.
9051 * <p>
9052 * May be called by the device owner or the profile owner of an organization-owned device.
9053 *
9054 * @param admin The name of the admin component to check.
9055 * @param info Device owner information which will be displayed instead of the user owner info.
9056 * @throws SecurityException if {@code admin} is not a device owner.
9057 */
9058 public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
9059 throwIfParentInstance("setDeviceOwnerLockScreenInfo");
9060 if (mService != null) {
9061 try {
9062 mService.setDeviceOwnerLockScreenInfo(admin, info);
9063 } catch (RemoteException re) {
9064 throw re.rethrowFromSystemServer();
9065 }
9066 }
9067 }
9068
9069 /**
9070 * @return The device owner information. If it is not set returns {@code null}.
9071 */
9072 public CharSequence getDeviceOwnerLockScreenInfo() {
9073 throwIfParentInstance("getDeviceOwnerLockScreenInfo");
9074 if (mService != null) {
9075 try {
9076 return mService.getDeviceOwnerLockScreenInfo();
9077 } catch (RemoteException re) {
9078 throw re.rethrowFromSystemServer();
9079 }
9080 }
9081 return null;
9082 }
9083
9084 /**
9085 * Called by device or profile owners to suspend packages for this user. This function can be
9086 * called by a device owner, profile owner, or by a delegate given the
9087 * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
9088 * <p>
9089 * A suspended package will not be able to start activities. Its notifications will be hidden,
9090 * it will not show up in recents, will not be able to show toasts or dialogs or ring the
9091 * device.
9092 * <p>
9093 * The package must already be installed. If the package is uninstalled while suspended the
9094 * package will no longer be suspended. The admin can block this by using
9095 * {@link #setUninstallBlocked}.
9096 *
9097 * <p>Some apps cannot be suspended, such as device admins, the active launcher, the required
9098 * package installer, the required package uninstaller, the required package verifier, the
9099 * default dialer, and the permission controller.
9100 *
9101 * @param admin The name of the admin component to check, or {@code null} if the caller is a
9102 * package access delegate.
9103 * @param packageNames The package names to suspend or unsuspend.
9104 * @param suspended If set to {@code true} than the packages will be suspended, if set to
9105 * {@code false} the packages will be unsuspended.
9106 * @return an array of package names for which the suspended status is not set as requested in
9107 * this method.
9108 * @throws SecurityException if {@code admin} is not a device or profile owner.
9109 * @see #setDelegatedScopes
9110 * @see #DELEGATION_PACKAGE_ACCESS
9111 */
9112 public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
9113 @NonNull String[] packageNames, boolean suspended) {
9114 throwIfParentInstance("setPackagesSuspended");
9115 if (mService != null) {
9116 try {
9117 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
9118 suspended);
9119 } catch (RemoteException re) {
9120 throw re.rethrowFromSystemServer();
9121 }
9122 }
9123 return packageNames;
9124 }
9125
9126 /**
9127 * Determine if a package is suspended. This function can be called by a device owner, profile
9128 * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
9129 * {@link #setDelegatedScopes}.
9130 *
9131 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9132 * {@code null} if the caller is a package access delegate.
9133 * @param packageName The name of the package to retrieve the suspended status of.
9134 * @return {@code true} if the package is suspended or {@code false} if the package is not
9135 * suspended, could not be found or an error occurred.
9136 * @throws SecurityException if {@code admin} is not a device or profile owner.
9137 * @throws NameNotFoundException if the package could not be found.
9138 * @see #setDelegatedScopes
9139 * @see #DELEGATION_PACKAGE_ACCESS
9140 */
9141 public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
9142 throws NameNotFoundException {
9143 throwIfParentInstance("isPackageSuspended");
9144 if (mService != null) {
9145 try {
9146 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
9147 } catch (RemoteException e) {
9148 throw e.rethrowFromSystemServer();
9149 } catch (IllegalArgumentException ex) {
9150 throw new NameNotFoundException(packageName);
9151 }
9152 }
9153 return false;
9154 }
9155
9156 /**
9157 * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
9158 * be used. Only the profile owner can call this.
9159 *
9160 * @see #isProfileOwnerApp
9161 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9162 * @throws SecurityException if {@code admin} is not a profile owner.
9163 */
9164 public void setProfileEnabled(@NonNull ComponentName admin) {
9165 throwIfParentInstance("setProfileEnabled");
9166 if (mService != null) {
9167 try {
9168 mService.setProfileEnabled(admin);
9169 } catch (RemoteException e) {
9170 throw e.rethrowFromSystemServer();
9171 }
9172 }
9173 }
9174
9175 /**
9176 * Sets the name of the profile. In the device owner case it sets the name of the user which it
9177 * is called from. Only a profile owner or device owner can call this. If this is never called
9178 * by the profile or device owner, the name will be set to default values.
9179 *
9180 * @see #isProfileOwnerApp
9181 * @see #isDeviceOwnerApp
9182 * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
9183 * @param profileName The name of the profile.
9184 * @throws SecurityException if {@code admin} is not a device or profile owner.
9185 */
9186 public void setProfileName(@NonNull ComponentName admin, String profileName) {
9187 throwIfParentInstance("setProfileName");
9188 if (mService != null) {
9189 try {
9190 mService.setProfileName(admin, profileName);
9191 } catch (RemoteException e) {
9192 throw e.rethrowFromSystemServer();
9193 }
9194 }
9195 }
9196
9197 /**
9198 * Used to determine if a particular package is registered as the profile owner for the
9199 * user. A profile owner is a special device admin that has additional privileges
9200 * within the profile.
9201 *
9202 * @param packageName The package name of the app to compare with the registered profile owner.
9203 * @return Whether or not the package is registered as the profile owner.
9204 */
9205 public boolean isProfileOwnerApp(String packageName) {
9206 throwIfParentInstance("isProfileOwnerApp");
9207 if (mService != null) {
9208 try {
9209 ComponentName profileOwner = mService.getProfileOwnerAsUser(myUserId());
9210 return profileOwner != null
9211 && profileOwner.getPackageName().equals(packageName);
9212 } catch (RemoteException re) {
9213 throw re.rethrowFromSystemServer();
9214 }
9215 }
9216 return false;
9217 }
9218
9219 /**
9220 * @hide
9221 * @return the packageName of the owner of the given user profile or {@code null} if no profile
9222 * owner has been set for that user.
9223 * @throws IllegalArgumentException if the userId is invalid.
9224 */
9225 @SystemApi
9226 public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
9227 throwIfParentInstance("getProfileOwner");
9228 return getProfileOwnerAsUser(mContext.getUserId());
9229 }
9230
9231 /**
9232 * @see #getProfileOwner()
9233 * @hide
9234 */
9235 @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
9236 conditional = true)
9237 public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
9238 if (mService != null) {
9239 try {
9240 return mService.getProfileOwnerAsUser(user.getIdentifier());
9241 } catch (RemoteException re) {
9242 throw re.rethrowFromSystemServer();
9243 }
9244 }
9245 return null;
9246 }
9247
9248 /**
9249 * @hide
9250 */
9251 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
9252 public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
9253 if (mService != null) {
9254 try {
9255 return mService.getProfileOwnerAsUser(userId);
9256 } catch (RemoteException re) {
9257 throw re.rethrowFromSystemServer();
9258 }
9259 }
9260 return null;
9261 }
9262
9263 private final IpcDataCache<UserHandle, ComponentName>
9264 mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache =
9265 new IpcDataCache<>(sDpmCaches.child("getProfileOwnerOrDeviceOwnerSupervisionComponent"),
9266 (arg) -> getService().getProfileOwnerOrDeviceOwnerSupervisionComponent(arg));
9267
9268 /**
9269 * Returns the configured supervision app if it exists and is the device owner or policy owner.
9270 * @hide
9271 */
9272 public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
9273 @NonNull UserHandle user) {
9274 if (mService != null) {
9275 return mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache.query(user);
9276 }
9277 return null;
9278 }
9279
9280 /**
9281 * Checks if the specified component is the supervision component.
9282 * @hide
9283 */
9284 public boolean isSupervisionComponent(@NonNull ComponentName who) {
9285 if (mService != null) {
9286 try {
9287 return getService().isSupervisionComponent(who);
9288 } catch (RemoteException re) {
9289 throw re.rethrowFromSystemServer();
9290 }
9291 }
9292 return false;
9293 }
9294
9295 /**
9296 * @hide
9297 * @return the human readable name of the organisation associated with this DPM or {@code null}
9298 * if one is not set.
9299 * @throws IllegalArgumentException if the userId is invalid.
9300 */
9301 public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
9302 if (mService != null) {
9303 try {
9304 return mService.getProfileOwnerName(mContext.getUserId());
9305 } catch (RemoteException re) {
9306 throw re.rethrowFromSystemServer();
9307 }
9308 }
9309 return null;
9310 }
9311
9312 /**
9313 * @hide
9314 * @param userId The user for whom to fetch the profile owner name, if any.
9315 * @return the human readable name of the organisation associated with this profile owner or
9316 * null if one is not set.
9317 * @throws IllegalArgumentException if the userId is invalid.
9318 */
9319 @SystemApi
9320 @RequiresPermission(anyOf = {
9321 android.Manifest.permission.MANAGE_USERS,
9322 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
9323 })
9324 public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
9325 throwIfParentInstance("getProfileOwnerNameAsUser");
9326 if (mService != null) {
9327 try {
9328 return mService.getProfileOwnerName(userId);
9329 } catch (RemoteException re) {
9330 throw re.rethrowFromSystemServer();
9331 }
9332 }
9333 return null;
9334 }
9335
9336 private final IpcDataCache<Void, Boolean> mIsOrganizationOwnedDeviceWithManagedProfileCache =
9337 new IpcDataCache(sDpmCaches.child("isOrganizationOwnedDeviceWithManagedProfile"),
9338 (query) -> getService().isOrganizationOwnedDeviceWithManagedProfile());
9339
9340 /**
9341 * Apps can use this method to find out if the device was provisioned as
9342 * organization-owend device with a managed profile.
9343 *
9344 * This, together with checking whether the device has a device owner (by calling
9345 * {@link #isDeviceOwnerApp}), could be used to learn whether the device is owned by an
9346 * organization or an individual:
9347 * If this method returns true OR {@link #isDeviceOwnerApp} returns true (for any package),
9348 * then the device is owned by an organization. Otherwise, it's owned by an individual.
9349 *
9350 * @return {@code true} if the device was provisioned as organization-owned device,
9351 * {@code false} otherwise.
9352 */
9353 public boolean isOrganizationOwnedDeviceWithManagedProfile() {
9354 throwIfParentInstance("isOrganizationOwnedDeviceWithManagedProfile");
9355 if (mService != null) {
9356 return mIsOrganizationOwnedDeviceWithManagedProfileCache.query(null);
9357 }
9358 return false;
9359 }
9360
9361 /**
9362 * Returns whether the specified package can read the device identifiers.
9363 *
9364 * @param packageName The package name of the app to check for device identifier access.
9365 * @param pid The process id of the package to be checked.
9366 * @param uid The uid of the package to be checked.
9367 * @return whether the package can read the device identifiers.
9368 *
9369 * @hide
9370 */
9371 public boolean hasDeviceIdentifierAccess(@NonNull String packageName, int pid, int uid) {
9372 throwIfParentInstance("hasDeviceIdentifierAccess");
9373 if (packageName == null) {
9374 return false;
9375 }
9376 if (mService != null) {
9377 try {
9378 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
9379 } catch (RemoteException re) {
9380 throw re.rethrowFromSystemServer();
9381 }
9382 }
9383 return false;
9384 }
9385
9386 /**
9387 * Called by a profile owner or device owner to set a default activity that the system selects
9388 * to handle intents that match the given {@link IntentFilter}. This activity will remain the
9389 * default intent handler even if the set of potential event handlers for the intent filter
9390 * changes and if the intent preferences are reset.
9391 * <p>
9392 * Note that the caller should still declare the activity in the manifest, the API just sets
9393 * the activity to be the default one to handle the given intent filter.
9394 * <p>
9395 * The default disambiguation mechanism takes over if the activity is not installed (anymore).
9396 * When the activity is (re)installed, it is automatically reset as default intent handler for
9397 * the filter.
9398 * <p>
9399 * The calling device admin must be a profile owner or device owner. If it is not, a security
9400 * exception will be thrown.
9401 *
9402 * <p>NOTE: Performs disk I/O and shouldn't be called on the main thread.
9403 *
9404 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9405 * @param filter The IntentFilter for which a default handler is added.
9406 * @param activity The Activity that is added as default intent handler.
9407 * @throws SecurityException if {@code admin} is not a device or profile owner.
9408 */
9409 public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
9410 @NonNull ComponentName activity) {
9411 throwIfParentInstance("addPersistentPreferredActivity");
9412 if (mService != null) {
9413 try {
9414 mService.addPersistentPreferredActivity(admin, filter, activity);
9415 } catch (RemoteException e) {
9416 throw e.rethrowFromSystemServer();
9417 }
9418 }
9419 }
9420
9421 /**
9422 * Called by a profile owner or device owner to remove all persistent intent handler preferences
9423 * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
9424 * <p>
9425 * The calling device admin must be a profile owner. If it is not, a security exception will be
9426 * thrown.
9427 *
9428 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9429 * @param packageName The name of the package for which preferences are removed.
9430 * @throws SecurityException if {@code admin} is not a device or profile owner.
9431 */
9432 public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
9433 String packageName) {
9434 throwIfParentInstance("clearPackagePersistentPreferredActivities");
9435 if (mService != null) {
9436 try {
9437 mService.clearPackagePersistentPreferredActivities(admin, packageName);
9438 } catch (RemoteException e) {
9439 throw e.rethrowFromSystemServer();
9440 }
9441 }
9442 }
9443
9444 /**
9445 * Must be called by a device owner or a profile owner of an organization-owned managed profile
9446 * to set the default SMS application.
9447 * <p>
9448 * This method can be called on the {@link DevicePolicyManager} instance, returned by
9449 * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
9450 * of an organization-owned managed profile and the package must be a pre-installed system
9451 * package. If called on the parent instance, then the default SMS application is set on the
9452 * personal profile.
9453 *
9454 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9455 * @param packageName The name of the package to set as the default SMS application.
9456 * @throws SecurityException if {@code admin} is not a device or profile owner or if
9457 * called on the parent profile and the {@code admin} is not a
9458 * profile owner of an organization-owned managed profile.
9459 * @throws IllegalArgumentException if called on the parent profile and the package
9460 * provided is not a pre-installed system package.
9461 */
9462 public void setDefaultSmsApplication(@NonNull ComponentName admin,
9463 @NonNull String packageName) {
9464 if (mService != null) {
9465 try {
9466 mService.setDefaultSmsApplication(admin, packageName, mParentInstance);
9467 } catch (RemoteException e) {
9468 throw e.rethrowFromSystemServer();
9469 }
9470 }
9471 }
9472
9473 /**
9474 * Called by a profile owner or device owner to grant permission to a package to manage
9475 * application restrictions for the calling user via {@link #setApplicationRestrictions} and
9476 * {@link #getApplicationRestrictions}.
9477 * <p>
9478 * This permission is persistent until it is later cleared by calling this method with a
9479 * {@code null} value or uninstalling the managing package.
9480 * <p>
9481 * The supplied application restriction managing package must be installed when calling this
9482 * API, otherwise an {@link NameNotFoundException} will be thrown.
9483 *
9484 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9485 * @param packageName The package name which will be given access to application restrictions
9486 * APIs. If {@code null} is given the current package will be cleared.
9487 * @throws SecurityException if {@code admin} is not a device or profile owner.
9488 * @throws NameNotFoundException if {@code packageName} is not found
9489 *
9490 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
9491 * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
9492 */
9493 @Deprecated
9494 public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
9495 @Nullable String packageName) throws NameNotFoundException {
9496 throwIfParentInstance("setApplicationRestrictionsManagingPackage");
9497 if (mService != null) {
9498 try {
9499 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
9500 throw new NameNotFoundException(packageName);
9501 }
9502 } catch (RemoteException e) {
9503 throw e.rethrowFromSystemServer();
9504 }
9505 }
9506 }
9507
9508 /**
9509 * Called by a profile owner or device owner to retrieve the application restrictions managing
9510 * package for the current user, or {@code null} if none is set. If there are multiple
9511 * delegates this function will return one of them.
9512 *
9513 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9514 * @return The package name allowed to manage application restrictions on the current user, or
9515 * {@code null} if none is set.
9516 * @throws SecurityException if {@code admin} is not a device or profile owner.
9517 *
9518 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
9519 * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
9520 */
9521 @Deprecated
9522 @Nullable
9523 public String getApplicationRestrictionsManagingPackage(
9524 @NonNull ComponentName admin) {
9525 throwIfParentInstance("getApplicationRestrictionsManagingPackage");
9526 if (mService != null) {
9527 try {
9528 return mService.getApplicationRestrictionsManagingPackage(admin);
9529 } catch (RemoteException e) {
9530 throw e.rethrowFromSystemServer();
9531 }
9532 }
9533 return null;
9534 }
9535
9536 /**
9537 * Called by any application to find out whether it has been granted permission via
9538 * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
9539 * for the calling user.
9540 *
9541 * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
9542 * that method.
9543 *
9544 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
9545 * instead.
9546 */
9547 @Deprecated
9548 public boolean isCallerApplicationRestrictionsManagingPackage() {
9549 throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
9550 if (mService != null) {
9551 try {
9552 return mService.isCallerApplicationRestrictionsManagingPackage(
9553 mContext.getPackageName());
9554 } catch (RemoteException e) {
9555 throw e.rethrowFromSystemServer();
9556 }
9557 }
9558 return false;
9559 }
9560
9561 /**
9562 * Sets the application restrictions for a given target application running in the calling user.
9563 * <p>
9564 * The caller must be a profile or device owner on that user, or the package allowed to manage
9565 * application restrictions via {@link #setDelegatedScopes} with the
9566 * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
9567 * <p>
9568 * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
9569 * <ul>
9570 * <li>{@code boolean}
9571 * <li>{@code int}
9572 * <li>{@code String} or {@code String[]}
9573 * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
9574 * </ul>
9575 * <p>
9576 * If the restrictions are not available yet, but may be applied in the near future, the caller
9577 * can notify the target application of that by adding
9578 * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
9579 * <p>
9580 * The application restrictions are only made visible to the target application via
9581 * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
9582 * owner, and the application restrictions managing package via
9583 * {@link #getApplicationRestrictions}.
9584 *
9585 * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
9586 *
9587 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9588 * {@code null} if called by the application restrictions managing package.
9589 * @param packageName The name of the package to update restricted settings for.
9590 * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
9591 * set of active restrictions.
9592 * @throws SecurityException if {@code admin} is not a device or profile owner.
9593 * @see #setDelegatedScopes
9594 * @see #DELEGATION_APP_RESTRICTIONS
9595 * @see UserManager#KEY_RESTRICTIONS_PENDING
9596 */
9597 @WorkerThread
9598 public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
9599 Bundle settings) {
9600 throwIfParentInstance("setApplicationRestrictions");
9601 if (mService != null) {
9602 try {
9603 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
9604 settings);
9605 } catch (RemoteException e) {
9606 throw e.rethrowFromSystemServer();
9607 }
9608 }
9609 }
9610
9611 /**
9612 * Sets a list of configuration features to enable for a trust agent component. This is meant to
9613 * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
9614 * agents but those enabled by this function call. If flag
9615 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
9616 * <p>
9617 * For any specific trust agent, whether it is disabled or not depends on the aggregated state
9618 * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
9619 * configuration as set by this function call. In particular: if any admin sets
9620 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
9621 * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
9622 * will receive the list of configurations from all admins who set
9623 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
9624 * behavior. The exact meaning of aggregation is trust-agent-specific.
9625 * <p>
9626 * The calling device admin must have requested
9627 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
9628 * if not, a security exception will be thrown.
9629 * <p>
9630 * This method can be called on the {@link DevicePolicyManager} instance returned by
9631 * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
9632 * the parent profile.
9633 * <p>
9634 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
9635 * this method has no effect - no trust agent configuration will be set.
9636 *
9637 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9638 * @param target Component name of the agent to be configured.
9639 * @param configuration Trust-agent-specific feature configuration bundle. Please consult
9640 * documentation of the specific trust agent to determine the interpretation of this
9641 * bundle.
9642 * @throws SecurityException if {@code admin} is not an active administrator or does not use
9643 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
9644 */
9645 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
9646 public void setTrustAgentConfiguration(@NonNull ComponentName admin,
9647 @NonNull ComponentName target, PersistableBundle configuration) {
9648 if (mService != null) {
9649 try {
9650 mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
9651 } catch (RemoteException e) {
9652 throw e.rethrowFromSystemServer();
9653 }
9654 }
9655 }
9656
9657 /**
9658 * Gets configuration for the given trust agent based on aggregating all calls to
9659 * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
9660 * all device admins.
9661 * <p>
9662 * This method can be called on the {@link DevicePolicyManager} instance returned by
9663 * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
9664 * on the parent profile.
9665 * <p>
9666 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
9667 * always returned.
9668 *
9669 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
9670 * this function returns a list of configurations for all admins that declare
9671 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
9672 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
9673 * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
9674 * for this {@param agent} or calls it with a null configuration, null is returned.
9675 * @param agent Which component to get enabled features for.
9676 * @return configuration for the given trust agent.
9677 */
9678 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
9679 public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
9680 @Nullable ComponentName admin, @NonNull ComponentName agent) {
9681 return getTrustAgentConfiguration(admin, agent, myUserId());
9682 }
9683
9684 /** @hide per-user version */
9685 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
9686 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
9687 public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
9688 @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
9689 if (mService != null) {
9690 try {
9691 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
9692 mParentInstance);
9693 } catch (RemoteException e) {
9694 throw e.rethrowFromSystemServer();
9695 }
9696 }
9697 return new ArrayList<PersistableBundle>(); // empty list
9698 }
9699
9700 /**
9701 * Called by a profile owner of a managed profile to set whether caller-Id information from the
9702 * managed profile will be shown in the parent profile, for incoming calls.
9703 * <p>
9704 * The calling device admin must be a profile owner. If it is not, a security exception will be
9705 * thrown.
9706 *
9707 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9708 * @param disabled If true caller-Id information in the managed profile is not displayed.
9709 * @throws SecurityException if {@code admin} is not a profile owner.
9710 */
9711 public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
9712 throwIfParentInstance("setCrossProfileCallerIdDisabled");
9713 if (mService != null) {
9714 try {
9715 mService.setCrossProfileCallerIdDisabled(admin, disabled);
9716 } catch (RemoteException e) {
9717 throw e.rethrowFromSystemServer();
9718 }
9719 }
9720 }
9721
9722 /**
9723 * Called by a profile owner of a managed profile to determine whether or not caller-Id
9724 * information has been disabled.
9725 * <p>
9726 * The calling device admin must be a profile owner. If it is not, a security exception will be
9727 * thrown.
9728 *
9729 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9730 * @throws SecurityException if {@code admin} is not a profile owner.
9731 */
9732 public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
9733 throwIfParentInstance("getCrossProfileCallerIdDisabled");
9734 if (mService != null) {
9735 try {
9736 return mService.getCrossProfileCallerIdDisabled(admin);
9737 } catch (RemoteException e) {
9738 throw e.rethrowFromSystemServer();
9739 }
9740 }
9741 return false;
9742 }
9743
9744 /**
9745 * Determine whether or not caller-Id information has been disabled.
9746 *
9747 * @param userHandle The user for whom to check the caller-id permission
9748 * @hide
9749 */
9750 public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
9751 if (mService != null) {
9752 try {
9753 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
9754 } catch (RemoteException e) {
9755 throw e.rethrowFromSystemServer();
9756 }
9757 }
9758 return false;
9759 }
9760
9761 /**
9762 * Called by a profile owner of a managed profile to set whether contacts search from the
9763 * managed profile will be shown in the parent profile, for incoming calls.
9764 * <p>
9765 * The calling device admin must be a profile owner. If it is not, a security exception will be
9766 * thrown.
9767 *
9768 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9769 * @param disabled If true contacts search in the managed profile is not displayed.
9770 * @throws SecurityException if {@code admin} is not a profile owner.
9771 */
9772 public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
9773 boolean disabled) {
9774 throwIfParentInstance("setCrossProfileContactsSearchDisabled");
9775 if (mService != null) {
9776 try {
9777 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
9778 } catch (RemoteException e) {
9779 throw e.rethrowFromSystemServer();
9780 }
9781 }
9782 }
9783
9784 /**
9785 * Called by a profile owner of a managed profile to determine whether or not contacts search
9786 * has been disabled.
9787 * <p>
9788 * The calling device admin must be a profile owner. If it is not, a security exception will be
9789 * thrown.
9790 *
9791 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9792 * @throws SecurityException if {@code admin} is not a profile owner.
9793 */
9794 public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
9795 throwIfParentInstance("getCrossProfileContactsSearchDisabled");
9796 if (mService != null) {
9797 try {
9798 return mService.getCrossProfileContactsSearchDisabled(admin);
9799 } catch (RemoteException e) {
9800 throw e.rethrowFromSystemServer();
9801 }
9802 }
9803 return false;
9804 }
9805
9806
9807 /**
9808 * Determine whether or not contacts search has been disabled.
9809 *
9810 * @param userHandle The user for whom to check the contacts search permission
9811 * @hide
9812 */
9813 public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
9814 if (mService != null) {
9815 try {
9816 return mService
9817 .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
9818 } catch (RemoteException e) {
9819 throw e.rethrowFromSystemServer();
9820 }
9821 }
9822 return false;
9823 }
9824
9825 /**
9826 * Start Quick Contact on the managed profile for the user, if the policy allows.
9827 *
9828 * @hide
9829 */
9830 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
9831 boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
9832 if (mService != null) {
9833 try {
9834 mService.startManagedQuickContact(actualLookupKey, actualContactId,
9835 isContactIdIgnored, directoryId, originalIntent);
9836 } catch (RemoteException e) {
9837 throw e.rethrowFromSystemServer();
9838 }
9839 }
9840 }
9841
9842 /**
9843 * Start Quick Contact on the managed profile for the user, if the policy allows.
9844 * @hide
9845 */
9846 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
9847 Intent originalIntent) {
9848 startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
9849 originalIntent);
9850 }
9851
9852 /**
9853 * Called by a profile owner of a managed profile to set whether bluetooth devices can access
9854 * enterprise contacts.
9855 * <p>
9856 * The calling device admin must be a profile owner. If it is not, a security exception will be
9857 * thrown.
9858 * <p>
9859 * This API works on managed profile only.
9860 *
9861 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9862 * @param disabled If true, bluetooth devices cannot access enterprise contacts.
9863 * @throws SecurityException if {@code admin} is not a profile owner.
9864 */
9865 public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
9866 throwIfParentInstance("setBluetoothContactSharingDisabled");
9867 if (mService != null) {
9868 try {
9869 mService.setBluetoothContactSharingDisabled(admin, disabled);
9870 } catch (RemoteException e) {
9871 throw e.rethrowFromSystemServer();
9872 }
9873 }
9874 }
9875
9876 /**
9877 * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
9878 * cannot access enterprise contacts.
9879 * <p>
9880 * The calling device admin must be a profile owner. If it is not, a security exception will be
9881 * thrown.
9882 * <p>
9883 * This API works on managed profile only.
9884 *
9885 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9886 * @throws SecurityException if {@code admin} is not a profile owner.
9887 */
9888 public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
9889 throwIfParentInstance("getBluetoothContactSharingDisabled");
9890 if (mService != null) {
9891 try {
9892 return mService.getBluetoothContactSharingDisabled(admin);
9893 } catch (RemoteException e) {
9894 throw e.rethrowFromSystemServer();
9895 }
9896 }
9897 return true;
9898 }
9899
9900 /**
9901 * Determine whether or not Bluetooth devices cannot access contacts.
9902 * <p>
9903 * This API works on managed profile UserHandle only.
9904 *
9905 * @param userHandle The user for whom to check the caller-id permission
9906 * @hide
9907 */
9908 @SystemApi
9909 @RequiresPermission(permission.INTERACT_ACROSS_USERS)
9910 public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) {
9911 if (mService != null) {
9912 try {
9913 return mService.getBluetoothContactSharingDisabledForUser(userHandle
9914 .getIdentifier());
9915 } catch (RemoteException e) {
9916 throw e.rethrowFromSystemServer();
9917 }
9918 }
9919 return true;
9920 }
9921
9922 /**
9923 * Called by the profile owner of a managed profile so that some intents sent in the managed
9924 * profile can also be resolved in the parent, or vice versa. Only activity intents are
9925 * supported.
9926 *
9927 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9928 * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
9929 * other profile
9930 * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
9931 * {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
9932 * @throws SecurityException if {@code admin} is not a device or profile owner.
9933 */
9934 public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
9935 throwIfParentInstance("addCrossProfileIntentFilter");
9936 if (mService != null) {
9937 try {
9938 mService.addCrossProfileIntentFilter(admin, filter, flags);
9939 } catch (RemoteException e) {
9940 throw e.rethrowFromSystemServer();
9941 }
9942 }
9943 }
9944
9945 /**
9946 * Called by a profile owner of a managed profile to remove the cross-profile intent filters
9947 * that go from the managed profile to the parent, or from the parent to the managed profile.
9948 * Only removes those that have been set by the profile owner.
9949 * <p>
9950 * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
9951 * the profile is created, some of them ensure the proper functioning of the profile, while
9952 * others enable sharing of data from the parent to the managed profile for user convenience.
9953 * These default intent filters are not cleared when this API is called. If the default cross
9954 * profile data sharing is not desired, they can be disabled with
9955 * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
9956 *
9957 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9958 * @throws SecurityException if {@code admin} is not a profile owner.
9959 */
9960 public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
9961 throwIfParentInstance("clearCrossProfileIntentFilters");
9962 if (mService != null) {
9963 try {
9964 mService.clearCrossProfileIntentFilters(admin);
9965 } catch (RemoteException e) {
9966 throw e.rethrowFromSystemServer();
9967 }
9968 }
9969 }
9970
9971 /**
9972 * Called by a profile or device owner to set the permitted
9973 * {@link android.accessibilityservice.AccessibilityService}. When set by
9974 * a device owner or profile owner the restriction applies to all profiles of the user the
9975 * device owner or profile owner is an admin for. By default, the user can use any accessibility
9976 * service. When zero or more packages have been added, accessibility services that are not in
9977 * the list and not part of the system can not be enabled by the user.
9978 * <p>
9979 * Calling with a {@code null} value for the list disables the restriction so that all services
9980 * can be used, calling with an empty list only allows the built-in system services. Any
9981 * non-system accessibility service that's currently enabled must be included in the list.
9982 * <p>
9983 * System accessibility services are always available to the user and this method can't
9984 * disable them.
9985 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9986 * @param packageNames List of accessibility service package names.
9987 * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
9988 * contain every enabled non-system accessibility service.
9989 * @throws SecurityException if {@code admin} is not a device or profile owner.
9990 */
9991 public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
9992 List<String> packageNames) {
9993 throwIfParentInstance("setPermittedAccessibilityServices");
9994 if (mService != null) {
9995 try {
9996 return mService.setPermittedAccessibilityServices(admin, packageNames);
9997 } catch (RemoteException e) {
9998 throw e.rethrowFromSystemServer();
9999 }
10000 }
10001 return false;
10002 }
10003
10004 /**
10005 * Returns the list of permitted accessibility services set by this device or profile owner.
10006 * <p>
10007 * An empty list means no accessibility services except system services are allowed.
10008 * {@code null} means all accessibility services are allowed.
10009 *
10010 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10011 * @return List of accessiblity service package names.
10012 * @throws SecurityException if {@code admin} is not a device or profile owner.
10013 */
10014 public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
10015 throwIfParentInstance("getPermittedAccessibilityServices");
10016 if (mService != null) {
10017 try {
10018 return mService.getPermittedAccessibilityServices(admin);
10019 } catch (RemoteException e) {
10020 throw e.rethrowFromSystemServer();
10021 }
10022 }
10023 return null;
10024 }
10025
10026 /**
10027 * Called by the system to check if a specific accessibility service is disabled by admin.
10028 *
10029 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10030 * @param packageName Accessibility service package name that needs to be checked.
10031 * @param userHandle user id the admin is running as.
10032 * @return true if the accessibility service is permitted, otherwise false.
10033 *
10034 * @hide
10035 */
10036 public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
10037 @NonNull String packageName, int userHandle) {
10038 if (mService != null) {
10039 try {
10040 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
10041 userHandle);
10042 } catch (RemoteException e) {
10043 throw e.rethrowFromSystemServer();
10044 }
10045 }
10046 return false;
10047 }
10048
10049 /**
10050 * Returns the list of accessibility services permitted by the device or profiles
10051 * owners of this user.
10052 *
10053 * <p>{@code null} means all accessibility services are allowed, if a non-null list is returned
10054 * it will contain the intersection of the permitted lists for any device or profile
10055 * owners that apply to this user. It will also include any system accessibility services.
10056 *
10057 * @param userId which user to check for.
10058 * @return List of accessiblity service package names.
10059 * @hide
10060 */
10061 @SystemApi
10062 @RequiresPermission(anyOf = {
10063 android.Manifest.permission.MANAGE_USERS,
10064 android.Manifest.permission.QUERY_ADMIN_POLICY})
10065 public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
10066 throwIfParentInstance("getPermittedAccessibilityServices");
10067 if (mService != null) {
10068 try {
10069 return mService.getPermittedAccessibilityServicesForUser(userId);
10070 } catch (RemoteException e) {
10071 throw e.rethrowFromSystemServer();
10072 }
10073 }
10074 return null;
10075 }
10076
10077 /**
10078 * Called by a profile or device owner to set the permitted input methods services for this
10079 * user. By default, the user can use any input method.
10080 * <p>
10081 * This method can be called on the {@link DevicePolicyManager} instance,
10082 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
10083 * a profile owner of an organization-owned device.
10084 * <p>
10085 * If called on the parent instance:
10086 * <ul>
10087 * <li>The permitted input methods will be applied on the personal profile</li>
10088 * <li>Can only permit all input methods (calling this method with a {@code null} package
10089 * list) or only permit system input methods (calling this method with an empty package
10090 * list). This is to prevent the caller from learning which packages are installed on
10091 * the personal side</li>
10092 * </ul>
10093 * <p>
10094 * When zero or more packages have been added, input method that are not in the list and not
10095 * part of the system can not be enabled by the user. This method will fail if it is called for
10096 * a admin that is not for the foreground user or a profile of the foreground user. Any
10097 * non-system input method service that's currently enabled must be included in the list.
10098 * <p>
10099 * Calling with a null value for the list disables the restriction so that all input methods can
10100 * be used, calling with an empty list disables all but the system's own input methods.
10101 * <p>
10102 * System input methods are always available to the user - this method can't modify this.
10103 *
10104 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10105 * @param packageNames List of input method package names.
10106 * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
10107 * contain every enabled non-system input method service.
10108 * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
10109 * the parent profile and the {@code admin} is not a profile owner
10110 * of an organization-owned managed profile.
10111 * @throws IllegalArgumentException if called on the parent profile, the {@code admin} is a
10112 * profile owner of an organization-owned managed profile and the
10113 * list of permitted input method package names is not null or empty.
10114 */
10115 public boolean setPermittedInputMethods(
10116 @NonNull ComponentName admin, List<String> packageNames) {
10117 if (mService != null) {
10118 try {
10119 return mService.setPermittedInputMethods(admin, packageNames, mParentInstance);
10120 } catch (RemoteException e) {
10121 throw e.rethrowFromSystemServer();
10122 }
10123 }
10124 return false;
10125 }
10126
10127
10128 /**
10129 * Returns the list of permitted input methods set by this device or profile owner.
10130 * <p>
10131 * This method can be called on the {@link DevicePolicyManager} instance,
10132 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
10133 * a profile owner of an organization-owned managed profile. If called on the parent instance,
10134 * then the returned list of permitted input methods are those which are applied on the
10135 * personal profile.
10136 * <p>
10137 * An empty list means no input methods except system input methods are allowed. Null means all
10138 * input methods are allowed.
10139 *
10140 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10141 * @return List of input method package names.
10142 * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
10143 * the parent profile and the {@code admin} is not a profile owner
10144 * of an organization-owned managed profile.
10145 */
10146 public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
10147 if (mService != null) {
10148 try {
10149 return mService.getPermittedInputMethods(admin, mParentInstance);
10150 } catch (RemoteException e) {
10151 throw e.rethrowFromSystemServer();
10152 }
10153 }
10154 return null;
10155 }
10156
10157 /**
10158 * Called by the system to check if a specific input method is disabled by admin.
10159 * <p>
10160 * This method can be called on the {@link DevicePolicyManager} instance,
10161 * returned by {@link #getParentProfileInstance(ComponentName)}. If called on the parent
10162 * instance, this method will check whether the given input method is permitted on
10163 * the personal profile.
10164 *
10165 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10166 * @param packageName Input method package name that needs to be checked.
10167 * @param userHandle user id the admin is running as.
10168 * @return true if the input method is permitted, otherwise false.
10169 *
10170 * @hide
10171 */
10172 public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
10173 @NonNull String packageName, int userHandle) {
10174 if (mService != null) {
10175 try {
10176 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle,
10177 mParentInstance);
10178 } catch (RemoteException e) {
10179 throw e.rethrowFromSystemServer();
10180 }
10181 }
10182 return false;
10183 }
10184
10185 /**
10186 * Returns the list of input methods permitted by the device or profiles owners.
10187 *
10188 * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
10189 * result for the calling user.</p>
10190 *
10191 * <p>On Android P and prior devices, this method returns the result for the current user.</p>
10192 *
10193 * <p>Null means all input methods are allowed, if a non-null list is returned
10194 * it will contain the intersection of the permitted lists for any device or profile
10195 * owners that apply to this user. It will also include any system input methods.
10196 *
10197 * @return List of input method package names.
10198 * @hide
10199 *
10200 * @see #setPermittedAccessibilityServices(ComponentName, List)
10201 */
10202 @SystemApi
10203 @RequiresPermission(anyOf = {
10204 android.Manifest.permission.MANAGE_USERS,
10205 android.Manifest.permission.QUERY_ADMIN_POLICY})
10206 public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
10207 throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
10208 if (mService != null) {
10209 try {
10210 return mService.getPermittedInputMethodsAsUser(UserHandle.myUserId());
10211 } catch (RemoteException e) {
10212 throw e.rethrowFromSystemServer();
10213 }
10214 }
10215 return null;
10216 }
10217
10218 /**
10219 * Returns the list of input methods permitted.
10220 *
10221 * <p>{@code null} means all input methods are allowed, if a non-null list is returned
10222 * it will contain the intersection of the permitted lists for any device or profile
10223 * owners that apply to this user. It will also include any system input methods.
10224 *
10225 * @return List of input method package names.
10226 * @hide
10227 *
10228 * @see #setPermittedAccessibilityServices(ComponentName, List)
10229 */
10230 @UserHandleAware
10231 @RequiresPermission(allOf = {
10232 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10233 android.Manifest.permission.MANAGE_USERS
10234 }, conditional = true)
10235 public @Nullable List<String> getPermittedInputMethods() {
10236 throwIfParentInstance("getPermittedInputMethods");
10237 if (mService != null) {
10238 try {
10239 return mService.getPermittedInputMethodsAsUser(myUserId());
10240 } catch (RemoteException e) {
10241 throw e.rethrowFromSystemServer();
10242 }
10243 }
10244 return null;
10245 }
10246
10247 /**
10248 * Called by a profile owner of a managed profile to set the packages that are allowed to use
10249 * a {@link android.service.notification.NotificationListenerService} in the primary user to
10250 * see notifications from the managed profile. By default all packages are permitted by this
10251 * policy. When zero or more packages have been added, notification listeners installed on the
10252 * primary user that are not in the list and are not part of the system won't receive events
10253 * for managed profile notifications.
10254 * <p>
10255 * Calling with a {@code null} value for the list disables the restriction so that all
10256 * notification listener services be used. Calling with an empty list disables all but the
10257 * system's own notification listeners. System notification listener services are always
10258 * available to the user.
10259 * <p>
10260 * If a device or profile owner want to stop notification listeners in their user from seeing
10261 * that user's notifications they should prevent that service from running instead (e.g. via
10262 * {@link #setApplicationHidden(ComponentName, String, boolean)})
10263 *
10264 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10265 * @param packageList List of package names to allowlist
10266 * @return true if setting the restriction succeeded. It will fail if called outside a managed
10267 * profile
10268 * @throws SecurityException if {@code admin} is not a profile owner.
10269 *
10270 * @see android.service.notification.NotificationListenerService
10271 */
10272 public boolean setPermittedCrossProfileNotificationListeners(
10273 @NonNull ComponentName admin, @Nullable List<String> packageList) {
10274 throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
10275 if (mService != null) {
10276 try {
10277 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
10278 } catch (RemoteException e) {
10279 throw e.rethrowFromSystemServer();
10280 }
10281 }
10282 return false;
10283 }
10284
10285 /**
10286 * Returns the list of packages installed on the primary user that allowed to use a
10287 * {@link android.service.notification.NotificationListenerService} to receive
10288 * notifications from this managed profile, as set by the profile owner.
10289 * <p>
10290 * An empty list means no notification listener services except system ones are allowed.
10291 * A {@code null} return value indicates that all notification listeners are allowed.
10292 */
10293 public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
10294 @NonNull ComponentName admin) {
10295 throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
10296 if (mService != null) {
10297 try {
10298 return mService.getPermittedCrossProfileNotificationListeners(admin);
10299 } catch (RemoteException e) {
10300 throw e.rethrowFromSystemServer();
10301 }
10302 }
10303 return null;
10304 }
10305
10306 /**
10307 * Returns true if {@code NotificationListenerServices} from the given package are allowed to
10308 * receive events for notifications from the given user id. Can only be called by the system uid
10309 *
10310 * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
10311 *
10312 * @hide
10313 */
10314 public boolean isNotificationListenerServicePermitted(
10315 @NonNull String packageName, @UserIdInt int userId) {
10316 if (mService != null) {
10317 try {
10318 return mService.isNotificationListenerServicePermitted(packageName, userId);
10319 } catch (RemoteException e) {
10320 throw e.rethrowFromSystemServer();
10321 }
10322 }
10323 return true;
10324 }
10325
10326 /**
10327 * Get the list of apps to keep around as APKs even if no user has currently installed it. This
10328 * function can be called by a device owner or by a delegate given the
10329 * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
10330 * <p>
10331 * Please note that packages returned in this method are not automatically pre-cached.
10332 *
10333 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10334 * {@code null} if the caller is a keep uninstalled packages delegate.
10335 * @return List of package names to keep cached.
10336 * @see #setDelegatedScopes
10337 * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
10338 */
10339 public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
10340 throwIfParentInstance("getKeepUninstalledPackages");
10341 if (mService != null) {
10342 try {
10343 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
10344 } catch (RemoteException e) {
10345 throw e.rethrowFromSystemServer();
10346 }
10347 }
10348 return null;
10349 }
10350
10351 /**
10352 * Set a list of apps to keep around as APKs even if no user has currently installed it. This
10353 * function can be called by a device owner or by a delegate given the
10354 * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
10355 *
10356 * <p>Please note that setting this policy does not imply that specified apps will be
10357 * automatically pre-cached.</p>
10358 *
10359 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10360 * {@code null} if the caller is a keep uninstalled packages delegate.
10361 * @param packageNames List of package names to keep cached.
10362 * @throws SecurityException if {@code admin} is not a device owner.
10363 * @see #setDelegatedScopes
10364 * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
10365 */
10366 public void setKeepUninstalledPackages(@Nullable ComponentName admin,
10367 @NonNull List<String> packageNames) {
10368 throwIfParentInstance("setKeepUninstalledPackages");
10369 if (mService != null) {
10370 try {
10371 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
10372 } catch (RemoteException e) {
10373 throw e.rethrowFromSystemServer();
10374 }
10375 }
10376 }
10377
10378 /**
10379 * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
10380 */
10381 public static final int SKIP_SETUP_WIZARD = 0x0001;
10382
10383 /**
10384 * Flag used by {@link #createAndManageUser} to specify that the user should be created
10385 * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
10386 * device.
10387 */
10388 public static final int MAKE_USER_EPHEMERAL = 0x0002;
10389
10390 /**
10391 * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
10392 * demo user.
10393 * @hide
10394 */
10395 public static final int MAKE_USER_DEMO = 0x0004;
10396
10397 /**
10398 * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
10399 * the disabling of system apps during provisioning.
10400 */
10401 public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
10402
10403 /**
10404 * @hide
10405 */
10406 @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
10407 SKIP_SETUP_WIZARD,
10408 MAKE_USER_EPHEMERAL,
10409 MAKE_USER_DEMO,
10410 LEAVE_ALL_SYSTEM_APPS_ENABLED
10411 })
10412 @Retention(RetentionPolicy.SOURCE)
10413 public @interface CreateAndManageUserFlags {}
10414
10415 /**
10416 * Called by a device owner to create a user with the specified name and a given component of
10417 * the calling package as profile owner. The UserHandle returned by this method should not be
10418 * persisted as user handles are recycled as users are removed and created. If you need to
10419 * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
10420 * user will not be started in the background.
10421 * <p>
10422 * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
10423 * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
10424 * be registered as an active admin on the new user. The profile owner package will be installed
10425 * on the new user.
10426 * <p>
10427 * If the adminExtras are not null, they will be stored on the device until the user is started
10428 * for the first time. Then the extras will be passed to the admin when onEnable is called.
10429 * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
10430 * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
10431 * returning {@code null} on failure.
10432 *
10433 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10434 * @param name The user's name.
10435 * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
10436 * same package as admin, otherwise no user is created and an
10437 * IllegalArgumentException is thrown.
10438 * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
10439 * user.
10440 * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
10441 * {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
10442 * @see UserHandle
10443 * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
10444 * user could not be created.
10445 * @throws SecurityException if {@code admin} is not a device owner.
10446 * @throws UserOperationException if the user could not be created and the calling app is
10447 * targeting {@link android.os.Build.VERSION_CODES#P} and running on
10448 * {@link android.os.Build.VERSION_CODES#P}.
10449 */
10450 public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
10451 @NonNull String name,
10452 @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
10453 @CreateAndManageUserFlags int flags) {
10454 throwIfParentInstance("createAndManageUser");
10455 try {
10456 return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
10457 } catch (ServiceSpecificException e) {
10458 throw new UserOperationException(e.getMessage(), e.errorCode);
10459 } catch (RemoteException re) {
10460 throw re.rethrowFromSystemServer();
10461 }
10462 }
10463
10464 /**
10465 * Called by a device owner to remove a user/profile and all associated data. The primary user
10466 * can not be removed.
10467 *
10468 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10469 * @param userHandle the user to remove.
10470 * @return {@code true} if the user was removed, {@code false} otherwise.
10471 * @throws SecurityException if {@code admin} is not a device owner.
10472 */
10473 public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
10474 throwIfParentInstance("removeUser");
10475 try {
10476 return mService.removeUser(admin, userHandle);
10477 } catch (RemoteException re) {
10478 throw re.rethrowFromSystemServer();
10479 }
10480 }
10481
10482 /**
10483 * Called by a device owner to switch the specified secondary user to the foreground.
10484 *
10485 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10486 * @param userHandle the user to switch to; null will switch to primary.
10487 * @return {@code true} if the switch was successful, {@code false} otherwise.
10488 * @throws SecurityException if {@code admin} is not a device owner.
10489 * @see Intent#ACTION_USER_FOREGROUND
10490 * @see #getSecondaryUsers(ComponentName)
10491 */
10492 public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
10493 throwIfParentInstance("switchUser");
10494 try {
10495 return mService.switchUser(admin, userHandle);
10496 } catch (RemoteException re) {
10497 throw re.rethrowFromSystemServer();
10498 }
10499 }
10500
10501 /**
10502 * Called by a device owner to start the specified secondary user in background.
10503 *
10504 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10505 * @param userHandle the user to be started in background.
10506 * @return one of the following result codes:
10507 * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
10508 * {@link UserManager#USER_OPERATION_SUCCESS},
10509 * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
10510 * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
10511 * @throws SecurityException if {@code admin} is not a device owner.
10512 * @see #getSecondaryUsers(ComponentName)
10513 */
10514 public @UserOperationResult int startUserInBackground(
10515 @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
10516 throwIfParentInstance("startUserInBackground");
10517 try {
10518 return mService.startUserInBackground(admin, userHandle);
10519 } catch (RemoteException re) {
10520 throw re.rethrowFromSystemServer();
10521 }
10522 }
10523
10524 /**
10525 * Called by a device owner to stop the specified secondary user.
10526 *
10527 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10528 * @param userHandle the user to be stopped.
10529 * @return one of the following result codes:
10530 * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
10531 * {@link UserManager#USER_OPERATION_SUCCESS},
10532 * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
10533 * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
10534 * @throws SecurityException if {@code admin} is not a device owner.
10535 * @see #getSecondaryUsers(ComponentName)
10536 */
10537 public @UserOperationResult int stopUser(
10538 @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
10539 throwIfParentInstance("stopUser");
10540 try {
10541 return mService.stopUser(admin, userHandle);
10542 } catch (RemoteException re) {
10543 throw re.rethrowFromSystemServer();
10544 }
10545 }
10546
10547 /**
10548 * Called by a profile owner of secondary user that is affiliated with the device to stop the
10549 * calling user and switch back to primary user (when the user was
10550 * {@link #switchUser(ComponentName, UserHandle)} switched to) or stop the user (when it was
10551 * {@link #startUserInBackground(ComponentName, UserHandle) started in background}.
10552 *
10553 * <p>Notice that on devices running with
10554 * {@link UserManager#isHeadlessSystemUserMode() headless system user mode}, there is no primary
10555 * user, so it switches back to the user that was in the foreground before the first call to
10556 * {@link #switchUser(ComponentName, UserHandle)} (or fails with
10557 * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN} if that method was not called prior to this
10558 * call).
10559 *
10560 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10561 * @return one of the following result codes:
10562 * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
10563 * {@link UserManager#USER_OPERATION_SUCCESS},
10564 * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
10565 * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
10566 * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
10567 * @see #getSecondaryUsers(ComponentName)
10568 */
10569 public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
10570 throwIfParentInstance("logoutUser");
10571 try {
10572 return mService.logoutUser(admin);
10573 } catch (RemoteException re) {
10574 throw re.rethrowFromSystemServer();
10575 }
10576 }
10577
10578 /**
10579 * Similar to {@link #logoutUser(ComponentName)}, except:
10580 *
10581 * <ul>
10582 * <li>Called by system (like Settings), not admin.
10583 * <li>It logs out the current user, not the caller.
10584 * </ul>
10585 *
10586 * @hide
10587 */
10588 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
10589 android.Manifest.permission.INTERACT_ACROSS_USERS})
10590 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
10591 public @UserOperationResult int logoutUser() {
10592 // TODO(b/214336184): add CTS test
10593 try {
10594 return mService.logoutUserInternal();
10595 } catch (RemoteException re) {
10596 throw re.rethrowFromSystemServer();
10597 }
10598 }
10599
10600 /**
10601 * Gets the user a {@link #logoutUser(ComponentName)} call would switch to,
10602 * or {@code null} if the current user is not in a session (i.e., if it was not
10603 * {@link #switchUser(ComponentName, UserHandle) switched} or
10604 * {@link #startUserInBackground(ComponentName, UserHandle) started in background} by the
10605 * device admin.
10606 *
10607 * @hide
10608 */
10609 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
10610 android.Manifest.permission.INTERACT_ACROSS_USERS})
10611 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
10612 public @Nullable UserHandle getLogoutUser() {
10613 // TODO(b/214336184): add CTS test
10614 try {
10615 int userId = mService.getLogoutUserId();
10616 return userId == UserHandle.USER_NULL ? null : UserHandle.of(userId);
10617 } catch (RemoteException re) {
10618 throw re.rethrowFromSystemServer();
10619 }
10620 }
10621
10622 /**
10623 * Called by a device owner to list all secondary users on the device. Managed profiles are not
10624 * considered as secondary users.
10625 * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
10626 * and {@link #stopUser}.
10627 *
10628 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10629 * @return list of other {@link UserHandle}s on the device.
10630 * @throws SecurityException if {@code admin} is not a device owner.
10631 * @see #removeUser(ComponentName, UserHandle)
10632 * @see #switchUser(ComponentName, UserHandle)
10633 * @see #startUserInBackground(ComponentName, UserHandle)
10634 * @see #stopUser(ComponentName, UserHandle)
10635 */
10636 public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
10637 throwIfParentInstance("getSecondaryUsers");
10638 try {
10639 return mService.getSecondaryUsers(admin);
10640 } catch (RemoteException re) {
10641 throw re.rethrowFromSystemServer();
10642 }
10643 }
10644
10645 /**
10646 * Checks if the profile owner is running in an ephemeral user.
10647 *
10648 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10649 * @return whether the profile owner is running in an ephemeral user.
10650 */
10651 public boolean isEphemeralUser(@NonNull ComponentName admin) {
10652 throwIfParentInstance("isEphemeralUser");
10653 try {
10654 return mService.isEphemeralUser(admin);
10655 } catch (RemoteException re) {
10656 throw re.rethrowFromSystemServer();
10657 }
10658 }
10659
10660 /**
10661 * Retrieves the application restrictions for a given target application running in the calling
10662 * user.
10663 * <p>
10664 * The caller must be a profile or device owner on that user, or the package allowed to manage
10665 * application restrictions via {@link #setDelegatedScopes} with the
10666 * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
10667 *
10668 * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
10669 *
10670 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10671 * {@code null} if called by the application restrictions managing package.
10672 * @param packageName The name of the package to fetch restricted settings of.
10673 * @return {@link Bundle} of settings corresponding to what was set last time
10674 * {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
10675 * {@link Bundle} if no restrictions have been set.
10676 * @throws SecurityException if {@code admin} is not a device or profile owner.
10677 * @see #setDelegatedScopes
10678 * @see #DELEGATION_APP_RESTRICTIONS
10679 */
10680 @WorkerThread
10681 public @NonNull Bundle getApplicationRestrictions(
10682 @Nullable ComponentName admin, String packageName) {
10683 throwIfParentInstance("getApplicationRestrictions");
10684 if (mService != null) {
10685 try {
10686 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
10687 packageName);
10688 } catch (RemoteException e) {
10689 throw e.rethrowFromSystemServer();
10690 }
10691 }
10692 return null;
10693 }
10694
10695 /**
10696 * Called by a profile or device owner to set a user restriction specified by the key.
10697 * <p>
10698 * The calling device admin must be a profile or device owner; if it is not, a security
10699 * exception will be thrown.
10700 * <p>
10701 * The profile owner of an organization-owned managed profile may invoke this method on
10702 * the {@link DevicePolicyManager} instance it obtained from
10703 * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions.
10704 * <p>
10705 * See the constants in {@link android.os.UserManager} for the list of restrictions that can
10706 * be enforced device-wide.
10707 *
10708 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10709 * @param key The key of the restriction.
10710 * @throws SecurityException if {@code admin} is not a device or profile owner.
10711 */
10712 public void addUserRestriction(@NonNull ComponentName admin,
10713 @UserManager.UserRestrictionKey String key) {
10714 if (mService != null) {
10715 try {
10716 mService.setUserRestriction(admin, key, true, mParentInstance);
10717 } catch (RemoteException e) {
10718 throw e.rethrowFromSystemServer();
10719 }
10720 }
10721 }
10722
10723 /**
10724 * Called by a profile or device owner to clear a user restriction specified by the key.
10725 * <p>
10726 * The calling device admin must be a profile or device owner; if it is not, a security
10727 * exception will be thrown.
10728 * <p>
10729 * The profile owner of an organization-owned managed profile may invoke this method on
10730 * the {@link DevicePolicyManager} instance it obtained from
10731 * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions.
10732 * <p>
10733 * See the constants in {@link android.os.UserManager} for the list of restrictions.
10734 *
10735 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10736 * @param key The key of the restriction.
10737 * @throws SecurityException if {@code admin} is not a device or profile owner.
10738 */
10739 public void clearUserRestriction(@NonNull ComponentName admin,
10740 @UserManager.UserRestrictionKey String key) {
10741 if (mService != null) {
10742 try {
10743 mService.setUserRestriction(admin, key, false, mParentInstance);
10744 } catch (RemoteException e) {
10745 throw e.rethrowFromSystemServer();
10746 }
10747 }
10748 }
10749
10750 /**
10751 * Called by a profile or device owner to get user restrictions set with
10752 * {@link #addUserRestriction(ComponentName, String)}.
10753 * <p>
10754 * The target user may have more restrictions set by the system or other device owner / profile
10755 * owner. To get all the user restrictions currently set, use
10756 * {@link UserManager#getUserRestrictions()}.
10757 * <p>
10758 * The profile owner of an organization-owned managed profile may invoke this method on
10759 * the {@link DevicePolicyManager} instance it obtained from
10760 * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions
10761 * it previously set with {@link #addUserRestriction(ComponentName, String)}.
10762 *
10763 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10764 * @return a {@link Bundle} whose keys are the user restrictions, and the values a
10765 * {@code boolean} indicating whether the restriction is set.
10766 * @throws SecurityException if {@code admin} is not a device or profile owner.
10767 */
10768 public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
10769 Bundle ret = null;
10770 if (mService != null) {
10771 try {
10772 ret = mService.getUserRestrictions(admin, mParentInstance);
10773 } catch (RemoteException e) {
10774 throw e.rethrowFromSystemServer();
10775 }
10776 }
10777 return ret == null ? new Bundle() : ret;
10778 }
10779
10780 /**
10781 * Called by any app to display a support dialog when a feature was disabled by an admin.
10782 * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
10783 * display the dialog. It will tell the user that the feature indicated by {@code restriction}
10784 * was disabled by an admin, and include a link for more information. The default content of
10785 * the dialog can be changed by the restricting admin via
10786 * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
10787 * set (i.e. the feature is available), then the return value will be {@code null}.
10788 * @param restriction Indicates for which feature the dialog should be displayed. Can be a
10789 * user restriction from {@link UserManager}, e.g.
10790 * {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
10791 * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
10792 * @return Intent An intent to be used to start the dialog-activity if the restriction is
10793 * set by an admin, or null if the restriction does not exist or no admin set it.
10794 */
10795 public Intent createAdminSupportIntent(@NonNull String restriction) {
10796 throwIfParentInstance("createAdminSupportIntent");
10797 if (mService != null) {
10798 try {
10799 return mService.createAdminSupportIntent(restriction);
10800 } catch (RemoteException e) {
10801 throw e.rethrowFromSystemServer();
10802 }
10803 }
10804 return null;
10805 }
10806
10807 /**
10808 * @param userId The user for whom to retrieve information.
10809 * @param restriction The restriction enforced by admin. It could be any user restriction or
10810 * policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
10811 * {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
10812 * @return Details of admin and user which enforced the restriction for the userId. If
10813 * restriction is null, profile owner for the user or device owner info is returned.
10814 * @hide
10815 */
10816 public @Nullable Bundle getEnforcingAdminAndUserDetails(int userId,
10817 @Nullable String restriction) {
10818 if (mService != null) {
10819 try {
10820 return mService.getEnforcingAdminAndUserDetails(userId, restriction);
10821 } catch (RemoteException e) {
10822 throw e.rethrowFromSystemServer();
10823 }
10824 }
10825 return null;
10826 }
10827
10828 /**
10829 * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
10830 * actual package file remain. This function can be called by a device owner, profile owner, or
10831 * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
10832 * {@link #setDelegatedScopes}.
10833 * <p>
10834 * This method can be called on the {@link DevicePolicyManager} instance, returned by
10835 * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
10836 * of an organization-owned managed profile and the package must be a system package. If called
10837 * on the parent instance, then the package is hidden or unhidden in the personal profile.
10838 *
10839 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10840 * {@code null} if the caller is a package access delegate.
10841 * @param packageName The name of the package to hide or unhide.
10842 * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
10843 * unhidden.
10844 * @return boolean Whether the hidden setting of the package was successfully updated.
10845 * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
10846 * the parent profile and the {@code admin} is not a profile owner of an
10847 * organization-owned managed profile.
10848 * @throws IllegalArgumentException if called on the parent profile and the package provided
10849 * is not a system package.
10850 * @see #setDelegatedScopes
10851 * @see #DELEGATION_PACKAGE_ACCESS
10852 */
10853 public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
10854 boolean hidden) {
10855 if (mService != null) {
10856 try {
10857 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
10858 hidden, mParentInstance);
10859 } catch (RemoteException e) {
10860 throw e.rethrowFromSystemServer();
10861 }
10862 }
10863 return false;
10864 }
10865
10866 /**
10867 * Determine if a package is hidden. This function can be called by a device owner, profile
10868 * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
10869 * {@link #setDelegatedScopes}.
10870 * <p>
10871 * This method can be called on the {@link DevicePolicyManager} instance, returned by
10872 * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
10873 * of an organization-owned managed profile and the package must be a system package. If called
10874 * on the parent instance, this will determine whether the package is hidden or unhidden in the
10875 * personal profile.
10876 *
10877 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10878 * {@code null} if the caller is a package access delegate.
10879 * @param packageName The name of the package to retrieve the hidden status of.
10880 * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
10881 * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
10882 * the parent profile and the {@code admin} is not a profile owner of an
10883 * organization-owned managed profile.
10884 * @throws IllegalArgumentException if called on the parent profile and the package provided
10885 * is not a system package.
10886 * @see #setDelegatedScopes
10887 * @see #DELEGATION_PACKAGE_ACCESS
10888 */
10889 public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
10890 if (mService != null) {
10891 try {
10892 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName,
10893 mParentInstance);
10894 } catch (RemoteException e) {
10895 throw e.rethrowFromSystemServer();
10896 }
10897 }
10898 return false;
10899 }
10900
10901 /**
10902 * Re-enable a system app that was disabled by default when the user was initialized. This
10903 * function can be called by a device owner, profile owner, or by a delegate given the
10904 * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
10905 *
10906 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10907 * {@code null} if the caller is an enable system app delegate.
10908 * @param packageName The package to be re-enabled in the calling profile.
10909 * @throws SecurityException if {@code admin} is not a device or profile owner.
10910 * @see #setDelegatedScopes
10911 * @see #DELEGATION_PACKAGE_ACCESS
10912 */
10913 public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
10914 throwIfParentInstance("enableSystemApp");
10915 if (mService != null) {
10916 try {
10917 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
10918 } catch (RemoteException e) {
10919 throw e.rethrowFromSystemServer();
10920 }
10921 }
10922 }
10923
10924 /**
10925 * Re-enable system apps by intent that were disabled by default when the user was initialized.
10926 * This function can be called by a device owner, profile owner, or by a delegate given the
10927 * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
10928 *
10929 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10930 * {@code null} if the caller is an enable system app delegate.
10931 * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
10932 * intent will be re-enabled in the calling profile.
10933 * @return int The number of activities that matched the intent and were installed.
10934 * @throws SecurityException if {@code admin} is not a device or profile owner.
10935 * @see #setDelegatedScopes
10936 * @see #DELEGATION_PACKAGE_ACCESS
10937 */
10938 public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
10939 throwIfParentInstance("enableSystemApp");
10940 if (mService != null) {
10941 try {
10942 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
10943 } catch (RemoteException e) {
10944 throw e.rethrowFromSystemServer();
10945 }
10946 }
10947 return 0;
10948 }
10949
10950 /**
10951 * Install an existing package that has been installed in another user, or has been kept after
10952 * removal via {@link #setKeepUninstalledPackages}.
10953 * This function can be called by a device owner, profile owner or a delegate given
10954 * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
10955 * When called in a secondary user or managed profile, the user/profile must be affiliated with
10956 * the device. See {@link #isAffiliatedUser}.
10957 *
10958 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10959 * @param packageName The package to be installed in the calling profile.
10960 * @return {@code true} if the app is installed; {@code false} otherwise.
10961 * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
10962 * an affiliated user or profile.
10963 * @see #setKeepUninstalledPackages
10964 * @see #setDelegatedScopes
10965 * @see #isAffiliatedUser
10966 * @see #DELEGATION_PACKAGE_ACCESS
10967 */
10968 public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
10969 throwIfParentInstance("installExistingPackage");
10970 if (mService != null) {
10971 try {
10972 return mService.installExistingPackage(admin, mContext.getPackageName(),
10973 packageName);
10974 } catch (RemoteException e) {
10975 throw e.rethrowFromSystemServer();
10976 }
10977 }
10978 return false;
10979 }
10980
10981 /**
10982 * Called by a device owner or profile owner to disable account management for a specific type
10983 * of account.
10984 * <p>
10985 * The calling device admin must be a device owner or profile owner. If it is not, a security
10986 * exception will be thrown.
10987 * <p>
10988 * When account management is disabled for an account type, adding or removing an account of
10989 * that type will not be possible.
10990 * <p>
10991 * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
10992 * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
10993 * management for a specific type is disabled.
10994 * <p>
10995 * This method may be called on the {@code DevicePolicyManager} instance returned from
10996 * {@link #getParentProfileInstance(ComponentName)} by the profile owner on an
10997 * organization-owned device, to restrict accounts that may not be managed on the primary
10998 * profile.
10999 *
11000 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11001 * @param accountType For which account management is disabled or enabled.
11002 * @param disabled The boolean indicating that account management will be disabled (true) or
11003 * enabled (false).
11004 * @throws SecurityException if {@code admin} is not a device or profile owner.
11005 */
11006 public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
11007 boolean disabled) {
11008 if (mService != null) {
11009 try {
11010 mService.setAccountManagementDisabled(admin, accountType, disabled,
11011 mParentInstance);
11012 } catch (RemoteException e) {
11013 throw e.rethrowFromSystemServer();
11014 }
11015 }
11016 }
11017
11018 /**
11019 * Gets the array of accounts for which account management is disabled by the profile owner
11020 * or device owner.
11021 *
11022 * <p> Account management can be disabled/enabled by calling
11023 * {@link #setAccountManagementDisabled}.
11024 * <p>
11025 * This method may be called on the {@code DevicePolicyManager} instance returned from
11026 * {@link #getParentProfileInstance(ComponentName)}. Note that only a profile owner on
11027 * an organization-owned device can affect account types on the parent profile instance.
11028 *
11029 * @return a list of account types for which account management has been disabled.
11030 *
11031 * @see #setAccountManagementDisabled
11032 */
11033 public @Nullable String[] getAccountTypesWithManagementDisabled() {
11034 return getAccountTypesWithManagementDisabledAsUser(myUserId(), mParentInstance);
11035 }
11036
11037 /**
11038 * @see #getAccountTypesWithManagementDisabled()
11039 * Note that calling this method on the parent profile instance will return the same
11040 * value as calling it on the main {@code DevicePolicyManager} instance.
11041 * @hide
11042 */
11043 public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
11044 return getAccountTypesWithManagementDisabledAsUser(userId, false);
11045 }
11046
11047 /**
11048 * @see #getAccountTypesWithManagementDisabled()
11049 * @hide
11050 */
11051 public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(
11052 int userId, boolean parentInstance) {
11053 if (mService != null) {
11054 try {
11055 return mService.getAccountTypesWithManagementDisabledAsUser(userId, parentInstance);
11056 } catch (RemoteException e) {
11057 throw e.rethrowFromSystemServer();
11058 }
11059 }
11060
11061 return null;
11062 }
11063
11064 /**
11065 * Called by device owner or profile owner to set whether a secondary lockscreen needs to be
11066 * shown.
11067 *
11068 * <p>The secondary lockscreen will by displayed after the primary keyguard security screen
11069 * requirements are met. To provide the lockscreen content the DO/PO will need to provide a
11070 * service handling the {@link #ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE} intent action,
11071 * extending the {@link DevicePolicyKeyguardService} class.
11072 *
11073 * <p>Relevant interactions on the secondary lockscreen should be communicated back to the
11074 * keyguard via {@link IKeyguardCallback}, such as when the screen is ready to be dismissed.
11075 *
11076 * <p>This API, and associated APIs, can only be called by the default supervision app when it
11077 * is set as the device owner or profile owner.
11078 *
11079 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11080 * @param enabled Whether or not the lockscreen needs to be shown.
11081 * @throws SecurityException if {@code admin} is not a device or profile owner.
11082 * @see #isSecondaryLockscreenEnabled
11083 * @hide
11084 **/
11085 @SystemApi
11086 public void setSecondaryLockscreenEnabled(@NonNull ComponentName admin, boolean enabled) {
11087 throwIfParentInstance("setSecondaryLockscreenEnabled");
11088 if (mService != null) {
11089 try {
11090 mService.setSecondaryLockscreenEnabled(admin, enabled);
11091 } catch (RemoteException e) {
11092 throw e.rethrowFromSystemServer();
11093 }
11094 }
11095 }
11096
11097 /**
11098 * Returns whether the secondary lock screen needs to be shown.
11099 * @see #setSecondaryLockscreenEnabled
11100 * @hide
11101 */
11102 @SystemApi
11103 public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
11104 throwIfParentInstance("isSecondaryLockscreenEnabled");
11105 if (mService != null) {
11106 try {
11107 return mService.isSecondaryLockscreenEnabled(userHandle);
11108 } catch (RemoteException e) {
11109 throw e.rethrowFromSystemServer();
11110 }
11111 }
11112 return false;
11113 }
11114
11115 /**
11116 * Sets which packages may enter lock task mode.
11117 * <p>
11118 * Any packages that share uid with an allowed package will also be allowed to activate lock
11119 * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
11120 * package list results in locked tasks belonging to those packages to be finished.
11121 * <p>
11122 * This function can only be called by the device owner, a profile owner of an affiliated user
11123 * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
11124 * Any package set via this method will be cleared if the user becomes unaffiliated.
11125 *
11126 * @param packages The list of packages allowed to enter lock task mode
11127 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11128 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
11129 * affiliated user or profile, or the profile owner when no device owner is set.
11130 * @see #isAffiliatedUser
11131 * @see Activity#startLockTask()
11132 * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
11133 * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
11134 * @see UserManager#DISALLOW_CREATE_WINDOWS
11135 */
11136 public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
11137 throws SecurityException {
11138 throwIfParentInstance("setLockTaskPackages");
11139 if (mService != null) {
11140 try {
11141 mService.setLockTaskPackages(admin, packages);
11142 } catch (RemoteException e) {
11143 throw e.rethrowFromSystemServer();
11144 }
11145 }
11146 }
11147
11148 /**
11149 * Returns the list of packages allowed to start the lock task mode.
11150 *
11151 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
11152 * affiliated user or profile, or the profile owner when no device owner is set.
11153 * @see #isAffiliatedUser
11154 * @see #setLockTaskPackages
11155 */
11156 public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
11157 throwIfParentInstance("getLockTaskPackages");
11158 if (mService != null) {
11159 try {
11160 return mService.getLockTaskPackages(admin);
11161 } catch (RemoteException e) {
11162 throw e.rethrowFromSystemServer();
11163 }
11164 }
11165 return new String[0];
11166 }
11167
11168 /**
11169 * This function lets the caller know whether the given component is allowed to start the
11170 * lock task mode.
11171 * @param pkg The package to check
11172 */
11173 public boolean isLockTaskPermitted(String pkg) {
11174 throwIfParentInstance("isLockTaskPermitted");
11175 if (mService != null) {
11176 try {
11177 return mService.isLockTaskPermitted(pkg);
11178 } catch (RemoteException e) {
11179 throw e.rethrowFromSystemServer();
11180 }
11181 }
11182 return false;
11183 }
11184
11185 /**
11186 * Sets which system features are enabled when the device runs in lock task mode. This method
11187 * doesn't affect the features when lock task mode is inactive. Any system features not included
11188 * in {@code flags} are implicitly disabled when calling this method. By default, only
11189 * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To
11190 * disable the global actions dialog, call this method omitting
11191 * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
11192 *
11193 * <p>This method can only be called by the device owner, a profile owner of an affiliated
11194 * user or profile, or the profile owner when no device owner is set. See
11195 * {@link #isAffiliatedUser}.
11196 * Any features set using this method are cleared if the user becomes unaffiliated.
11197 *
11198 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11199 * @param flags The system features enabled during lock task mode.
11200 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
11201 * affiliated user or profile, or the profile owner when no device owner is set.
11202 * @see #isAffiliatedUser
11203 **/
11204 public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
11205 throwIfParentInstance("setLockTaskFeatures");
11206 if (mService != null) {
11207 try {
11208 mService.setLockTaskFeatures(admin, flags);
11209 } catch (RemoteException e) {
11210 throw e.rethrowFromSystemServer();
11211 }
11212 }
11213 }
11214
11215 /**
11216 * Gets which system features are enabled for LockTask mode.
11217 *
11218 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11219 * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
11220 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
11221 * affiliated user or profile, or the profile owner when no device owner is set.
11222 * @see #isAffiliatedUser
11223 * @see #setLockTaskFeatures
11224 */
11225 public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
11226 throwIfParentInstance("getLockTaskFeatures");
11227 if (mService != null) {
11228 try {
11229 return mService.getLockTaskFeatures(admin);
11230 } catch (RemoteException e) {
11231 throw e.rethrowFromSystemServer();
11232 }
11233 }
11234 return 0;
11235 }
11236
11237 /**
11238 * Sets whether preferential network service is enabled.
11239 * For example, an organization can have a deal/agreement with a carrier that all of
11240 * the work data from its employees’ devices will be sent via a network service dedicated
11241 * for enterprise use.
11242 *
11243 * An example of a supported preferential network service is the Enterprise
11244 * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
11245 * configure enterprise APN to set up data call for the preferential network service.
11246 * These APNs can be added using {@link #addOverrideApn}.
11247 *
11248 * By default, preferential network service is disabled on the work profile and
11249 * fully managed devices, on supported carriers and devices.
11250 * Admins can explicitly enable it with this API.
11251 *
11252 * <p> This method enables preferential network service with a default configuration.
11253 * To fine-tune the configuration, use {@link #setPreferentialNetworkServiceConfigs) instead.
11254 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
11255 * this method can be called by the profile owner of a managed profile.
11256 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
11257 * This method can be called by the profile owner of a managed profile
11258 * or device owner.
11259 *
11260 * @param enabled whether preferential network service should be enabled.
11261 * @throws SecurityException if the caller is not the profile owner or device owner.
11262 **/
11263 public void setPreferentialNetworkServiceEnabled(boolean enabled) {
11264 throwIfParentInstance("setPreferentialNetworkServiceEnabled");
11265 PreferentialNetworkServiceConfig.Builder configBuilder =
11266 new PreferentialNetworkServiceConfig.Builder();
11267 configBuilder.setEnabled(enabled);
11268 if (enabled) {
11269 configBuilder.setNetworkId(NET_ENTERPRISE_ID_1);
11270 }
11271 setPreferentialNetworkServiceConfigs(List.of(configBuilder.build()));
11272 }
11273
11274 /**
11275 * Indicates whether preferential network service is enabled.
11276 *
11277 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
11278 * This method can be called by the profile owner of a managed profile.
11279 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
11280 * This method can be called by the profile owner of a managed profile
11281 * or device owner.
11282 *
11283 * @return whether preferential network service is enabled.
11284 * @throws SecurityException if the caller is not the profile owner or device owner.
11285 */
11286 public boolean isPreferentialNetworkServiceEnabled() {
11287 throwIfParentInstance("isPreferentialNetworkServiceEnabled");
11288 return getPreferentialNetworkServiceConfigs().stream().anyMatch(c -> c.isEnabled());
11289 }
11290
11291 /**
11292 * Sets preferential network configurations.
11293 * {@see PreferentialNetworkServiceConfig}
11294 *
11295 * An example of a supported preferential network service is the Enterprise
11296 * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
11297 * configure enterprise APN to set up data call for the preferential network service.
11298 * These APNs can be added using {@link #addOverrideApn}.
11299 *
11300 * By default, preferential network service is disabled on the work profile and fully managed
11301 * devices, on supported carriers and devices. Admins can explicitly enable it with this API.
11302 * If admin wants to have multiple enterprise slices,
11303 * it can be configured by passing list of {@link PreferentialNetworkServiceConfig} objects.
11304 *
11305 * @param preferentialNetworkServiceConfigs list of preferential network configurations.
11306 * @throws SecurityException if the caller is not the profile owner or device owner.
11307 **/
11308 public void setPreferentialNetworkServiceConfigs(
11309 @NonNull List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
11310 throwIfParentInstance("setPreferentialNetworkServiceConfigs");
11311 if (mService == null) {
11312 return;
11313 }
11314 try {
11315 mService.setPreferentialNetworkServiceConfigs(preferentialNetworkServiceConfigs);
11316 } catch (RemoteException e) {
11317 throw e.rethrowFromSystemServer();
11318 }
11319 }
11320
11321 /**
11322 * Get preferential network configuration
11323 * {@see PreferentialNetworkServiceConfig}
11324 *
11325 * @return preferential network configuration.
11326 * @throws SecurityException if the caller is not the profile owner or device owner.
11327 */
11328 public @NonNull List<PreferentialNetworkServiceConfig> getPreferentialNetworkServiceConfigs() {
11329 throwIfParentInstance("getPreferentialNetworkServiceConfigs");
11330 if (mService == null) {
11331 return List.of(PreferentialNetworkServiceConfig.DEFAULT);
11332 }
11333 try {
11334 return mService.getPreferentialNetworkServiceConfigs();
11335 } catch (RemoteException e) {
11336 throw e.rethrowFromSystemServer();
11337 }
11338 }
11339
11340 /**
11341 * This method is mostly deprecated.
11342 * Most of the settings that still have an effect have dedicated setter methods or user
11343 * restrictions. See individual settings for details.
11344 * <p>
11345 * Called by device owner to update {@link android.provider.Settings.Global} settings.
11346 * Validation that the value of the setting is in the correct form for the setting type should
11347 * be performed by the caller.
11348 * <p>
11349 * The settings that can be updated with this method are:
11350 * <ul>
11351 * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use
11352 * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling
11353 * debugging features and this setting to turn adb on.</li>
11354 * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
11355 * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
11356 * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
11357 * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
11358 * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
11359 * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
11360 * </ul>
11361 * <p>
11362 * The following settings used to be supported, but can be controlled in other ways:
11363 * <ul>
11364 * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
11365 * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
11366 * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
11367 * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
11368 * instead.</li>
11369 * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
11370 * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
11371 * </ul>
11372 * <p>
11373 * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
11374 * <ul>
11375 * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
11376 * {@link android.bluetooth.BluetoothAdapter#enable()} and
11377 * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
11378 * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
11379 * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
11380 * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
11381 * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
11382 * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
11383 * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
11384 * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li>
11385 * </ul>
11386 *
11387 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11388 * @param setting The name of the setting to update.
11389 * @param value The value to update the setting to.
11390 * @throws SecurityException if {@code admin} is not a device owner.
11391 */
11392 public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
11393 throwIfParentInstance("setGlobalSetting");
11394 if (mService != null) {
11395 try {
11396 mService.setGlobalSetting(admin, setting, value);
11397 } catch (RemoteException e) {
11398 throw e.rethrowFromSystemServer();
11399 }
11400 }
11401 }
11402
11403 /** @hide */
11404 @StringDef({
11405 Settings.System.SCREEN_BRIGHTNESS_MODE,
11406 Settings.System.SCREEN_BRIGHTNESS,
11407 Settings.System.SCREEN_BRIGHTNESS_FLOAT,
11408 Settings.System.SCREEN_OFF_TIMEOUT
11409 })
11410 @Retention(RetentionPolicy.SOURCE)
11411 public @interface SystemSettingsWhitelist {}
11412
11413 /**
11414 * Called by a device or profile owner to update {@link android.provider.Settings.System}
11415 * settings. Validation that the value of the setting is in the correct form for the setting
11416 * type should be performed by the caller.
11417 * <p>
11418 * The settings that can be updated by a device owner or profile owner of secondary user with
11419 * this method are:
11420 * <ul>
11421 * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
11422 * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
11423 * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
11424 * </ul>
11425 * <p>
11426 *
11427 * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
11428 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11429 * @param setting The name of the setting to update.
11430 * @param value The value to update the setting to.
11431 * @throws SecurityException if {@code admin} is not a device or profile owner.
11432 */
11433 public void setSystemSetting(@NonNull ComponentName admin,
11434 @NonNull @SystemSettingsWhitelist String setting, String value) {
11435 throwIfParentInstance("setSystemSetting");
11436 if (mService != null) {
11437 try {
11438 mService.setSystemSetting(admin, setting, value);
11439 } catch (RemoteException e) {
11440 throw e.rethrowFromSystemServer();
11441 }
11442 }
11443 }
11444
11445 /**
11446 * Called by a device owner or a profile owner of an organization-owned managed profile to
11447 * control whether the user can change networks configured by the admin. When this lockdown is
11448 * enabled, the user can still configure and connect to other Wi-Fi networks, or use other Wi-Fi
11449 * capabilities such as tethering.
11450 * <p>
11451 * WiFi network configuration lockdown is controlled by a global settings
11452 * {@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN} and calling
11453 * this API effectively modifies the global settings. Previously device owners can also
11454 * control this directly via {@link #setGlobalSetting} but they are recommended to switch
11455 * to this API.
11456 *
11457 * @param admin admin Which {@link DeviceAdminReceiver} this request is associated
11458 * with.
11459 * @param lockdown Whether the admin configured networks should be unmodifiable by the
11460 * user.
11461 * @throws SecurityException if caller is not a device owner or a profile owner of an
11462 * organization-owned managed profile.
11463 */
11464 public void setConfiguredNetworksLockdownState(@NonNull ComponentName admin, boolean lockdown) {
11465 throwIfParentInstance("setConfiguredNetworksLockdownState");
11466 if (mService != null) {
11467 try {
11468 mService.setConfiguredNetworksLockdownState(admin, lockdown);
11469 } catch (RemoteException e) {
11470 throw e.rethrowFromSystemServer();
11471 }
11472 }
11473 }
11474
11475 /**
11476 * Called by a device owner or a profile owner of an organization-owned managed profile to
11477 * determine whether the user is prevented from modifying networks configured by the admin.
11478 *
11479 * @param admin admin Which {@link DeviceAdminReceiver} this request is associated
11480 * with.
11481 * @throws SecurityException if caller is not a device owner or a profile owner of an
11482 * organization-owned managed profile.
11483 */
11484 public boolean hasLockdownAdminConfiguredNetworks(@NonNull ComponentName admin) {
11485 throwIfParentInstance("hasLockdownAdminConfiguredNetworks");
11486 if (mService != null) {
11487 try {
11488 return mService.hasLockdownAdminConfiguredNetworks(admin);
11489 } catch (RemoteException e) {
11490 throw e.rethrowFromSystemServer();
11491 }
11492 }
11493 return false;
11494 }
11495
11496 /**
11497 * Called by a device owner or a profile owner of an organization-owned managed
11498 * profile to set the system wall clock time. This only takes effect if called when
11499 * {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false}
11500 * will be returned.
11501 *
11502 * @param admin Which {@link DeviceAdminReceiver} this request is associated with
11503 * @param millis time in milliseconds since the Epoch
11504 * @return {@code true} if set time succeeded, {@code false} otherwise.
11505 * @throws SecurityException if {@code admin} is not a device owner or a profile owner
11506 * of an organization-owned managed profile.
11507 */
11508 public boolean setTime(@NonNull ComponentName admin, long millis) {
11509 throwIfParentInstance("setTime");
11510 if (mService != null) {
11511 try {
11512 return mService.setTime(admin, millis);
11513 } catch (RemoteException e) {
11514 throw e.rethrowFromSystemServer();
11515 }
11516 }
11517 return false;
11518 }
11519
11520 /**
11521 * Called by a device owner or a profile owner of an organization-owned managed
11522 * profile to set the system's persistent default time zone. This only takes
11523 * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE}
11524 * is 0, otherwise {@code false} will be returned.
11525 *
11526 * @see android.app.AlarmManager#setTimeZone(String)
11527 * @param admin Which {@link DeviceAdminReceiver} this request is associated with
11528 * @param timeZone one of the Olson ids from the list returned by
11529 * {@link java.util.TimeZone#getAvailableIDs}
11530 * @return {@code true} if set timezone succeeded, {@code false} otherwise.
11531 * @throws SecurityException if {@code admin} is not a device owner or a profile owner
11532 * of an organization-owned managed profile.
11533 */
11534 public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
11535 throwIfParentInstance("setTimeZone");
11536 if (mService != null) {
11537 try {
11538 return mService.setTimeZone(admin, timeZone);
11539 } catch (RemoteException e) {
11540 throw e.rethrowFromSystemServer();
11541 }
11542 }
11543 return false;
11544 }
11545
11546 /**
11547 * Called by device owners to set the user's global location setting.
11548 *
11549 *
11550 * @param admin Which {@link DeviceAdminReceiver} this request is associated with
11551 * @param locationEnabled whether location should be enabled or disabled. <b>Note: </b> on
11552 * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, calls to
11553 * disable will be ignored.
11554 * @throws SecurityException if {@code admin} is not a device owner.
11555 */
11556 public void setLocationEnabled(@NonNull ComponentName admin, boolean locationEnabled) {
11557 throwIfParentInstance("setLocationEnabled");
11558 if (mService != null) {
11559 try {
11560 mService.setLocationEnabled(admin, locationEnabled);
11561 } catch (RemoteException e) {
11562 throw e.rethrowFromSystemServer();
11563 }
11564 }
11565 }
11566
11567 /**
11568 * This method is mostly deprecated.
11569 * Most of the settings that still have an effect have dedicated setter methods
11570 * (e.g. {@link #setLocationEnabled}) or user restrictions.
11571 * <p>
11572 *
11573 * Called by profile or device owners to update {@link android.provider.Settings.Secure}
11574 * settings. Validation that the value of the setting is in the correct form for the setting
11575 * type should be performed by the caller.
11576 * <p>
11577 * The settings that can be updated by a profile or device owner with this method are:
11578 * <ul>
11579 * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
11580 * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
11581 * </ul>
11582 * <p>
11583 * A device owner can additionally update the following settings:
11584 * <ul>
11585 * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li>
11586 * </ul>
11587 *
11588 * <strong>Note: Starting from Android O, apps should no longer call this method with the
11589 * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
11590 * deprecated. Instead, device owners or profile owners should use the restriction
11591 * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
11592 * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
11593 * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
11594 * an {@link UnsupportedOperationException} is thrown.
11595 *
11596 * Starting from Android Q, the device and profile owner can also call
11597 * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
11598 * all users.
11599 * </strong>
11600 *
11601 * <strong>Note: Starting from Android R, apps should no longer call this method with the
11602 * setting {@link android.provider.Settings.Secure#LOCATION_MODE}, which is deprecated. Instead,
11603 * device owners should call {@link #setLocationEnabled(ComponentName, boolean)}. This will be
11604 * enforced for all apps targeting Android R or above.
11605 * </strong>
11606 *
11607 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11608 * @param setting The name of the setting to update.
11609 * @param value The value to update the setting to.
11610 * @throws SecurityException if {@code admin} is not a device or profile owner.
11611 */
11612 public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
11613 throwIfParentInstance("setSecureSetting");
11614
11615 if (mService != null) {
11616 try {
11617 mService.setSecureSetting(admin, setting, value);
11618 } catch (RemoteException e) {
11619 throw e.rethrowFromSystemServer();
11620 }
11621 }
11622 }
11623
11624 /**
11625 * Designates a specific service component as the provider for making permission requests of a
11626 * local or remote administrator of the user.
11627 * <p/>
11628 * Only a device owner or profile owner can designate the restrictions provider.
11629 *
11630 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11631 * @param provider The component name of the service that implements
11632 * {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
11633 * provider previously assigned.
11634 * @throws SecurityException if {@code admin} is not a device or profile owner.
11635 */
11636 public void setRestrictionsProvider(@NonNull ComponentName admin,
11637 @Nullable ComponentName provider) {
11638 throwIfParentInstance("setRestrictionsProvider");
11639 if (mService != null) {
11640 try {
11641 mService.setRestrictionsProvider(admin, provider);
11642 } catch (RemoteException re) {
11643 throw re.rethrowFromSystemServer();
11644 }
11645 }
11646 }
11647
11648 /**
11649 * Called by profile or device owners to set the global volume mute on or off.
11650 * This has no effect when set on a managed profile.
11651 *
11652 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11653 * @param on {@code true} to mute global volume, {@code false} to turn mute off.
11654 * @throws SecurityException if {@code admin} is not a device or profile owner.
11655 */
11656 public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
11657 throwIfParentInstance("setMasterVolumeMuted");
11658 if (mService != null) {
11659 try {
11660 mService.setMasterVolumeMuted(admin, on);
11661 } catch (RemoteException re) {
11662 throw re.rethrowFromSystemServer();
11663 }
11664 }
11665 }
11666
11667 /**
11668 * Called by profile or device owners to check whether the global volume mute is on or off.
11669 *
11670 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11671 * @return {@code true} if global volume is muted, {@code false} if it's not.
11672 * @throws SecurityException if {@code admin} is not a device or profile owner.
11673 */
11674 public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
11675 throwIfParentInstance("isMasterVolumeMuted");
11676 if (mService != null) {
11677 try {
11678 return mService.isMasterVolumeMuted(admin);
11679 } catch (RemoteException re) {
11680 throw re.rethrowFromSystemServer();
11681 }
11682 }
11683 return false;
11684 }
11685
11686 /**
11687 * Change whether a user can uninstall a package. This function can be called by a device owner,
11688 * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
11689 * {@link #setDelegatedScopes}.
11690 *
11691 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11692 * {@code null} if the caller is a block uninstall delegate.
11693 * @param packageName package to change.
11694 * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
11695 * @throws SecurityException if {@code admin} is not a device or profile owner.
11696 * @see #setDelegatedScopes
11697 * @see #DELEGATION_BLOCK_UNINSTALL
11698 */
11699 public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
11700 boolean uninstallBlocked) {
11701 throwIfParentInstance("setUninstallBlocked");
11702 if (mService != null) {
11703 try {
11704 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
11705 uninstallBlocked);
11706 } catch (RemoteException re) {
11707 throw re.rethrowFromSystemServer();
11708 }
11709 }
11710 }
11711
11712 /**
11713 * Check whether the user has been blocked by device policy from uninstalling a package.
11714 * Requires the caller to be the profile owner if checking a specific admin's policy.
11715 * <p>
11716 * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
11717 * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
11718 * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
11719 * will cause a NullPointerException to be raised.
11720 * <p>
11721 * <strong>Note:</strong> If your app targets Android 11 (API level 30) or higher,
11722 * this method returns a filtered result. Learn more about how to
11723 * <a href="/training/basics/intents/package-visibility">manage package visibility</a>.
11724 *
11725 * @param admin The name of the admin component whose blocking policy will be checked, or
11726 * {@code null} to check whether any admin has blocked the uninstallation.
11727 * @param packageName package to check.
11728 * @return true if uninstallation is blocked and the given package is visible to you, false
11729 * otherwise if uninstallation isn't blocked or the given package isn't visible to you.
11730 * @throws SecurityException if {@code admin} is not a device or profile owner.
11731 */
11732 public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
11733 throwIfParentInstance("isUninstallBlocked");
11734 if (mService != null) {
11735 try {
11736 return mService.isUninstallBlocked(admin, packageName);
11737 } catch (RemoteException re) {
11738 throw re.rethrowFromSystemServer();
11739 }
11740 }
11741 return false;
11742 }
11743
11744 /**
11745 * Called by the profile owner of a managed profile to enable widget providers from a given
11746 * package to be available in the parent profile. As a result the user will be able to add
11747 * widgets from the allowlisted package running under the profile to a widget host which runs
11748 * under the parent profile, for example the home screen. Note that a package may have zero or
11749 * more provider components, where each component provides a different widget type.
11750 * <p>
11751 * <strong>Note:</strong> By default no widget provider package is allowlisted.
11752 *
11753 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11754 * @param packageName The package from which widget providers are allowlisted.
11755 * @return Whether the package was added.
11756 * @throws SecurityException if {@code admin} is not a profile owner.
11757 * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
11758 * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
11759 */
11760 public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
11761 throwIfParentInstance("addCrossProfileWidgetProvider");
11762 if (mService != null) {
11763 try {
11764 return mService.addCrossProfileWidgetProvider(admin, packageName);
11765 } catch (RemoteException re) {
11766 throw re.rethrowFromSystemServer();
11767 }
11768 }
11769 return false;
11770 }
11771
11772 /**
11773 * Called by the profile owner of a managed profile to disable widget providers from a given
11774 * package to be available in the parent profile. For this method to take effect the package
11775 * should have been added via
11776 * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
11777 * <p>
11778 * <strong>Note:</strong> By default no widget provider package is allowlisted.
11779 *
11780 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11781 * @param packageName The package from which widget providers are no longer allowlisted.
11782 * @return Whether the package was removed.
11783 * @throws SecurityException if {@code admin} is not a profile owner.
11784 * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
11785 * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
11786 */
11787 public boolean removeCrossProfileWidgetProvider(
11788 @NonNull ComponentName admin, String packageName) {
11789 throwIfParentInstance("removeCrossProfileWidgetProvider");
11790 if (mService != null) {
11791 try {
11792 return mService.removeCrossProfileWidgetProvider(admin, packageName);
11793 } catch (RemoteException re) {
11794 throw re.rethrowFromSystemServer();
11795 }
11796 }
11797 return false;
11798 }
11799
11800 /**
11801 * Called by the profile owner of a managed profile to query providers from which packages are
11802 * available in the parent profile.
11803 *
11804 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11805 * @return The allowlisted package list.
11806 * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
11807 * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
11808 * @throws SecurityException if {@code admin} is not a profile owner.
11809 */
11810 public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
11811 throwIfParentInstance("getCrossProfileWidgetProviders");
11812 if (mService != null) {
11813 try {
11814 List<String> providers = mService.getCrossProfileWidgetProviders(admin);
11815 if (providers != null) {
11816 return providers;
11817 }
11818 } catch (RemoteException re) {
11819 throw re.rethrowFromSystemServer();
11820 }
11821 }
11822 return Collections.emptyList();
11823 }
11824
11825 /**
11826 * Called by profile or device owners to set the user's photo.
11827 *
11828 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11829 * @param icon the bitmap to set as the photo.
11830 * @throws SecurityException if {@code admin} is not a device or profile owner.
11831 */
11832 public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
11833 throwIfParentInstance("setUserIcon");
11834 try {
11835 mService.setUserIcon(admin, icon);
11836 } catch (RemoteException re) {
11837 throw re.rethrowFromSystemServer();
11838 }
11839 }
11840
11841 /**
11842 * Called by device owners or profile owners of an organization-owned managed profile to to set
11843 * a local system update policy. When a new policy is set,
11844 * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
11845 * <p>
11846 * If the supplied system update policy has freeze periods set but the freeze periods do not
11847 * meet 90-day maximum length or 60-day minimum separation requirement set out in
11848 * {@link SystemUpdatePolicy#setFreezePeriods},
11849 * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
11850 * keeps a record of freeze periods the device experienced previously, and combines them with
11851 * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
11852 * separation constraints. As a result, freeze periods that passed validation during
11853 * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
11854 * the freeze period history. If this is causing issues during development,
11855 * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
11856 *
11857 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
11858 * components in the device owner package can set system update policies and the most
11859 * recent policy takes effect.
11860 * @param policy the new policy, or {@code null} to clear the current policy.
11861 * @throws SecurityException if {@code admin} is not a device owner or a profile owner of an
11862 * organization-owned managed profile.
11863 * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
11864 * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
11865 * meet the requirement.
11866 * @see SystemUpdatePolicy
11867 * @see SystemUpdatePolicy#setFreezePeriods(List)
11868 */
11869 public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
11870 throwIfParentInstance("setSystemUpdatePolicy");
11871 if (mService != null) {
11872 try {
11873 mService.setSystemUpdatePolicy(admin, policy);
11874 } catch (RemoteException re) {
11875 throw re.rethrowFromSystemServer();
11876 }
11877 }
11878 }
11879
11880 /**
11881 * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
11882 *
11883 * @return The current policy object, or {@code null} if no policy is set.
11884 */
11885 public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
11886 throwIfParentInstance("getSystemUpdatePolicy");
11887 if (mService != null) {
11888 try {
11889 return mService.getSystemUpdatePolicy();
11890 } catch (RemoteException re) {
11891 throw re.rethrowFromSystemServer();
11892 }
11893 }
11894 return null;
11895 }
11896
11897 /**
11898 * Reset record of previous system update freeze period the device went through.
11899 * @hide
11900 */
11901 @TestApi
11902 @RequiresPermission(android.Manifest.permission.CLEAR_FREEZE_PERIOD)
11903 public void clearSystemUpdatePolicyFreezePeriodRecord() {
11904 throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
11905 if (mService == null) {
11906 return;
11907 }
11908 try {
11909 mService.clearSystemUpdatePolicyFreezePeriodRecord();
11910 } catch (RemoteException re) {
11911 throw re.rethrowFromSystemServer();
11912 }
11913 }
11914
11915 /**
11916 * Called by a device owner or profile owner of secondary users that is affiliated with the
11917 * device to disable the keyguard altogether.
11918 * <p>
11919 * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
11920 * type. However, this call has no effect if a password, pin or pattern is currently set. If a
11921 * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
11922 * disabled.
11923 *
11924 * <p>
11925 * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
11926 * keyguard if it is currently shown.
11927 *
11928 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11929 * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
11930 * @return {@code false} if attempting to disable the keyguard while a lock password was in
11931 * place. {@code true} otherwise.
11932 * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
11933 * secondary user that is affiliated with the device.
11934 * @see #isAffiliatedUser
11935 * @see #getSecondaryUsers
11936 */
11937 public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
11938 throwIfParentInstance("setKeyguardDisabled");
11939 try {
11940 return mService.setKeyguardDisabled(admin, disabled);
11941 } catch (RemoteException re) {
11942 throw re.rethrowFromSystemServer();
11943 }
11944 }
11945
11946 /**
11947 * Called by device owner or profile owner of secondary users that is affiliated with the
11948 * device to disable the status bar. Disabling the status bar blocks notifications and quick
11949 * settings.
11950 * <p>
11951 * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
11952 * status bar in LockTask mode can be configured with
11953 * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
11954 * LockTask mode will be registered, but will only take effect when the device leaves LockTask
11955 * mode.
11956 *
11957 * <p>This policy does not have any effect while on the lock screen, where the status bar will
11958 * not be disabled. Using LockTask instead of this method is recommended.
11959 *
11960 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11961 * @param disabled {@code true} disables the status bar, {@code false} reenables it.
11962 * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
11963 * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
11964 * secondary user that is affiliated with the device.
11965 * @see #isAffiliatedUser
11966 * @see #getSecondaryUsers
11967 */
11968 public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
11969 throwIfParentInstance("setStatusBarDisabled");
11970 try {
11971 return mService.setStatusBarDisabled(admin, disabled);
11972 } catch (RemoteException re) {
11973 throw re.rethrowFromSystemServer();
11974 }
11975 }
11976
11977 /**
11978 * Called by the system update service to notify device and profile owners of pending system
11979 * updates.
11980 *
11981 * This method should only be used when it is unknown whether the pending system
11982 * update is a security patch. Otherwise, use
11983 * {@link #notifyPendingSystemUpdate(long, boolean)}.
11984 *
11985 * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
11986 * indicating when the current pending update was first available. {@code -1} if no
11987 * update is available.
11988 * @see #notifyPendingSystemUpdate(long, boolean)
11989 * @hide
11990 */
11991 @SystemApi
11992 @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
11993 public void notifyPendingSystemUpdate(long updateReceivedTime) {
11994 throwIfParentInstance("notifyPendingSystemUpdate");
11995 if (mService != null) {
11996 try {
11997 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
11998 } catch (RemoteException re) {
11999 throw re.rethrowFromSystemServer();
12000 }
12001 }
12002 }
12003
12004 /**
12005 * Called by the system update service to notify device and profile owners of pending system
12006 * updates.
12007 *
12008 * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
12009 * when it is known whether the pending system update is a security patch.
12010 *
12011 * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
12012 * indicating when the current pending update was first available. {@code -1} if no
12013 * update is available.
12014 * @param isSecurityPatch {@code true} if this system update is purely a security patch;
12015 * {@code false} if not.
12016 * @see #notifyPendingSystemUpdate(long)
12017 * @hide
12018 */
12019 @SystemApi
12020 @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
12021 public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
12022 throwIfParentInstance("notifyPendingSystemUpdate");
12023 if (mService != null) {
12024 try {
12025 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
12026 isSecurityPatch));
12027 } catch (RemoteException re) {
12028 throw re.rethrowFromSystemServer();
12029 }
12030 }
12031 }
12032
12033 /**
12034 * Called by device or profile owners to get information about a pending system update.
12035 *
12036 * @param admin Which profile or device owner this request is associated with.
12037 * @return Information about a pending system update or {@code null} if no update pending.
12038 * @throws SecurityException if {@code admin} is not a device or profile owner.
12039 * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
12040 */
12041 public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
12042 throwIfParentInstance("getPendingSystemUpdate");
12043 try {
12044 return mService.getPendingSystemUpdate(admin);
12045 } catch (RemoteException re) {
12046 throw re.rethrowFromSystemServer();
12047 }
12048 }
12049
12050 /**
12051 * Set the default response for future runtime permission requests by applications. This
12052 * function can be called by a device owner, profile owner, or by a delegate given the
12053 * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
12054 * The policy can allow for normal operation which prompts the user to grant a permission, or
12055 * can allow automatic granting or denying of runtime permission requests by an application.
12056 * This also applies to new permissions declared by app updates. When a permission is denied or
12057 * granted this way, the effect is equivalent to setting the permission * grant state via
12058 * {@link #setPermissionGrantState}.
12059 * <p/>
12060 * As this policy only acts on runtime permission requests, it only applies to applications
12061 * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
12062 *
12063 * <p>
12064 * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, an auto-grant
12065 * policy will not apply to certain sensors-related permissions on some configurations.
12066 * See {@link #setPermissionGrantState(ComponentName, String, String, int)} for the list of
12067 * permissions affected, and the behavior change for managed profiles and fully-managed
12068 * devices.
12069 *
12070 * @param admin Which profile or device owner this request is associated with.
12071 * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
12072 * {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
12073 * @throws SecurityException if {@code admin} is not a device or profile owner.
12074 * @see #setPermissionGrantState
12075 * @see #setDelegatedScopes
12076 * @see #DELEGATION_PERMISSION_GRANT
12077 */
12078 public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
12079 throwIfParentInstance("setPermissionPolicy");
12080 try {
12081 mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
12082 } catch (RemoteException re) {
12083 throw re.rethrowFromSystemServer();
12084 }
12085 }
12086
12087 /**
12088 * Returns the current runtime permission policy set by the device or profile owner. The
12089 * default is {@link #PERMISSION_POLICY_PROMPT}.
12090 *
12091 * @param admin Which profile or device owner this request is associated with.
12092 * @return the current policy for future permission requests.
12093 */
12094 public int getPermissionPolicy(ComponentName admin) {
12095 throwIfParentInstance("getPermissionPolicy");
12096 try {
12097 return mService.getPermissionPolicy(admin);
12098 } catch (RemoteException re) {
12099 throw re.rethrowFromSystemServer();
12100 }
12101 }
12102
12103 /**
12104 * Sets the grant state of a runtime permission for a specific application. The state can be
12105 * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
12106 * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
12107 * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
12108 * the permission is granted and the user cannot manage it through the UI. This method can only
12109 * be called by a profile owner, device owner, or a delegate given the
12110 * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
12111 * <p/>
12112 * Note that user cannot manage other permissions in the affected group through the UI
12113 * either and their granted state will be kept as the current value. Thus, it's recommended that
12114 * you set the grant state of all the permissions in the affected group.
12115 * <p/>
12116 * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
12117 * the permission. It retains the previous grant, if any.
12118 * <p/>
12119 * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
12120 * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
12121 * &lt; {@link android.os.Build.VERSION_CODES#M}.
12122 * <p/>
12123 * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
12124 * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
12125 * application built with a {@code targetSdkVersion} &lt;
12126 * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
12127 * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
12128 * <p>
12129 * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
12130 * the following, sensors-related, permissions is restricted:
12131 * <ul>
12132 * <li>Manifest.permission.ACCESS_FINE_LOCATION</li>
12133 * <li>Manifest.permission.ACCESS_BACKGROUND_LOCATION</li>
12134 * <li>Manifest.permission.ACCESS_COARSE_LOCATION</li>
12135 * <li>Manifest.permission.CAMERA</li>
12136 * <li>Manifest.permission.RECORD_AUDIO</li>
12137 * <li>Manifest.permission.RECORD_BACKGROUND_AUDIO</li>
12138 * <li>Manifest.permission.ACTIVITY_RECOGNITION</li>
12139 * <li>Manifest.permission.BODY_SENSORS</li>
12140 * </ul>
12141 * <p>
12142 * A profile owner may not grant these permissions (i.e. call this method with any of the
12143 * permissions listed above and {@code grantState} of {@code #PERMISSION_GRANT_STATE_GRANTED}),
12144 * but may deny them.
12145 * <p>
12146 * A device owner, by default, may continue granting these permissions. However, for increased
12147 * user control, the admin may opt out of controlling grants for these permissions by including
12148 * {@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} in the provisioning parameters.
12149 * In that case the device owner's control will be limited do denying these permissions.
12150 * <p>
12151 * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
12152 * the following permissions are restricted for managed profile owners:
12153 * <ul>
12154 * <li>Manifest.permission.READ_SMS</li>
12155 * </ul>
12156 * <p>
12157 * A managed profile owner may not grant these permissions (i.e. call this method with any of
12158 * the permissions listed above and {@code grantState} of
12159 * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
12160 * <p>
12161 * Attempts by the admin to grant these permissions, when the admin is restricted from doing
12162 * so, will be silently ignored (no exception will be thrown).
12163 *
12164 * Control over the following permissions are restricted for managed profile owners:
12165 * <ul>
12166 * <li>Manifest.permission.READ_SMS</li>
12167 * </ul>
12168 * <p>
12169 * A managed profile owner may not grant these permissions (i.e. call this method with any of
12170 * the permissions listed above and {@code grantState} of
12171 * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
12172 *
12173 * @param admin Which profile or device owner this request is associated with.
12174 * @param packageName The application to grant or revoke a permission to.
12175 * @param permission The permission to grant or revoke.
12176 * @param grantState The permission grant state which is one of
12177 * {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
12178 * {@link #PERMISSION_GRANT_STATE_GRANTED},
12179 * @return whether the permission was successfully granted or revoked.
12180 * @throws SecurityException if {@code admin} is not a device or profile owner.
12181 * @see #PERMISSION_GRANT_STATE_DENIED
12182 * @see #PERMISSION_GRANT_STATE_DEFAULT
12183 * @see #PERMISSION_GRANT_STATE_GRANTED
12184 * @see #setDelegatedScopes
12185 * @see #DELEGATION_PERMISSION_GRANT
12186 */
12187 public boolean setPermissionGrantState(@NonNull ComponentName admin,
12188 @NonNull String packageName, @NonNull String permission,
12189 @PermissionGrantState int grantState) {
12190 throwIfParentInstance("setPermissionGrantState");
12191 try {
12192 CompletableFuture<Boolean> result = new CompletableFuture<>();
12193
12194 mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
12195 permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
12196
12197 // Timeout
12198 BackgroundThread.getHandler().sendMessageDelayed(
12199 obtainMessage(CompletableFuture::complete, result, false),
12200 20_000);
12201
12202 return result.get();
12203 } catch (RemoteException re) {
12204 throw re.rethrowFromSystemServer();
12205 } catch (InterruptedException | ExecutionException e) {
12206 throw new RuntimeException(e);
12207 }
12208 }
12209
12210 /**
12211 * Returns the current grant state of a runtime permission for a specific application. This
12212 * function can be called by a device owner, profile owner, or by a delegate given the
12213 * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
12214 *
12215 * @param admin Which profile or device owner this request is associated with, or {@code null}
12216 * if the caller is a permission grant delegate.
12217 * @param packageName The application to check the grant state for.
12218 * @param permission The permission to check for.
12219 * @return the current grant state specified by device policy. If the profile or device owner
12220 * has not set a grant state, the return value is
12221 * {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
12222 * permission is currently granted for the package.
12223 * <p/>
12224 * If a grant state was set by the profile or device owner, then the return value will
12225 * be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
12226 * {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
12227 * currently denied or granted.
12228 * @throws SecurityException if {@code admin} is not a device or profile owner.
12229 * @see #setPermissionGrantState(ComponentName, String, String, int)
12230 * @see PackageManager#checkPermission(String, String)
12231 * @see #setDelegatedScopes
12232 * @see #DELEGATION_PERMISSION_GRANT
12233 */
12234 public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
12235 @NonNull String packageName, @NonNull String permission) {
12236 throwIfParentInstance("getPermissionGrantState");
12237 try {
12238 return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
12239 permission);
12240 } catch (RemoteException re) {
12241 throw re.rethrowFromSystemServer();
12242 }
12243 }
12244
12245 /**
12246 * Returns whether it is possible for the caller to initiate provisioning of a managed profile
12247 * or device, setting itself as the device or profile owner.
12248 *
12249 * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
12250 * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
12251 * @return whether provisioning a managed profile or device is possible.
12252 * @throws IllegalArgumentException if the supplied action is not valid.
12253 */
12254 public boolean isProvisioningAllowed(@NonNull String action) {
12255 throwIfParentInstance("isProvisioningAllowed");
12256 try {
12257 return mService.isProvisioningAllowed(action, mContext.getPackageName());
12258 } catch (RemoteException re) {
12259 throw re.rethrowFromSystemServer();
12260 }
12261 }
12262
12263 /**
12264 * Checks whether it is possible to initiate provisioning a managed device,
12265 * profile or user, setting the given package as owner.
12266 *
12267 * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
12268 * {@link #ACTION_PROVISION_MANAGED_PROFILE}
12269 * @param packageName The package of the component that would be set as device, user, or profile
12270 * owner.
12271 * @return An int constant value indicating whether provisioning is allowed.
12272 * @hide
12273 */
12274 @SystemApi
12275 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
12276 @ProvisioningPrecondition
12277 public int checkProvisioningPrecondition(
12278 @NonNull String action, @NonNull String packageName) {
12279 try {
12280 return mService.checkProvisioningPrecondition(action, packageName);
12281 } catch (RemoteException re) {
12282 throw re.rethrowFromSystemServer();
12283 }
12284 }
12285
12286 /**
12287 * Return if this user is a managed profile of another user. An admin can become the profile
12288 * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
12289 * user with {@link #createAndManageUser}
12290 * @param admin Which profile owner this request is associated with.
12291 * @return if this user is a managed profile of another user.
12292 */
12293 public boolean isManagedProfile(@NonNull ComponentName admin) {
12294 throwIfParentInstance("isManagedProfile");
12295 try {
12296 return mService.isManagedProfile(admin);
12297 } catch (RemoteException re) {
12298 throw re.rethrowFromSystemServer();
12299 }
12300 }
12301
12302 /**
12303 * Called by device owner, or profile owner on organization-owned device, to get the MAC
12304 * address of the Wi-Fi device.
12305 *
12306 * NOTE: The MAC address returned here should only be used for inventory management and is
12307 * not likely to be the MAC address used by the device to connect to Wi-Fi networks: MAC
12308 * addresses used for scanning and connecting to Wi-Fi networks are randomized by default.
12309 * To get the randomized MAC address used, call
12310 * {@link android.net.wifi.WifiConfiguration#getRandomizedMacAddress}.
12311 *
12312 * @param admin Which device owner this request is associated with.
12313 * @return the MAC address of the Wi-Fi device, or null when the information is not available.
12314 * (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
12315 * <p>
12316 * The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
12317 * @throws SecurityException if {@code admin} is not a device owner.
12318 */
12319 public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
12320 throwIfParentInstance("getWifiMacAddress");
12321 try {
12322 return mService.getWifiMacAddress(admin);
12323 } catch (RemoteException re) {
12324 throw re.rethrowFromSystemServer();
12325 }
12326 }
12327
12328 /**
12329 * Called by device owner to reboot the device. If there is an ongoing call on the device,
12330 * throws an {@link IllegalStateException}.
12331 * @param admin Which device owner the request is associated with.
12332 * @throws IllegalStateException if device has an ongoing call.
12333 * @throws SecurityException if {@code admin} is not a device owner.
12334 * @see TelephonyManager#CALL_STATE_IDLE
12335 */
12336 public void reboot(@NonNull ComponentName admin) {
12337 throwIfParentInstance("reboot");
12338 try {
12339 mService.reboot(admin);
12340 } catch (RemoteException re) {
12341 throw re.rethrowFromSystemServer();
12342 }
12343 }
12344
12345 /**
12346 * Called by a device admin to set the short support message. This will be displayed to the user
12347 * in settings screens where funtionality has been disabled by the admin. The message should be
12348 * limited to a short statement such as "This setting is disabled by your administrator. Contact
12349 * [email protected] for support." If the message is longer than 200 characters it may be
12350 * truncated.
12351 * <p>
12352 * If the short support message needs to be localized, it is the responsibility of the
12353 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
12354 * and set a new version of this string accordingly.
12355 *
12356 * @see #setLongSupportMessage
12357 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12358 * @param message Short message to be displayed to the user in settings or null to clear the
12359 * existing message.
12360 * @throws SecurityException if {@code admin} is not an active administrator.
12361 */
12362 public void setShortSupportMessage(@NonNull ComponentName admin,
12363 @Nullable CharSequence message) {
12364 throwIfParentInstance("setShortSupportMessage");
12365 if (mService != null) {
12366 try {
12367 mService.setShortSupportMessage(admin, message);
12368 } catch (RemoteException e) {
12369 throw e.rethrowFromSystemServer();
12370 }
12371 }
12372 }
12373
12374 /**
12375 * Called by a device admin to get the short support message.
12376 *
12377 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12378 * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
12379 * null if no message has been set.
12380 * @throws SecurityException if {@code admin} is not an active administrator.
12381 */
12382 public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
12383 throwIfParentInstance("getShortSupportMessage");
12384 if (mService != null) {
12385 try {
12386 return mService.getShortSupportMessage(admin);
12387 } catch (RemoteException e) {
12388 throw e.rethrowFromSystemServer();
12389 }
12390 }
12391 return null;
12392 }
12393
12394 /**
12395 * Called by a device admin to set the long support message. This will be displayed to the user
12396 * in the device administators settings screen.
12397 * <p>
12398 * If the long support message needs to be localized, it is the responsibility of the
12399 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
12400 * and set a new version of this string accordingly.
12401 *
12402 * @see #setShortSupportMessage
12403 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12404 * @param message Long message to be displayed to the user in settings or null to clear the
12405 * existing message.
12406 * @throws SecurityException if {@code admin} is not an active administrator.
12407 */
12408 public void setLongSupportMessage(@NonNull ComponentName admin,
12409 @Nullable CharSequence message) {
12410 throwIfParentInstance("setLongSupportMessage");
12411 if (mService != null) {
12412 try {
12413 mService.setLongSupportMessage(admin, message);
12414 } catch (RemoteException e) {
12415 throw e.rethrowFromSystemServer();
12416 }
12417 }
12418 }
12419
12420 /**
12421 * Called by a device admin to get the long support message.
12422 *
12423 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12424 * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
12425 * null if no message has been set.
12426 * @throws SecurityException if {@code admin} is not an active administrator.
12427 */
12428 public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
12429 throwIfParentInstance("getLongSupportMessage");
12430 if (mService != null) {
12431 try {
12432 return mService.getLongSupportMessage(admin);
12433 } catch (RemoteException e) {
12434 throw e.rethrowFromSystemServer();
12435 }
12436 }
12437 return null;
12438 }
12439
12440 /**
12441 * Called by the system to get the short support message.
12442 *
12443 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12444 * @param userHandle user id the admin is running as.
12445 * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
12446 *
12447 * @hide
12448 */
12449 public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
12450 int userHandle) {
12451 if (mService != null) {
12452 try {
12453 return mService.getShortSupportMessageForUser(admin, userHandle);
12454 } catch (RemoteException e) {
12455 throw e.rethrowFromSystemServer();
12456 }
12457 }
12458 return null;
12459 }
12460
12461
12462 /**
12463 * Called by the system to get the long support message.
12464 *
12465 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12466 * @param userHandle user id the admin is running as.
12467 * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
12468 *
12469 * @hide
12470 */
12471 public @Nullable CharSequence getLongSupportMessageForUser(
12472 @NonNull ComponentName admin, int userHandle) {
12473 if (mService != null) {
12474 try {
12475 return mService.getLongSupportMessageForUser(admin, userHandle);
12476 } catch (RemoteException e) {
12477 throw e.rethrowFromSystemServer();
12478 }
12479 }
12480 return null;
12481 }
12482
12483 /**
12484 * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
12485 * whose calls act on the parent profile.
12486 *
12487 * <p>The following methods are supported for the parent instance, all other methods will
12488 * throw a SecurityException when called on the parent instance:
12489 * <ul>
12490 * <li>{@link #getPasswordQuality}</li>
12491 * <li>{@link #setPasswordQuality}</li>
12492 * <li>{@link #getPasswordMinimumLength}</li>
12493 * <li>{@link #setPasswordMinimumLength}</li>
12494 * <li>{@link #getPasswordMinimumUpperCase}</li>
12495 * <li>{@link #setPasswordMinimumUpperCase}</li>
12496 * <li>{@link #getPasswordMinimumLowerCase}</li>
12497 * <li>{@link #setPasswordMinimumLowerCase}</li>
12498 * <li>{@link #getPasswordMinimumLetters}</li>
12499 * <li>{@link #setPasswordMinimumLetters}</li>
12500 * <li>{@link #getPasswordMinimumNumeric}</li>
12501 * <li>{@link #setPasswordMinimumNumeric}</li>
12502 * <li>{@link #getPasswordMinimumSymbols}</li>
12503 * <li>{@link #setPasswordMinimumSymbols}</li>
12504 * <li>{@link #getPasswordMinimumNonLetter}</li>
12505 * <li>{@link #setPasswordMinimumNonLetter}</li>
12506 * <li>{@link #getPasswordHistoryLength}</li>
12507 * <li>{@link #setPasswordHistoryLength}</li>
12508 * <li>{@link #getPasswordExpirationTimeout}</li>
12509 * <li>{@link #setPasswordExpirationTimeout}</li>
12510 * <li>{@link #getPasswordExpiration}</li>
12511 * <li>{@link #getPasswordMaximumLength}</li>
12512 * <li>{@link #isActivePasswordSufficient}</li>
12513 * <li>{@link #getCurrentFailedPasswordAttempts}</li>
12514 * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
12515 * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
12516 * <li>{@link #getMaximumTimeToLock}</li>
12517 * <li>{@link #setMaximumTimeToLock}</li>
12518 * <li>{@link #lockNow}</li>
12519 * <li>{@link #getKeyguardDisabledFeatures}</li>
12520 * <li>{@link #setKeyguardDisabledFeatures}</li>
12521 * <li>{@link #getTrustAgentConfiguration}</li>
12522 * <li>{@link #setTrustAgentConfiguration}</li>
12523 * <li>{@link #getRequiredStrongAuthTimeout}</li>
12524 * <li>{@link #setRequiredStrongAuthTimeout}</li>
12525 * <li>{@link #getAccountTypesWithManagementDisabled}</li>
12526 * <li>{@link #setRequiredPasswordComplexity(int)} </li>
12527 * <li>{@link #getRequiredPasswordComplexity()}</li>
12528 * </ul>
12529 * <p>
12530 * The following methods are supported for the parent instance but can only be called by the
12531 * profile owner of a managed profile that was created during the device provisioning flow:
12532 * <ul>
12533 * <li>{@link #getPasswordComplexity}</li>
12534 * <li>{@link #setCameraDisabled}</li>
12535 * <li>{@link #getCameraDisabled}</li>
12536 * <li>{@link #setAccountManagementDisabled(ComponentName, String, boolean)}</li>
12537 * <li>{@link #setPermittedInputMethods}</li>
12538 * <li>{@link #getPermittedInputMethods}</li>
12539 * </ul>
12540 *
12541 * <p>The following methods can be called by the profile owner of a managed profile
12542 * on an organization-owned device:
12543 * <ul>
12544 * <li>{@link #wipeData}</li>
12545 * </ul>
12546 *
12547 * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
12548 * @throws SecurityException if {@code admin} is not a profile owner.
12549 */
12550 public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
12551 throwIfParentInstance("getParentProfileInstance");
12552 try {
12553 if (!mService.isManagedProfile(admin)) {
12554 throw new SecurityException("The current user does not have a parent profile.");
12555 }
12556 return new DevicePolicyManager(mContext, mService, true);
12557 } catch (RemoteException e) {
12558 throw e.rethrowFromSystemServer();
12559 }
12560 }
12561
12562 /**
12563 * Called by device owner or a profile owner of an organization-owned managed profile to
12564 * control the security logging feature.
12565 *
12566 * <p> Security logs contain various information intended for security auditing purposes.
12567 * When security logging is enabled by a profile owner of
12568 * an organization-owned managed profile, certain security logs are not visible (for example
12569 * personal app launch events) or they will be redacted (for example, details of the physical
12570 * volume mount events). Please see {@link SecurityEvent} for details.
12571 *
12572 * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
12573 * are unaffiliated secondary users or profiles on the device, regardless of whether the
12574 * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
12575 * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
12576 * new users as soon as possible after provisioning via {@link #setAffiliationIds}. Profile
12577 * owner of organization-owned managed profile is not subject to this restriction since all
12578 * privacy-sensitive events happening outside the managed profile would have been redacted
12579 * already.
12580 *
12581 * @param admin Which device admin this request is associated with.
12582 * @param enabled whether security logging should be enabled or not.
12583 * @throws SecurityException if {@code admin} is not allowed to control security logging.
12584 * @see #setAffiliationIds
12585 * @see #retrieveSecurityLogs
12586 */
12587 public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
12588 throwIfParentInstance("setSecurityLoggingEnabled");
12589 try {
12590 mService.setSecurityLoggingEnabled(admin, mContext.getPackageName(), enabled);
12591 } catch (RemoteException re) {
12592 throw re.rethrowFromSystemServer();
12593 }
12594 }
12595
12596 /**
12597 * Return whether security logging is enabled or not by the admin.
12598 *
12599 * <p>Can only be called by the device owner or a profile owner of an organization-owned
12600 * managed profile, otherwise a {@link SecurityException} will be thrown.
12601 *
12602 * @param admin Which device admin this request is associated with.
12603 * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
12604 * @throws SecurityException if {@code admin} is not allowed to control security logging.
12605 */
12606 public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
12607 throwIfParentInstance("isSecurityLoggingEnabled");
12608 try {
12609 return mService.isSecurityLoggingEnabled(admin, mContext.getPackageName());
12610 } catch (RemoteException re) {
12611 throw re.rethrowFromSystemServer();
12612 }
12613 }
12614
12615 /**
12616 * Called by device owner or profile owner of an organization-owned managed profile to retrieve
12617 * all new security logging entries since the last call to this API after device boots.
12618 *
12619 * <p> Access to the logs is rate limited and it will only return new logs after the device
12620 * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
12621 *
12622 * <p> When called by a device owner, if there is any other user or profile on the device,
12623 * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
12624 * See {@link #isAffiliatedUser}.
12625 *
12626 * @param admin Which device admin this request is associated with.
12627 * @return the new batch of security logs which is a list of {@link SecurityEvent},
12628 * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
12629 * @throws SecurityException if {@code admin} is not allowed to access security logging,
12630 * or there is at least one profile or secondary user that is not affiliated with the device.
12631 * @see #isAffiliatedUser
12632 * @see DeviceAdminReceiver#onSecurityLogsAvailable
12633 */
12634 @SuppressLint("NullableCollection")
12635 public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
12636 throwIfParentInstance("retrieveSecurityLogs");
12637 try {
12638 ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(
12639 admin, mContext.getPackageName());
12640 if (list != null) {
12641 return list.getList();
12642 } else {
12643 // Rate limit exceeded.
12644 return null;
12645 }
12646 } catch (RemoteException re) {
12647 throw re.rethrowFromSystemServer();
12648 }
12649 }
12650
12651 /**
12652 * Makes all accumulated network logs available to DPC in a new batch.
12653 * If throttled, returns time to wait in milliseconds, otherwise 0.
12654 * @hide
12655 */
12656 @TestApi
12657 @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
12658 public long forceNetworkLogs() {
12659 if (mService == null) {
12660 return -1;
12661 }
12662 try {
12663 return mService.forceNetworkLogs();
12664 } catch (RemoteException re) {
12665 throw re.rethrowFromSystemServer();
12666 }
12667 }
12668
12669 /**
12670 * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
12671 * If throttled, returns time to wait in milliseconds, otherwise 0.
12672 * @hide
12673 */
12674 @TestApi
12675 @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
12676 public long forceSecurityLogs() {
12677 if (mService == null) {
12678 return 0;
12679 }
12680 try {
12681 return mService.forceSecurityLogs();
12682 } catch (RemoteException re) {
12683 throw re.rethrowFromSystemServer();
12684 }
12685 }
12686
12687 /**
12688 * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
12689 * profile.
12690 *
12691 * @hide
12692 */
12693 public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
12694 mContext.checkSelfPermission(
12695 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
12696 if (!uInfo.isManagedProfile()) {
12697 throw new SecurityException("The user " + uInfo.id
12698 + " does not have a parent profile.");
12699 }
12700 return new DevicePolicyManager(mContext, mService, true);
12701 }
12702
12703 /**
12704 * Called by a device or profile owner to restrict packages from using metered data.
12705 *
12706 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12707 * @param packageNames the list of package names to be restricted.
12708 * @return a list of package names which could not be restricted.
12709 * @throws SecurityException if {@code admin} is not a device or profile owner.
12710 */
12711 public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
12712 @NonNull List<String> packageNames) {
12713 throwIfParentInstance("setMeteredDataDisabled");
12714 if (mService != null) {
12715 try {
12716 return mService.setMeteredDataDisabledPackages(admin, packageNames);
12717 } catch (RemoteException re) {
12718 throw re.rethrowFromSystemServer();
12719 }
12720 }
12721 return packageNames;
12722 }
12723
12724 /**
12725 * Called by a device or profile owner to retrieve the list of packages which are restricted
12726 * by the admin from using metered data.
12727 *
12728 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12729 * @return the list of restricted package names.
12730 * @throws SecurityException if {@code admin} is not a device or profile owner.
12731 */
12732 public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
12733 throwIfParentInstance("getMeteredDataDisabled");
12734 if (mService != null) {
12735 try {
12736 return mService.getMeteredDataDisabledPackages(admin);
12737 } catch (RemoteException re) {
12738 throw re.rethrowFromSystemServer();
12739 }
12740 }
12741 return new ArrayList<>();
12742 }
12743
12744 /**
12745 * Called by the system to check if a package is restricted from using metered data
12746 * by {@param admin}.
12747 *
12748 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12749 * @param packageName the package whose restricted status is needed.
12750 * @param userId the user to which {@param packageName} belongs.
12751 * @return {@code true} if the package is restricted by admin, otherwise {@code false}
12752 * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
12753 * @hide
12754 */
12755 public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
12756 String packageName, @UserIdInt int userId) {
12757 throwIfParentInstance("getMeteredDataDisabledForUser");
12758 if (mService != null) {
12759 try {
12760 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
12761 } catch (RemoteException re) {
12762 throw re.rethrowFromSystemServer();
12763 }
12764 }
12765 return false;
12766 }
12767
12768 /**
12769 * Called by device owner or profile owner of an organization-owned managed profile to retrieve
12770 * device logs from before the device's last reboot.
12771 * <p>
12772 * <strong> This API is not supported on all devices. Calling this API on unsupported devices
12773 * will result in {@code null} being returned. The device logs are retrieved from a RAM region
12774 * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
12775 * about data corruption when parsing. </strong>
12776 *
12777 * <p> When called by a device owner, if there is any other user or profile on the device,
12778 * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
12779 * See {@link #isAffiliatedUser}.
12780 *
12781 * @param admin Which device admin this request is associated with.
12782 * @return Device logs from before the latest reboot of the system, or {@code null} if this API
12783 * is not supported on the device.
12784 * @throws SecurityException if {@code admin} is not allowed to access security logging, or
12785 * there is at least one profile or secondary user that is not affiliated with the device.
12786 * @see #isAffiliatedUser
12787 * @see #retrieveSecurityLogs
12788 */
12789 @SuppressLint("NullableCollection")
12790 public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
12791 @NonNull ComponentName admin) {
12792 throwIfParentInstance("retrievePreRebootSecurityLogs");
12793 try {
12794 ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(
12795 admin, mContext.getPackageName());
12796 if (list != null) {
12797 return list.getList();
12798 } else {
12799 return null;
12800 }
12801 } catch (RemoteException re) {
12802 throw re.rethrowFromSystemServer();
12803 }
12804 }
12805
12806 /**
12807 * Called by a profile owner of a managed profile to set the color used for customization. This
12808 * color is used as background color of the confirm credentials screen for that user. The
12809 * default color is teal (#00796B).
12810 * <p>
12811 * The confirm credentials screen can be created using
12812 * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
12813 * <p>
12814 * Starting from Android R, the organization color will no longer be used as the background
12815 * color of the confirm credentials screen.
12816 *
12817 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12818 * @param color The 24bit (0xRRGGBB) representation of the color to be used.
12819 * @throws SecurityException if {@code admin} is not a profile owner.
12820 * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
12821 * used as the background color of the confirm credentials screen.
12822 */
12823 @Deprecated
12824 public void setOrganizationColor(@NonNull ComponentName admin, int color) {
12825 throwIfParentInstance("setOrganizationColor");
12826 try {
12827 // always enforce alpha channel to have 100% opacity
12828 color |= 0xFF000000;
12829 mService.setOrganizationColor(admin, color);
12830 } catch (RemoteException re) {
12831 throw re.rethrowFromSystemServer();
12832 }
12833 }
12834
12835 /**
12836 * @hide
12837 *
12838 * Sets the color used for customization.
12839 *
12840 * @param color The 24bit (0xRRGGBB) representation of the color to be used.
12841 * @param userId which user to set the color to.
12842 * @RequiresPermission(allOf = {
12843 * Manifest.permission.MANAGE_USERS,
12844 * Manifest.permission.INTERACT_ACROSS_USERS_FULL})
12845 * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
12846 * used as the background color of the confirm credentials screen.
12847 */
12848 @Deprecated
12849 public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
12850 try {
12851 // always enforce alpha channel to have 100% opacity
12852 color |= 0xFF000000;
12853 mService.setOrganizationColorForUser(color, userId);
12854 } catch (RemoteException re) {
12855 throw re.rethrowFromSystemServer();
12856 }
12857 }
12858
12859 /**
12860 * Called by a profile owner of a managed profile to retrieve the color used for customization.
12861 * This color is used as background color of the confirm credentials screen for that user.
12862 *
12863 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12864 * @return The 24bit (0xRRGGBB) representation of the color to be used.
12865 * @throws SecurityException if {@code admin} is not a profile owner.
12866 * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
12867 * used as the background color of the confirm credentials screen.
12868 */
12869 @Deprecated
12870 public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
12871 throwIfParentInstance("getOrganizationColor");
12872 try {
12873 return mService.getOrganizationColor(admin);
12874 } catch (RemoteException re) {
12875 throw re.rethrowFromSystemServer();
12876 }
12877 }
12878
12879 /**
12880 * @hide
12881 * Retrieve the customization color for a given user.
12882 *
12883 * @param userHandle The user id of the user we're interested in.
12884 * @return The 24bit (0xRRGGBB) representation of the color to be used.
12885 * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
12886 * used as the background color of the confirm credentials screen.
12887 */
12888 @Deprecated
12889 public @ColorInt int getOrganizationColorForUser(int userHandle) {
12890 try {
12891 return mService.getOrganizationColorForUser(userHandle);
12892 } catch (RemoteException re) {
12893 throw re.rethrowFromSystemServer();
12894 }
12895 }
12896
12897 /**
12898 * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
12899 * the organization under management.
12900 *
12901 * <p>If the organization name needs to be localized, it is the responsibility of the {@link
12902 * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
12903 * a new version of this string accordingly.
12904 *
12905 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12906 * @param title The organization name or {@code null} to clear a previously set name.
12907 * @throws SecurityException if {@code admin} is not a device or profile owner.
12908 */
12909 public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
12910 throwIfParentInstance("setOrganizationName");
12911 try {
12912 mService.setOrganizationName(admin, title);
12913 } catch (RemoteException re) {
12914 throw re.rethrowFromSystemServer();
12915 }
12916 }
12917
12918 /**
12919 * Called by a profile owner of a managed profile to retrieve the name of the organization under
12920 * management.
12921 *
12922 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12923 * @return The organization name or {@code null} if none is set.
12924 * @throws SecurityException if {@code admin} is not a profile owner.
12925 */
12926 public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
12927 throwIfParentInstance("getOrganizationName");
12928 try {
12929 return mService.getOrganizationName(admin);
12930 } catch (RemoteException re) {
12931 throw re.rethrowFromSystemServer();
12932 }
12933 }
12934
12935 private final IpcDataCache<Void, CharSequence> mGetDeviceOwnerOrganizationNameCache =
12936 new IpcDataCache(sDpmCaches.child("getDeviceOwnerOrganizationName"),
12937 (query) -> getService().getDeviceOwnerOrganizationName());
12938
12939 /**
12940 * Called by the system to retrieve the name of the organization managing the device.
12941 *
12942 * @return The organization name or {@code null} if none is set.
12943 * @throws SecurityException if the caller is not the device owner, does not hold the
12944 * MANAGE_USERS permission and is not the system.
12945 *
12946 * @hide
12947 */
12948 @SystemApi
12949 @SuppressLint("RequiresPermission")
12950 public @Nullable CharSequence getDeviceOwnerOrganizationName() {
12951 return mGetDeviceOwnerOrganizationNameCache.query(null);
12952 }
12953
12954 private final IpcDataCache<Integer, CharSequence> mGetOrganizationNameForUserCache =
12955 new IpcDataCache<>(sDpmCaches.child("getOrganizationNameForUser"),
12956 (query) -> getService().getOrganizationNameForUser(query));
12957
12958 /**
12959 * Retrieve the default title message used in the confirm credentials screen for a given user.
12960 *
12961 * @param userHandle The user id of the user we're interested in.
12962 * @return The organization name or {@code null} if none is set.
12963 *
12964 * @hide
12965 */
12966 public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
12967 return mGetOrganizationNameForUserCache.query(userHandle);
12968 }
12969
12970 /**
12971 * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
12972 * return {@link #STATE_USER_UNMANAGED}
12973 * @hide
12974 */
12975 @SystemApi
12976 @RequiresPermission(anyOf = {
12977 android.Manifest.permission.MANAGE_USERS,
12978 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
12979 })
12980 @UserProvisioningState
12981 public int getUserProvisioningState() {
12982 throwIfParentInstance("getUserProvisioningState");
12983 if (mService != null) {
12984 try {
12985 return mService.getUserProvisioningState();
12986 } catch (RemoteException e) {
12987 throw e.rethrowFromSystemServer();
12988 }
12989 }
12990 return STATE_USER_UNMANAGED;
12991 }
12992
12993 /**
12994 * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
12995 *
12996 * @param state to store
12997 * @param userHandle for user
12998 *
12999 * @hide
13000 */
13001 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
13002 public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
13003 if (mService != null) {
13004 try {
13005 mService.setUserProvisioningState(state, userHandle);
13006 } catch (RemoteException e) {
13007 throw e.rethrowFromSystemServer();
13008 }
13009 }
13010 }
13011
13012 /**
13013 * Set the {@link UserProvisioningState} for the supplied user. The supplied user has to be
13014 * manged, otherwise it will throw an {@link IllegalStateException}.
13015 *
13016 * <p> For managed users/profiles/devices, only the following state changes are allowed:
13017 * <ul>
13018 * <li>{@link #STATE_USER_UNMANAGED} can change to any other state except itself
13019 * <li>{@link #STATE_USER_SETUP_INCOMPLETE} and {@link #STATE_USER_SETUP_COMPLETE} can only
13020 * change to {@link #STATE_USER_SETUP_FINALIZED}</li>
13021 * <li>{@link #STATE_USER_PROFILE_COMPLETE} can only change to
13022 * {@link #STATE_USER_PROFILE_FINALIZED}</li>
13023 * <li>{@link #STATE_USER_SETUP_FINALIZED} can't be changed to any other state</li>
13024 * <li>{@link #STATE_USER_PROFILE_FINALIZED} can only change to
13025 * {@link #STATE_USER_UNMANAGED}</li>
13026 * </ul>
13027 * @param state to store
13028 * @param userHandle for user
13029 * @throws IllegalStateException if called with an invalid state change.
13030 *
13031 * @hide
13032 */
13033 @SystemApi
13034 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
13035 public void setUserProvisioningState(
13036 @UserProvisioningState int state, @NonNull UserHandle userHandle) {
13037 setUserProvisioningState(state, userHandle.getIdentifier());
13038 }
13039
13040 /**
13041 * Indicates the entity that controls the device. Two users are
13042 * affiliated if the set of ids set by the device owner and the admin of the secondary user.
13043 *
13044 * <p>A user that is affiliated with the device owner user is considered to be
13045 * affiliated with the device.
13046 *
13047 * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
13048 * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user
13049 * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
13050 * affiliation ids are set by its owner as soon as possible after the user is
13051 * created.
13052 * <p>
13053 * Note: This method used to be available for affiliating device owner and profile
13054 * owner. However, since Android 11, this combination is not possible. This method is now
13055 * only useful for affiliating the primary user with managed secondary users.
13056 *
13057 * @param admin Which device owner, or owner of secondary user, this request is associated with.
13058 * @param ids A set of opaque non-empty affiliation ids.
13059 *
13060 * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
13061 * @see #isAffiliatedUser
13062 */
13063 public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
13064 throwIfParentInstance("setAffiliationIds");
13065 if (ids == null) {
13066 throw new IllegalArgumentException("ids must not be null");
13067 }
13068 try {
13069 mService.setAffiliationIds(admin, new ArrayList<>(ids));
13070 } catch (RemoteException e) {
13071 throw e.rethrowFromSystemServer();
13072 }
13073 }
13074
13075 /**
13076 * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
13077 * empty set if none have been set.
13078 */
13079 public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
13080 throwIfParentInstance("getAffiliationIds");
13081 try {
13082 return new ArraySet<>(mService.getAffiliationIds(admin));
13083 } catch (RemoteException e) {
13084 throw e.rethrowFromSystemServer();
13085 }
13086 }
13087
13088 /**
13089 * Returns whether this user is affiliated with the device.
13090 * <p>
13091 * By definition, the user that the device owner runs on is always affiliated with the device.
13092 * Any other user is considered affiliated with the device if the set specified by its
13093 * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
13094 * @see #setAffiliationIds
13095 */
13096 public boolean isAffiliatedUser() {
13097 throwIfParentInstance("isAffiliatedUser");
13098 try {
13099 return mService.isCallingUserAffiliated();
13100 } catch (RemoteException e) {
13101 throw e.rethrowFromSystemServer();
13102 }
13103 }
13104
13105 /**
13106 * @hide
13107 * Returns whether target user is affiliated with the device.
13108 */
13109 public boolean isAffiliatedUser(@UserIdInt int userId) {
13110 try {
13111 return mService.isAffiliatedUser(userId);
13112 } catch (RemoteException e) {
13113 throw e.rethrowFromSystemServer();
13114 }
13115 }
13116
13117 /**
13118 * @hide
13119 * Returns whether the uninstall for {@code packageName} for the current user is in queue
13120 * to be started
13121 * @param packageName the package to check for
13122 * @return whether the uninstall intent for {@code packageName} is pending
13123 */
13124 public boolean isUninstallInQueue(String packageName) {
13125 try {
13126 return mService.isUninstallInQueue(packageName);
13127 } catch (RemoteException re) {
13128 throw re.rethrowFromSystemServer();
13129 }
13130 }
13131
13132 /**
13133 * @hide
13134 * @param packageName the package containing active DAs to be uninstalled
13135 */
13136 public void uninstallPackageWithActiveAdmins(String packageName) {
13137 try {
13138 mService.uninstallPackageWithActiveAdmins(packageName);
13139 } catch (RemoteException re) {
13140 throw re.rethrowFromSystemServer();
13141 }
13142 }
13143
13144 /**
13145 * @hide
13146 * Remove a test admin synchronously without sending it a broadcast about being removed.
13147 * If the admin is a profile owner or device owner it will still be removed.
13148 *
13149 * @param userHandle user id to remove the admin for.
13150 * @param admin The administration compononent to remove.
13151 * @throws SecurityException if the caller is not shell / root or the admin package
13152 * isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
13153 */
13154 @TestApi
13155 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
13156 public void forceRemoveActiveAdmin(
13157 @NonNull ComponentName adminReceiver, @UserIdInt int userHandle) {
13158 try {
13159 mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
13160 } catch (RemoteException re) {
13161 throw re.rethrowFromSystemServer();
13162 }
13163 }
13164
13165 /**
13166 * Returns whether the device has been provisioned.
13167 *
13168 * <p>Not for use by third-party applications.
13169 *
13170 * @hide
13171 */
13172 @SystemApi
13173 @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
13174 public boolean isDeviceProvisioned() {
13175 try {
13176 return mService.isDeviceProvisioned();
13177 } catch (RemoteException re) {
13178 throw re.rethrowFromSystemServer();
13179 }
13180 }
13181
13182 /**
13183 * Writes that the provisioning configuration has been applied.
13184 *
13185 * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
13186 * permission.
13187 *
13188 * <p>Not for use by third-party applications.
13189 *
13190 * @hide
13191 */
13192 @SystemApi
13193 @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
13194 public void setDeviceProvisioningConfigApplied() {
13195 try {
13196 mService.setDeviceProvisioningConfigApplied();
13197 } catch (RemoteException re) {
13198 throw re.rethrowFromSystemServer();
13199 }
13200 }
13201
13202 /**
13203 * Returns whether the provisioning configuration has been applied.
13204 *
13205 * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
13206 *
13207 * <p>Not for use by third-party applications.
13208 *
13209 * @return whether the provisioning configuration has been applied.
13210 *
13211 * @hide
13212 */
13213 @SystemApi
13214 @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
13215 public boolean isDeviceProvisioningConfigApplied() {
13216 try {
13217 return mService.isDeviceProvisioningConfigApplied();
13218 } catch (RemoteException re) {
13219 throw re.rethrowFromSystemServer();
13220 }
13221 }
13222
13223 /**
13224 * @hide
13225 * Force update user setup completed status for the given {@code userId}.
13226 * @throws {@link SecurityException} if the caller has no
13227 * {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS}.
13228 */
13229 @TestApi
13230 public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
13231 try {
13232 mService.forceUpdateUserSetupComplete(userId);
13233 } catch (RemoteException re) {
13234 throw re.rethrowFromSystemServer();
13235 }
13236 }
13237
13238 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
13239 private void throwIfParentInstance(String functionName) {
13240 if (mParentInstance) {
13241 throw new SecurityException(functionName + " cannot be called on the parent instance");
13242 }
13243 }
13244
13245 /**
13246 * Allows the device owner or profile owner to enable or disable the backup service.
13247 *
13248 * <p> Each user has its own backup service which manages the backup and restore mechanisms in
13249 * that user. Disabling the backup service will prevent data from being backed up or restored.
13250 *
13251 * <p> Device owner calls this API to control backup services across all users on the device.
13252 * Profile owner can use this API to enable or disable the profile's backup service. However,
13253 * for a managed profile its backup functionality is only enabled if both the device owner
13254 * and the profile owner have enabled the backup service.
13255 *
13256 * <p> By default, backup service is disabled on a device with device owner, and within a
13257 * managed profile.
13258 *
13259 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13260 * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
13261 * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
13262 */
13263 public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
13264 throwIfParentInstance("setBackupServiceEnabled");
13265 try {
13266 mService.setBackupServiceEnabled(admin, enabled);
13267 } catch (RemoteException re) {
13268 throw re.rethrowFromSystemServer();
13269 }
13270 }
13271
13272 /**
13273 * Return whether the backup service is enabled by the device owner or profile owner for the
13274 * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
13275 *
13276 * <p> Whether the backup functionality is actually enabled or not depends on settings from both
13277 * the current user and the device owner, please see
13278 * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
13279 *
13280 * <p> Backup service manages all backup and restore mechanisms on the device.
13281 *
13282 * @return {@code true} if backup service is enabled, {@code false} otherwise.
13283 * @see #setBackupServiceEnabled
13284 */
13285 public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
13286 throwIfParentInstance("isBackupServiceEnabled");
13287 try {
13288 return mService.isBackupServiceEnabled(admin);
13289 } catch (RemoteException re) {
13290 throw re.rethrowFromSystemServer();
13291 }
13292 }
13293
13294 /**
13295 * Called by a device owner, profile owner of a managed profile or delegated app with
13296 * {@link #DELEGATION_NETWORK_LOGGING} to control the network logging feature.
13297 *
13298 * <p> Supported for a device owner from Android 8 and a delegated app granted by a device
13299 * owner from Android 10. Supported for a profile owner of a managed profile and a delegated
13300 * app granted by a profile owner from Android 12. When network logging is enabled by a
13301 * profile owner, the network logs will only include work profile network activity, not
13302 * activity on the personal profile.
13303 *
13304 * <p> Network logs contain DNS lookup and connect() library call events. The following library
13305 * functions are recorded while network logging is active:
13306 * <ul>
13307 * <li>{@code getaddrinfo()}</li>
13308 * <li>{@code gethostbyname()}</li>
13309 * <li>{@code connect()}</li>
13310 * </ul>
13311 *
13312 * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
13313 * full system call logging; event reporting is enabled by default for all processes but not
13314 * strongly enforced.
13315 * Events from applications using alternative implementations of libc, making direct kernel
13316 * calls, or deliberately obfuscating traffic may not be recorded.
13317 *
13318 * <p> Some common network events may not be reported. For example:
13319 * <ul>
13320 * <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
13321 * an alternative system for name resolution, and so avoid calling
13322 * {@code getaddrinfo()} or {@code gethostbyname}.</li>
13323 * <li>Applications may use datagram sockets for performance reasons, for example
13324 * for a game client. Calling {@code connect()} is unnecessary for this kind of
13325 * socket, so it will not trigger a network event.</li>
13326 * </ul>
13327 *
13328 * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
13329 * always-on VPN service.
13330 * See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
13331 * and {@link android.net.VpnService} for details.
13332 *
13333 * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
13334 * are unaffiliated secondary users or profiles on the device, regardless of whether the
13335 * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
13336 * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
13337 * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
13338 *
13339 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
13340 * {@code null} if called by a delegated app.
13341 * @param enabled whether network logging should be enabled or not.
13342 * @throws SecurityException if {@code admin} is not a device owner or profile owner.
13343 * @see #setAffiliationIds
13344 * @see #retrieveNetworkLogs
13345 */
13346 public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
13347 throwIfParentInstance("setNetworkLoggingEnabled");
13348 try {
13349 mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
13350 } catch (RemoteException re) {
13351 throw re.rethrowFromSystemServer();
13352 }
13353 }
13354
13355 private IpcDataCache<ComponentName, Boolean> mIsNetworkLoggingEnabledCache =
13356 new IpcDataCache<>(sDpmCaches.child("isNetworkLoggingEnabled"),
13357 (admin) -> getService().isNetworkLoggingEnabled(admin,
13358 getContext().getPackageName()));
13359
13360 /**
13361 * Return whether network logging is enabled by a device owner or profile owner of
13362 * a managed profile.
13363 *
13364 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
13365 * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
13366 * or has MANAGE_USERS permission.
13367 * @return {@code true} if network logging is enabled by device owner or profile owner,
13368 * {@code false} otherwise.
13369 * @throws SecurityException if {@code admin} is not a device owner or profile owner and
13370 * caller has no MANAGE_USERS permission
13371 */
13372 public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
13373 throwIfParentInstance("isNetworkLoggingEnabled");
13374 return mIsNetworkLoggingEnabledCache.query(admin);
13375 }
13376
13377 /**
13378 * Called by device owner, profile owner of a managed profile or delegated app with
13379 * {@link #DELEGATION_NETWORK_LOGGING} to retrieve the most recent batch of
13380 * network logging events.
13381 *
13382 * <p> When network logging is enabled by a profile owner, the network logs will only include
13383 * work profile network activity, not activity on the personal profile.
13384 *
13385 * A device owner or profile owner has to provide a batchToken provided as part of
13386 * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
13387 * token of the most recent available batch of logs, {@code null} will be returned.
13388 *
13389 * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
13390 *
13391 * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
13392 *
13393 * <p> Access to the logs is rate limited and this method will only return a new batch of logs
13394 * after the device device owner has been notified via
13395 * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
13396 *
13397 * <p>If the caller is not a profile owner and a secondary user or profile is created, calling
13398 * this method will throw a {@link SecurityException} until all users become affiliated again.
13399 * It will also no longer be possible to retrieve the network logs batch with the most recent
13400 * batchToken provided by {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
13401 * See {@link DevicePolicyManager#setAffiliationIds}.
13402 *
13403 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
13404 * {@code null} if called by a delegated app.
13405 * @param batchToken A token of the batch to retrieve
13406 * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
13407 * {@code null} if the batch represented by batchToken is no longer available or if
13408 * logging is disabled.
13409 * @throws SecurityException if {@code admin} is not a device owner, profile owner or if the
13410 * {@code admin} is not a profile owner and there is at least one profile or secondary user
13411 * that is not affiliated with the device.
13412 * @see #setAffiliationIds
13413 * @see DeviceAdminReceiver#onNetworkLogsAvailable
13414 */
13415 public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
13416 long batchToken) {
13417 throwIfParentInstance("retrieveNetworkLogs");
13418 try {
13419 return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
13420 } catch (RemoteException re) {
13421 throw re.rethrowFromSystemServer();
13422 }
13423 }
13424
13425 /**
13426 * Called by a device owner to bind to a service from a secondary managed user or vice versa.
13427 * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a
13428 * device owner to bind to services of another managed user.
13429 * <p>
13430 * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
13431 * Note that the {@link Context} used to obtain this
13432 * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
13433 * to bind to the {@link android.app.Service}.
13434 * <p>
13435 * Note: This method used to be available for communication between device owner and profile
13436 * owner. However, since Android 11, this combination is not possible. This method is now
13437 * only useful for communication between device owner and managed secondary users.
13438 *
13439 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13440 * @param serviceIntent Identifies the service to connect to. The Intent must specify either an
13441 * explicit component name or a package name to match an
13442 * {@link IntentFilter} published by a service.
13443 * @param conn Receives information as the service is started and stopped in main thread. This
13444 * must be a valid {@link ServiceConnection} object; it must not be {@code null}.
13445 * @param flags Operation options for the binding operation. See
13446 * {@link Context#bindService(Intent, ServiceConnection, int)}.
13447 * @param targetUser Which user to bind to. Must be one of the users returned by
13448 * {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
13449 * be thrown.
13450 * @return If you have successfully bound to the service, {@code true} is returned;
13451 * {@code false} is returned if the connection is not made and you will not
13452 * receive the service object.
13453 *
13454 * @see Context#bindService(Intent, ServiceConnection, int)
13455 * @see #getBindDeviceAdminTargetUsers(ComponentName)
13456 */
13457 public boolean bindDeviceAdminServiceAsUser(
13458 @NonNull ComponentName admin, Intent serviceIntent, @NonNull ServiceConnection conn,
13459 @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
13460 throwIfParentInstance("bindDeviceAdminServiceAsUser");
13461 // Keep this in sync with ContextImpl.bindServiceCommon.
13462 try {
13463 final IServiceConnection sd = mContext.getServiceDispatcher(
13464 conn, mContext.getMainThreadHandler(), flags);
13465 serviceIntent.prepareToLeaveProcess(mContext);
13466 return mService.bindDeviceAdminServiceAsUser(admin,
13467 mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
13468 sd, flags, targetUser.getIdentifier());
13469 } catch (RemoteException re) {
13470 throw re.rethrowFromSystemServer();
13471 }
13472 }
13473
13474 /**
13475 * Returns the list of target users that the calling device owner or owner of secondary user
13476 * can use when calling {@link #bindDeviceAdminServiceAsUser}.
13477 * <p>
13478 * A device owner can bind to a service from a secondary managed user and vice versa, provided
13479 * that both users are affiliated. See {@link #setAffiliationIds}.
13480 */
13481 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
13482 throwIfParentInstance("getBindDeviceAdminTargetUsers");
13483 try {
13484 return mService.getBindDeviceAdminTargetUsers(admin);
13485 } catch (RemoteException re) {
13486 throw re.rethrowFromSystemServer();
13487 }
13488 }
13489
13490 /**
13491 * Called by the system to get the time at which the device owner last retrieved security
13492 * logging entries.
13493 *
13494 * @return the time at which the device owner most recently retrieved security logging entries,
13495 * in milliseconds since epoch; -1 if security logging entries were never retrieved.
13496 * @throws SecurityException if the caller is not the device owner, does not hold the
13497 * MANAGE_USERS permission and is not the system.
13498 *
13499 * @hide
13500 */
13501 @TestApi
13502 public long getLastSecurityLogRetrievalTime() {
13503 try {
13504 return mService.getLastSecurityLogRetrievalTime();
13505 } catch (RemoteException re) {
13506 throw re.rethrowFromSystemServer();
13507 }
13508 }
13509
13510 /**
13511 * Called by the system to get the time at which the device owner last requested a bug report.
13512 *
13513 * @return the time at which the device owner most recently requested a bug report, in
13514 * milliseconds since epoch; -1 if a bug report was never requested.
13515 * @throws SecurityException if the caller is not the device owner, does not hold the
13516 * MANAGE_USERS permission and is not the system.
13517 *
13518 * @hide
13519 */
13520 @TestApi
13521 public long getLastBugReportRequestTime() {
13522 try {
13523 return mService.getLastBugReportRequestTime();
13524 } catch (RemoteException re) {
13525 throw re.rethrowFromSystemServer();
13526 }
13527 }
13528
13529 /**
13530 * Called by the system to get the time at which the device owner or profile owner of a
13531 * managed profile last retrieved network logging events.
13532 *
13533 * @return the time at which the device owner or profile owner most recently retrieved network
13534 * logging events, in milliseconds since epoch; -1 if network logging events were
13535 * never retrieved.
13536 * @throws SecurityException if the caller is not the device owner, does not hold the
13537 * MANAGE_USERS permission and is not the system.
13538 *
13539 * @hide
13540 */
13541 @TestApi
13542 public long getLastNetworkLogRetrievalTime() {
13543 try {
13544 return mService.getLastNetworkLogRetrievalTime();
13545 } catch (RemoteException re) {
13546 throw re.rethrowFromSystemServer();
13547 }
13548 }
13549
13550 /**
13551 * Called by the system to find out whether the current user's IME was set by the device/profile
13552 * owner or the user.
13553 *
13554 * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
13555 * otherwise.
13556 * @throws SecurityException if the caller is not the device owner/profile owner.
13557 *
13558 * @hide
13559 */
13560 @TestApi
13561 public boolean isCurrentInputMethodSetByOwner() {
13562 try {
13563 return mService.isCurrentInputMethodSetByOwner();
13564 } catch (RemoteException re) {
13565 throw re.rethrowFromSystemServer();
13566 }
13567 }
13568
13569 /**
13570 * Called by the system to get a list of CA certificates that were installed by the device or
13571 * profile owner.
13572 *
13573 * <p> The caller must be the target user's device owner/profile Owner or hold the
13574 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
13575 *
13576 * @param user The user for whom to retrieve information.
13577 * @return list of aliases identifying CA certificates installed by the device or profile owner
13578 * @throws SecurityException if the caller does not have permission to retrieve information
13579 * about the given user's CA certificates.
13580 *
13581 * @hide
13582 */
13583 @TestApi
13584 public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
13585 try {
13586 return mService.getOwnerInstalledCaCerts(user).getList();
13587 } catch (RemoteException re) {
13588 throw re.rethrowFromSystemServer();
13589 }
13590 }
13591
13592 /**
13593 * Returns whether factory reset protection policy is supported on the device.
13594 *
13595 * @return {@code true} if the device support factory reset protection policy.
13596 *
13597 * @hide
13598 */
13599 @TestApi
13600 public boolean isFactoryResetProtectionPolicySupported() {
13601 try {
13602 return mService.isFactoryResetProtectionPolicySupported();
13603 } catch (RemoteException re) {
13604 throw re.rethrowFromSystemServer();
13605 }
13606 }
13607
13608 /**
13609 * Called by the device owner or profile owner to clear application user data of a given
13610 * package. The behaviour of this is equivalent to the target application calling
13611 * {@link android.app.ActivityManager#clearApplicationUserData()}.
13612 *
13613 * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
13614 * external storage or user dictionary. This data will not be wiped by calling this API.
13615 *
13616 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13617 * @param packageName The name of the package which will have its user data wiped.
13618 * @param executor The executor through which the listener should be invoked.
13619 * @param listener A callback object that will inform the caller when the clearing is done.
13620 * @throws SecurityException if the caller is not the device owner/profile owner.
13621 */
13622 public void clearApplicationUserData(@NonNull ComponentName admin,
13623 @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
13624 @NonNull OnClearApplicationUserDataListener listener) {
13625 throwIfParentInstance("clearAppData");
13626 Objects.requireNonNull(executor);
13627 Objects.requireNonNull(listener);
13628 try {
13629 mService.clearApplicationUserData(admin, packageName,
13630 new IPackageDataObserver.Stub() {
13631 public void onRemoveCompleted(String pkg, boolean succeeded) {
13632 executor.execute(() ->
13633 listener.onApplicationUserDataCleared(pkg, succeeded));
13634 }
13635 });
13636 } catch (RemoteException re) {
13637 throw re.rethrowFromSystemServer();
13638 }
13639 }
13640
13641 /**
13642 * Called by a device owner to specify whether logout is enabled for all secondary users. The
13643 * system may show a logout button that stops the user and switches back to the primary user.
13644 *
13645 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13646 * @param enabled whether logout should be enabled or not.
13647 * @throws SecurityException if {@code admin} is not a device owner.
13648 */
13649 public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
13650 throwIfParentInstance("setLogoutEnabled");
13651 try {
13652 mService.setLogoutEnabled(admin, enabled);
13653 } catch (RemoteException re) {
13654 throw re.rethrowFromSystemServer();
13655 }
13656 }
13657
13658 /**
13659 * Returns whether logout is enabled by a device owner.
13660 *
13661 * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
13662 */
13663 public boolean isLogoutEnabled() {
13664 throwIfParentInstance("isLogoutEnabled");
13665 try {
13666 return mService.isLogoutEnabled();
13667 } catch (RemoteException re) {
13668 throw re.rethrowFromSystemServer();
13669 }
13670 }
13671
13672 /**
13673 * Callback used in {@link #clearApplicationUserData}
13674 * to indicate that the clearing of an application's user data is done.
13675 */
13676 public interface OnClearApplicationUserDataListener {
13677 /**
13678 * Method invoked when clearing the application user data has completed.
13679 *
13680 * @param packageName The name of the package which had its user data cleared.
13681 * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
13682 * apps and protected system packages.
13683 */
13684 void onApplicationUserDataCleared(String packageName, boolean succeeded);
13685 }
13686
13687 /**
13688 * Returns set of system apps that should be removed during provisioning.
13689 *
13690 * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13691 * @param userId ID of the user to be provisioned.
13692 * @param provisioningAction action indicating type of provisioning, should be one of
13693 * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
13694 * {@link #ACTION_PROVISION_MANAGED_USER}.
13695 *
13696 * @hide
13697 */
13698 @TestApi
13699 public @NonNull Set<String> getDisallowedSystemApps(@NonNull ComponentName admin,
13700 @UserIdInt int userId, @NonNull String provisioningAction) {
13701 try {
13702 return new ArraySet<>(
13703 mService.getDisallowedSystemApps(admin, userId, provisioningAction));
13704 } catch (RemoteException re) {
13705 throw re.rethrowFromSystemServer();
13706 }
13707 }
13708
13709 /**
13710 * Changes the current administrator to another one. All policies from the current
13711 * administrator are migrated to the new administrator. The whole operation is atomic -
13712 * the transfer is either complete or not done at all.
13713 *
13714 * <p>Depending on the current administrator (device owner, profile owner), you have the
13715 * following expected behaviour:
13716 * <ul>
13717 * <li>A device owner can only be transferred to a new device owner</li>
13718 * <li>A profile owner can only be transferred to a new profile owner</li>
13719 * </ul>
13720 *
13721 * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
13722 * will be received in the
13723 * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
13724 * callback of the new administrator.
13725 *
13726 * <p>The transfer has failed if the original administrator is still the corresponding owner
13727 * after calling this method.
13728 *
13729 * <p>The incoming target administrator must have the
13730 * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
13731 * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
13732 * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
13733 * {@link IllegalArgumentException} will be thrown.
13734 *
13735 * @param admin which {@link DeviceAdminReceiver} this request is associated with
13736 * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
13737 * @param bundle data to be sent to the new administrator
13738 * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
13739 * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
13740 * are components in the same package or {@code target} is not an active admin
13741 */
13742 public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
13743 @Nullable PersistableBundle bundle) {
13744 throwIfParentInstance("transferOwnership");
13745 try {
13746 mService.transferOwnership(admin, target, bundle);
13747 } catch (RemoteException re) {
13748 throw re.rethrowFromSystemServer();
13749 }
13750 }
13751
13752 /**
13753 * Called by a device owner to specify the user session start message. This may be displayed
13754 * during a user switch.
13755 * <p>
13756 * The message should be limited to a short statement or it may be truncated.
13757 * <p>
13758 * If the message needs to be localized, it is the responsibility of the
13759 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
13760 * and set a new version of this message accordingly.
13761 *
13762 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13763 * @param startUserSessionMessage message for starting user session, or {@code null} to use
13764 * system default message.
13765 * @throws SecurityException if {@code admin} is not a device owner.
13766 */
13767 public void setStartUserSessionMessage(
13768 @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
13769 throwIfParentInstance("setStartUserSessionMessage");
13770 try {
13771 mService.setStartUserSessionMessage(admin, startUserSessionMessage);
13772 } catch (RemoteException re) {
13773 throw re.rethrowFromSystemServer();
13774 }
13775 }
13776
13777 /**
13778 * Called by a device owner to specify the user session end message. This may be displayed
13779 * during a user switch.
13780 * <p>
13781 * The message should be limited to a short statement or it may be truncated.
13782 * <p>
13783 * If the message needs to be localized, it is the responsibility of the
13784 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
13785 * and set a new version of this message accordingly.
13786 *
13787 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13788 * @param endUserSessionMessage message for ending user session, or {@code null} to use system
13789 * default message.
13790 * @throws SecurityException if {@code admin} is not a device owner.
13791 */
13792 public void setEndUserSessionMessage(
13793 @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
13794 throwIfParentInstance("setEndUserSessionMessage");
13795 try {
13796 mService.setEndUserSessionMessage(admin, endUserSessionMessage);
13797 } catch (RemoteException re) {
13798 throw re.rethrowFromSystemServer();
13799 }
13800 }
13801
13802 /**
13803 * Returns the user session start message.
13804 *
13805 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13806 * @throws SecurityException if {@code admin} is not a device owner.
13807 */
13808 public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
13809 throwIfParentInstance("getStartUserSessionMessage");
13810 try {
13811 return mService.getStartUserSessionMessage(admin);
13812 } catch (RemoteException re) {
13813 throw re.rethrowFromSystemServer();
13814 }
13815 }
13816
13817 /**
13818 * Returns the user session end message.
13819 *
13820 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13821 * @throws SecurityException if {@code admin} is not a device owner.
13822 */
13823 public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
13824 throwIfParentInstance("getEndUserSessionMessage");
13825 try {
13826 return mService.getEndUserSessionMessage(admin);
13827 } catch (RemoteException re) {
13828 throw re.rethrowFromSystemServer();
13829 }
13830 }
13831
13832 /**
13833 * Called by device owner or managed profile owner to add an override APN.
13834 *
13835 * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
13836 * override APN. Update the existing conflicted APN with
13837 * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
13838 * <p>Two override APNs are considered to conflict when all the following APIs return
13839 * the same values on both override APNs:
13840 * <ul>
13841 * <li>{@link ApnSetting#getOperatorNumeric()}</li>
13842 * <li>{@link ApnSetting#getApnName()}</li>
13843 * <li>{@link ApnSetting#getProxyAddressAsString()}</li>
13844 * <li>{@link ApnSetting#getProxyPort()}</li>
13845 * <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
13846 * <li>{@link ApnSetting#getMmsProxyPort()}</li>
13847 * <li>{@link ApnSetting#getMmsc()}</li>
13848 * <li>{@link ApnSetting#isEnabled()}</li>
13849 * <li>{@link ApnSetting#getMvnoType()}</li>
13850 * <li>{@link ApnSetting#getProtocol()}</li>
13851 * <li>{@link ApnSetting#getRoamingProtocol()}</li>
13852 * </ul>
13853 *
13854 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13855 * Only device owners can add APNs.
13856 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13857 * Both device owners and managed profile owners can add enterprise APNs
13858 * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can add other type of APNs.
13859 * Enterprise APNs are specific to the managed profile and do not override any user-configured
13860 * VPNs. They are prerequisites for enabling preferential network service on the managed
13861 * profile on 4G networks ({@link #setPreferentialNetworkServiceConfigs}).
13862 *
13863 * @param admin which {@link DeviceAdminReceiver} this request is associated with
13864 * @param apnSetting the override APN to insert
13865 * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
13866 * the database.
13867 * @throws SecurityException If request is for enterprise APN {@code admin} is either device
13868 * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
13869 *
13870 * @see #setOverrideApnsEnabled(ComponentName, boolean)
13871 */
13872 public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
13873 throwIfParentInstance("addOverrideApn");
13874 if (mService != null) {
13875 try {
13876 return mService.addOverrideApn(admin, apnSetting);
13877 } catch (RemoteException e) {
13878 throw e.rethrowFromSystemServer();
13879 }
13880 }
13881 return -1;
13882 }
13883
13884 /**
13885 * Called by device owner or managed profile owner to update an override APN.
13886 *
13887 * <p>This method may returns {@code false} if there is no override APN with the given
13888 * {@code apnId}.
13889 * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
13890 * existing override APN. Update the existing conflicted APN instead.
13891 * <p>See {@link #addOverrideApn} for the definition of conflict.
13892 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13893 * Only device owners can update APNs.
13894 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13895 * Both device owners and managed profile owners can update enterprise APNs
13896 * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can update other type of APNs.
13897 *
13898 * @param admin which {@link DeviceAdminReceiver} this request is associated with
13899 * @param apnId the {@code id} of the override APN to update
13900 * @param apnSetting the override APN to update
13901 * @return {@code true} if the required override APN is successfully updated,
13902 * {@code false} otherwise.
13903 * @throws SecurityException If request is for enterprise APN {@code admin} is either device
13904 * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
13905 *
13906 * @see #setOverrideApnsEnabled(ComponentName, boolean)
13907 */
13908 public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
13909 @NonNull ApnSetting apnSetting) {
13910 throwIfParentInstance("updateOverrideApn");
13911 if (mService != null) {
13912 try {
13913 return mService.updateOverrideApn(admin, apnId, apnSetting);
13914 } catch (RemoteException e) {
13915 throw e.rethrowFromSystemServer();
13916 }
13917 }
13918 return false;
13919 }
13920
13921 /**
13922 * Called by device owner or managed profile owner to remove an override APN.
13923 *
13924 * <p>This method may returns {@code false} if there is no override APN with the given
13925 * {@code apnId}.
13926 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13927 * Only device owners can remove APNs.
13928 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13929 * Both device owners and managed profile owners can remove enterprise APNs
13930 * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can remove other type of APNs.
13931 *
13932 * @param admin which {@link DeviceAdminReceiver} this request is associated with
13933 * @param apnId the {@code id} of the override APN to remove
13934 * @return {@code true} if the required override APN is successfully removed, {@code false}
13935 * otherwise.
13936 * @throws SecurityException If request is for enterprise APN {@code admin} is either device
13937 * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
13938 *
13939 * @see #setOverrideApnsEnabled(ComponentName, boolean)
13940 */
13941 public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
13942 throwIfParentInstance("removeOverrideApn");
13943 if (mService != null) {
13944 try {
13945 return mService.removeOverrideApn(admin, apnId);
13946 } catch (RemoteException e) {
13947 throw e.rethrowFromSystemServer();
13948 }
13949 }
13950 return false;
13951 }
13952
13953 /**
13954 * Called by device owner or managed profile owner to get all override APNs inserted by
13955 * device owner or managed profile owner previously using {@link #addOverrideApn}.
13956 *
13957 * @param admin which {@link DeviceAdminReceiver} this request is associated with
13958 * @return A list of override APNs inserted by device owner.
13959 * @throws SecurityException if {@code admin} is not a device owner.
13960 *
13961 * @see #setOverrideApnsEnabled(ComponentName, boolean)
13962 */
13963 public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
13964 throwIfParentInstance("getOverrideApns");
13965 if (mService != null) {
13966 try {
13967 return mService.getOverrideApns(admin);
13968 } catch (RemoteException e) {
13969 throw e.rethrowFromSystemServer();
13970 }
13971 }
13972 return Collections.emptyList();
13973 }
13974
13975 /**
13976 * Called by device owner to set if override APNs should be enabled.
13977 * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
13978 * modified by the device owner. When enabled, only override APNs are in use, any other APNs
13979 * are ignored.
13980 * <p>Note: Enterprise APNs added by managed profile owners do not need to be enabled by
13981 * this API. They are part of the preferential network service config and is controlled by
13982 * {@link #setPreferentialNetworkServiceConfigs}.
13983 *
13984 * @param admin which {@link DeviceAdminReceiver} this request is associated with
13985 * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
13986 * @throws SecurityException if {@code admin} is not a device owner.
13987 */
13988 public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
13989 throwIfParentInstance("setOverrideApnEnabled");
13990 if (mService != null) {
13991 try {
13992 mService.setOverrideApnsEnabled(admin, enabled);
13993 } catch (RemoteException e) {
13994 throw e.rethrowFromSystemServer();
13995 }
13996 }
13997 }
13998
13999 /**
14000 * Called by device owner to check if override APNs are currently enabled.
14001 *
14002 * @param admin which {@link DeviceAdminReceiver} this request is associated with
14003 * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
14004 * @throws SecurityException if {@code admin} is not a device owner.
14005 *
14006 * @see #setOverrideApnsEnabled(ComponentName, boolean)
14007 */
14008 public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
14009 throwIfParentInstance("isOverrideApnEnabled");
14010 if (mService != null) {
14011 try {
14012 return mService.isOverrideApnEnabled(admin);
14013 } catch (RemoteException e) {
14014 throw e.rethrowFromSystemServer();
14015 }
14016 }
14017 return false;
14018 }
14019
14020 /**
14021 * Returns the data passed from the current administrator to the new administrator during an
14022 * ownership transfer. This is the same {@code bundle} passed in
14023 * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
14024 * persisted until the profile owner or device owner is removed.
14025 *
14026 * <p>This is the same <code>bundle</code> received in the
14027 * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
14028 * Use this method to retrieve it after the transfer as long as the new administrator is the
14029 * active device or profile owner.
14030 *
14031 * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
14032 *
14033 * @see #transferOwnership
14034 * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
14035 * @throws SecurityException if the caller is not a device or profile owner.
14036 */
14037 @Nullable
14038 public PersistableBundle getTransferOwnershipBundle() {
14039 throwIfParentInstance("getTransferOwnershipBundle");
14040 try {
14041 return mService.getTransferOwnershipBundle();
14042 } catch (RemoteException re) {
14043 throw re.rethrowFromSystemServer();
14044 }
14045 }
14046
14047 /**
14048 * Sets the global Private DNS mode to opportunistic.
14049 * May only be called by the device owner.
14050 *
14051 * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
14052 * resolver prior to attempting name resolution in cleartext.
14053 *
14054 * <p>Note: The device owner won't be able to set the global private DNS mode if there are
14055 * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
14056 * ids are set for new users as soon as possible after provisioning via
14057 * {@link #setAffiliationIds}.
14058 *
14059 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14060 *
14061 * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
14062 * {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
14063 *
14064 * @throws SecurityException if the caller is not the device owner.
14065 */
14066 public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
14067 @NonNull ComponentName admin) {
14068 throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
14069
14070 if (mService == null) {
14071 return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
14072 }
14073
14074 try {
14075 return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
14076 } catch (RemoteException re) {
14077 throw re.rethrowFromSystemServer();
14078 }
14079 }
14080
14081 /**
14082 * Sets the global Private DNS host to be used.
14083 * May only be called by the device owner.
14084 *
14085 * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
14086 * to ensure it is valid. Because of that, the method should not be called on any thread that
14087 * relates to user interaction, such as the UI thread.
14088 *
14089 * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
14090 * must be reachable both from within and outside the VPN. Otherwise, the device may lose
14091 * the ability to resolve hostnames as system traffic to the resolver may not go through the
14092 * VPN.
14093 *
14094 * <p>Note: The device owner won't be able to set the global private DNS mode if there are
14095 * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
14096 * ids are set for new users as soon as possible after provisioning via
14097 * {@link #setAffiliationIds}.
14098 *
14099 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14100 * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
14101 *
14102 * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
14103 * {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
14104 * {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
14105 * implement RFC7858.
14106 *
14107 * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
14108 *
14109 * @throws SecurityException if the caller is not the device owner.
14110 */
14111 @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
14112 @NonNull ComponentName admin, @NonNull String privateDnsHost) {
14113 throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
14114 Objects.requireNonNull(privateDnsHost, "dns resolver is null");
14115
14116 if (mService == null) {
14117 return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
14118 }
14119
14120 if (NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
14121 if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
14122 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
14123 }
14124 }
14125
14126 try {
14127 return mService.setGlobalPrivateDns(
14128 admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
14129 } catch (RemoteException re) {
14130 throw re.rethrowFromSystemServer();
14131 }
14132 }
14133
14134 /**
14135 * Called by device owner or profile owner of an organization-owned managed profile to install
14136 * a system update from the given file. The device will be
14137 * rebooted in order to finish installing the update. Note that if the device is rebooted, this
14138 * doesn't necessarily mean that the update has been applied successfully. The caller should
14139 * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
14140 * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
14141 * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
14142 * sufficient battery level, the installation will fail with error {@link
14143 * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
14144 *
14145 * @param admin The {@link DeviceAdminReceiver} that this request is associated with.
14146 * @param updateFilePath An Uri of the file that contains the update. The file should be
14147 * readable by the calling app.
14148 * @param executor The executor through which the callback should be invoked.
14149 * @param callback A callback object that will inform the caller when installing an update
14150 * fails.
14151 */
14152 public void installSystemUpdate(
14153 @NonNull ComponentName admin, @NonNull Uri updateFilePath,
14154 @NonNull @CallbackExecutor Executor executor,
14155 @NonNull InstallSystemUpdateCallback callback) {
14156 throwIfParentInstance("installUpdate");
14157 if (mService == null) {
14158 return;
14159 }
14160 try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
14161 .openFileDescriptor(updateFilePath, "r")) {
14162 mService.installUpdateFromFile(
14163 admin, fileDescriptor, new StartInstallingUpdateCallback.Stub() {
14164 @Override
14165 public void onStartInstallingUpdateError(
14166 int errorCode, String errorMessage) {
14167 executeCallback(errorCode, errorMessage, executor, callback);
14168 }
14169 });
14170 } catch (RemoteException e) {
14171 throw e.rethrowFromSystemServer();
14172 } catch (FileNotFoundException e) {
14173 Log.w(TAG, e);
14174 executeCallback(
14175 InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
14176 Log.getStackTraceString(e),
14177 executor, callback);
14178 } catch (IOException e) {
14179 Log.w(TAG, e);
14180 executeCallback(
14181 InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
14182 executor, callback);
14183 }
14184 }
14185
14186 private void executeCallback(int errorCode, String errorMessage,
14187 @NonNull @CallbackExecutor Executor executor,
14188 @NonNull InstallSystemUpdateCallback callback) {
14189 executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
14190 }
14191
14192 /**
14193 * Returns the system-wide Private DNS mode.
14194 *
14195 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14196 * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
14197 * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
14198 * @throws SecurityException if the caller is not the device owner.
14199 */
14200 public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
14201 throwIfParentInstance("setGlobalPrivateDns");
14202 if (mService == null) {
14203 return PRIVATE_DNS_MODE_UNKNOWN;
14204 }
14205
14206 try {
14207 return mService.getGlobalPrivateDnsMode(admin);
14208 } catch (RemoteException re) {
14209 throw re.rethrowFromSystemServer();
14210 }
14211 }
14212
14213 /**
14214 * Returns the system-wide Private DNS host.
14215 *
14216 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14217 * @return The hostname used for Private DNS queries, null if none is set.
14218 * @throws SecurityException if the caller is not the device owner.
14219 */
14220 public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
14221 throwIfParentInstance("setGlobalPrivateDns");
14222 if (mService == null) {
14223 return null;
14224 }
14225
14226 try {
14227 return mService.getGlobalPrivateDnsHost(admin);
14228 } catch (RemoteException re) {
14229 throw re.rethrowFromSystemServer();
14230 }
14231 }
14232
14233 /**
14234 * Deprecated. Use {@code markProfileOwnerOnOrganizationOwnedDevice} instead.
14235 * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#Q} or
14236 * below, will behave the same as {@link #setProfileOwnerOnOrganizationOwnedDevice}.
14237 *
14238 * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#R}
14239 * or above, will throw an UnsupportedOperationException when called.
14240 *
14241 * @deprecated Use {@link #setProfileOwnerOnOrganizationOwnedDevice} instead.
14242 *
14243 * @hide
14244 */
14245 @Deprecated
14246 @SystemApi
14247 @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
14248 conditional = true)
14249 public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
14250 ApplicationInfo ai = mContext.getApplicationInfo();
14251 if (ai.targetSdkVersion > Build.VERSION_CODES.Q) {
14252 throw new UnsupportedOperationException(
14253 "This method is deprecated. use markProfileOwnerOnOrganizationOwnedDevice"
14254 + " instead.");
14255 } else {
14256 setProfileOwnerOnOrganizationOwnedDevice(who, true);
14257 }
14258 }
14259
14260 /**
14261 * Sets whether the profile owner of the given user as managing an organization-owned device.
14262 * Managing an organization-owned device will give it access to device identifiers (such as
14263 * serial number, IMEI and MEID) as well as other privileges.
14264 *
14265 * @hide
14266 */
14267 @TestApi
14268 @RequiresPermission(anyOf = {
14269 android.Manifest.permission.MARK_DEVICE_ORGANIZATION_OWNED,
14270 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
14271 }, conditional = true)
14272 public void setProfileOwnerOnOrganizationOwnedDevice(@NonNull ComponentName who,
14273 boolean isProfileOwnerOnOrganizationOwnedDevice) {
14274 if (mService == null) {
14275 return;
14276 }
14277 try {
14278 mService.setProfileOwnerOnOrganizationOwnedDevice(who, myUserId(),
14279 isProfileOwnerOnOrganizationOwnedDevice);
14280 } catch (RemoteException re) {
14281 throw re.rethrowFromSystemServer();
14282 }
14283 }
14284
14285 /**
14286 * Allows a set of packages to access cross-profile calendar APIs.
14287 *
14288 * <p>Called by a profile owner of a managed profile.
14289 *
14290 * <p>Calling with a {@code null} value for the set disables the restriction so that all
14291 * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
14292 * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
14293 * called, no package is allowed to access cross-profile calendar APIs by default.
14294 *
14295 * @param admin which {@link DeviceAdminReceiver} this request is associated with
14296 * @param packageNames set of packages to be allowlisted
14297 * @throws SecurityException if {@code admin} is not a profile owner
14298 *
14299 * @see #getCrossProfileCalendarPackages(ComponentName)
14300 */
14301 public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
14302 @Nullable Set<String> packageNames) {
14303 throwIfParentInstance("setCrossProfileCalendarPackages");
14304 if (mService != null) {
14305 try {
14306 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
14307 : new ArrayList<>(packageNames));
14308 } catch (RemoteException e) {
14309 throw e.rethrowFromSystemServer();
14310 }
14311 }
14312 }
14313
14314 /**
14315 * Gets a set of package names that are allowed to access cross-profile calendar APIs.
14316 *
14317 * <p>Called by a profile owner of a managed profile.
14318 *
14319 * @param admin which {@link DeviceAdminReceiver} this request is associated with
14320 * @return the set of names of packages that were previously allowed via
14321 * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
14322 * empty set if none have been allowed
14323 * @throws SecurityException if {@code admin} is not a profile owner
14324 *
14325 * @see #setCrossProfileCalendarPackages(ComponentName, Set)
14326 */
14327 public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
14328 throwIfParentInstance("getCrossProfileCalendarPackages");
14329 if (mService != null) {
14330 try {
14331 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
14332 return packageNames == null ? null : new ArraySet<>(packageNames);
14333 } catch (RemoteException e) {
14334 throw e.rethrowFromSystemServer();
14335 }
14336 }
14337 return Collections.emptySet();
14338 }
14339
14340 /**
14341 * Returns if a package is allowed to access cross-profile calendar APIs.
14342 *
14343 * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
14344 * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
14345 * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
14346 * is turned on in the managed profile.
14347 *
14348 * <p>To query for a specific user, use
14349 * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
14350 * that user, and get a {@link DevicePolicyManager} from this context.
14351 *
14352 * @param packageName the name of the package
14353 * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
14354 * {@code false} otherwise
14355 *
14356 * @see #setCrossProfileCalendarPackages(ComponentName, Set)
14357 * @see #getCrossProfileCalendarPackages(ComponentName)
14358 * @hide
14359 */
14360 @RequiresPermission(anyOf = {
14361 permission.INTERACT_ACROSS_USERS_FULL,
14362 permission.INTERACT_ACROSS_USERS
14363 }, conditional = true)
14364 public boolean isPackageAllowedToAccessCalendar(@NonNull String packageName) {
14365 throwIfParentInstance("isPackageAllowedToAccessCalendar");
14366 if (mService != null) {
14367 try {
14368 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
14369 myUserId());
14370 } catch (RemoteException e) {
14371 throw e.rethrowFromSystemServer();
14372 }
14373 }
14374 return false;
14375 }
14376
14377 /**
14378 * Gets a set of package names that are allowed to access cross-profile calendar APIs.
14379 *
14380 * <p>To query for a specific user, use
14381 * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
14382 * that user, and get a {@link DevicePolicyManager} from this context.
14383 *
14384 * @return the set of names of packages that were previously allowed via
14385 * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
14386 * empty set if none have been allowed
14387 *
14388 * @see #setCrossProfileCalendarPackages(ComponentName, Set)
14389 * @see #getCrossProfileCalendarPackages(ComponentName)
14390 * @hide
14391 */
14392 @RequiresPermission(anyOf = {
14393 permission.INTERACT_ACROSS_USERS_FULL,
14394 permission.INTERACT_ACROSS_USERS
14395 })
14396 public @Nullable Set<String> getCrossProfileCalendarPackages() {
14397 throwIfParentInstance("getCrossProfileCalendarPackages");
14398 if (mService != null) {
14399 try {
14400 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
14401 myUserId());
14402 return packageNames == null ? null : new ArraySet<>(packageNames);
14403 } catch (RemoteException e) {
14404 throw e.rethrowFromSystemServer();
14405 }
14406 }
14407 return Collections.emptySet();
14408 }
14409
14410 /**
14411 * Sets the set of admin-allowlisted package names that are allowed to request user consent for
14412 * cross-profile communication.
14413 *
14414 * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
14415 *
14416 * <p>Previous calls are overridden by each subsequent call to this method.
14417 *
14418 * <p>Note that other apps may be able to request user consent for cross-profile communication
14419 * if they have been explicitly allowlisted by the OEM.
14420 *
14421 * <p>When previously-set cross-profile packages are missing from {@code packageNames}, the
14422 * app-op for {@code INTERACT_ACROSS_PROFILES} will be reset for those packages. This will not
14423 * occur for packages that are allowlisted by the OEM.
14424 *
14425 * @param admin the {@link DeviceAdminReceiver} this request is associated with
14426 * @param packageNames the new cross-profile package names
14427 */
14428 public void setCrossProfilePackages(
14429 @NonNull ComponentName admin, @NonNull Set<String> packageNames) {
14430 throwIfParentInstance("setCrossProfilePackages");
14431 if (mService != null) {
14432 try {
14433 mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames));
14434 } catch (RemoteException e) {
14435 throw e.rethrowFromSystemServer();
14436 }
14437 }
14438 }
14439
14440 /**
14441 * Returns the set of package names that the admin has previously set as allowed to request user
14442 * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
14443 * Set)}.
14444 *
14445 * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
14446 *
14447 * <p>Note that other apps not included in the returned set may be able to request user consent
14448 * for cross-profile communication if they have been explicitly allowlisted by the OEM.
14449 *
14450 * @param admin the {@link DeviceAdminReceiver} this request is associated with
14451 * @return the set of package names the admin has previously set as allowed to request user
14452 * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
14453 * Set)}
14454 */
14455 public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) {
14456 throwIfParentInstance("getCrossProfilePackages");
14457 if (mService != null) {
14458 try {
14459 return new ArraySet<>(mService.getCrossProfilePackages(admin));
14460 } catch (RemoteException e) {
14461 throw e.rethrowFromSystemServer();
14462 }
14463 }
14464 return Collections.emptySet();
14465 }
14466
14467 /**
14468 * Returns the combined set of the following:
14469 * <ul>
14470 * <li>The package names that the admin has previously set as allowed to request user consent
14471 * for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
14472 * Set)}.</li>
14473 * <li>The default package names set by the OEM that are allowed to request user consent for
14474 * cross-profile communication without being explicitly enabled by the admin, via {@link
14475 * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
14476 * #vendor_cross_profile_apps}.</li>
14477 * </ul>
14478 *
14479 * @return the combined set of allowlisted package names set via
14480 * {@link #setCrossProfilePackages(ComponentName, Set)}, {@link com.android.internal.R.array
14481 * #cross_profile_apps}, and {@link com.android.internal.R.array#vendor_cross_profile_apps}.
14482 *
14483 * @hide
14484 */
14485 @RequiresPermission(anyOf = {
14486 permission.INTERACT_ACROSS_USERS_FULL,
14487 permission.INTERACT_ACROSS_USERS,
14488 permission.INTERACT_ACROSS_PROFILES
14489 })
14490 public @NonNull Set<String> getAllCrossProfilePackages() {
14491 throwIfParentInstance("getAllCrossProfilePackages");
14492 if (mService != null) {
14493 try {
14494 return new ArraySet<>(mService.getAllCrossProfilePackages());
14495 } catch (RemoteException e) {
14496 throw e.rethrowFromSystemServer();
14497 }
14498 }
14499 return Collections.emptySet();
14500 }
14501
14502 /**
14503 * Returns the default package names set by the OEM that are allowed to communicate
14504 * cross-profile without being explicitly enabled by the admin, via {@link
14505 * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
14506 * #vendor_cross_profile_apps}.
14507 *
14508 * @hide
14509 */
14510 @TestApi
14511 public @NonNull Set<String> getDefaultCrossProfilePackages() {
14512 throwIfParentInstance("getDefaultCrossProfilePackages");
14513 if (mService != null) {
14514 try {
14515 return new ArraySet<>(mService.getDefaultCrossProfilePackages());
14516 } catch (RemoteException e) {
14517 throw e.rethrowFromSystemServer();
14518 }
14519 }
14520 return Collections.emptySet();
14521 }
14522
14523 /**
14524 * Returns whether the device is being used as a managed kiosk. These requirements are as
14525 * follows:
14526 * <ul>
14527 * <li>The device is in Lock Task (therefore there is also a Device Owner app on the
14528 * device)</li>
14529 * <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
14530 * not enabled, so the system info in the status bar is not visible</li>
14531 * <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
14532 * swipe-to-unlock)</li>
14533 * <li>The device is not in the middle of an ephemeral user session</li>
14534 * </ul>
14535 *
14536 * <p>Publicly-accessible dedicated devices don't have the same privacy model as
14537 * personally-used devices. In particular, user consent popups don't make sense as a barrier to
14538 * accessing persistent data on these devices since the user giving consent and the user whose
14539 * data is on the device are unlikely to be the same. These consent popups prevent the true
14540 * remote management of these devices.
14541 *
14542 * <p>This condition is not sufficient to cover APIs that would access data that only lives for
14543 * the duration of the user's session, since the user has an expectation of privacy in these
14544 * conditions that more closely resembles use of a personal device. In those cases, see {@link
14545 * #isUnattendedManagedKiosk()}.
14546 *
14547 * @hide
14548 */
14549 @SystemApi
14550 @RequiresPermission(anyOf = {
14551 android.Manifest.permission.MANAGE_USERS,
14552 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
14553 })
14554 public boolean isManagedKiosk() {
14555 throwIfParentInstance("isManagedKiosk");
14556 if (mService != null) {
14557 try {
14558 return mService.isManagedKiosk();
14559 } catch (RemoteException e) {
14560 throw e.rethrowFromSystemServer();
14561 }
14562 }
14563 return false;
14564 }
14565
14566 /**
14567 * Returns whether the device is being used as an unattended managed kiosk. These requirements
14568 * are as follows:
14569 * <ul>
14570 * <li>The device is being used as a managed kiosk, as defined at {@link
14571 * #isManagedKiosk()}</li>
14572 * <li>The device has not received user input for at least 30 minutes</li>
14573 * </ul>
14574 *
14575 * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
14576 * ensures that the device hasn't been interacted with recently, making it an appropriate check
14577 * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
14578 *
14579 * @hide
14580 */
14581 @SystemApi
14582 @RequiresPermission(anyOf = {
14583 android.Manifest.permission.MANAGE_USERS,
14584 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
14585 })
14586 public boolean isUnattendedManagedKiosk() {
14587 throwIfParentInstance("isUnattendedManagedKiosk");
14588 if (mService != null) {
14589 try {
14590 return mService.isUnattendedManagedKiosk();
14591 } catch (RemoteException e) {
14592 throw e.rethrowFromSystemServer();
14593 }
14594 }
14595 return false;
14596 }
14597
14598 /**
14599 * Starts an activity to view calendar events in the managed profile.
14600 *
14601 * @param eventId the id of the event to be viewed
14602 * @param start the start time of the event
14603 * @param end the end time of the event
14604 * @param allDay if the event is an all-day event
14605 * @param flags flags to be set for the intent
14606 * @return {@code true} if the activity is started successfully, {@code false} otherwise
14607 *
14608 * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
14609 * long, boolean, int)
14610 *
14611 * @hide
14612 */
14613 public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
14614 boolean allDay, int flags) {
14615 throwIfParentInstance("startViewCalendarEventInManagedProfile");
14616 if (mService != null) {
14617 try {
14618 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
14619 eventId, start, end, allDay, flags);
14620 } catch (RemoteException e) {
14621 throw e.rethrowFromSystemServer();
14622 }
14623 }
14624 return false;
14625 }
14626
14627 /**
14628 * Called by a device owner or a profile owner to disable user control over apps. User will not
14629 * be able to clear app data or force-stop packages. When called by a device owner, applies to
14630 * all users on the device.
14631 *
14632 * @param admin which {@link DeviceAdminReceiver} this request is associated with
14633 * @param packages The package names for the apps.
14634 * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
14635 */
14636 public void setUserControlDisabledPackages(@NonNull ComponentName admin,
14637 @NonNull List<String> packages) {
14638 throwIfParentInstance("setUserControlDisabledPackages");
14639 if (mService != null) {
14640 try {
14641 mService.setUserControlDisabledPackages(admin, packages);
14642 } catch (RemoteException re) {
14643 throw re.rethrowFromSystemServer();
14644 }
14645 }
14646 }
14647
14648 /**
14649 * Returns the list of packages over which user control is disabled by a device or profile
14650 * owner.
14651 *
14652 * @param admin which {@link DeviceAdminReceiver} this request is associated with
14653 * @throws SecurityException if {@code admin} is not a device or profile owner.
14654 */
14655 @NonNull
14656 public List<String> getUserControlDisabledPackages(@NonNull ComponentName admin) {
14657 throwIfParentInstance("getUserControlDisabledPackages");
14658 if (mService != null) {
14659 try {
14660 return mService.getUserControlDisabledPackages(admin);
14661 } catch (RemoteException re) {
14662 throw re.rethrowFromSystemServer();
14663 }
14664 }
14665 return Collections.emptyList();
14666 }
14667
14668 /**
14669 * Called by device owner or profile owner of an organization-owned managed profile to toggle
14670 * Common Criteria mode for the device. When the device is in Common Criteria mode,
14671 * certain device functionalities are tuned to meet the higher
14672 * security level required by Common Criteria certification. For example:
14673 * <ul>
14674 * <li> Bluetooth long term key material is additionally integrity-protected with AES-GCM. </li>
14675 * <li> WiFi configuration store is additionally integrity-protected with AES-GCM. </li>
14676 * </ul>
14677 * Common Criteria mode is disabled by default.
14678 *
14679 * <p><em>Note:</em> if Common Critera mode is turned off after being enabled previously,
14680 * all existing WiFi configurations will be lost.
14681 *
14682 * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14683 * @param enabled whether Common Criteria mode should be enabled or not.
14684 */
14685 public void setCommonCriteriaModeEnabled(@NonNull ComponentName admin, boolean enabled) {
14686 throwIfParentInstance("setCommonCriteriaModeEnabled");
14687 if (mService != null) {
14688 try {
14689 mService.setCommonCriteriaModeEnabled(admin, enabled);
14690 } catch (RemoteException e) {
14691 throw e.rethrowFromSystemServer();
14692 }
14693 }
14694 }
14695
14696 /**
14697 * Returns whether Common Criteria mode is currently enabled. Device owner and profile owner of
14698 * an organization-owned managed profile can query its own Common Criteria mode setting by
14699 * calling this method with its admin {@link ComponentName}. Any caller can obtain the
14700 * aggregated device-wide Common Criteria mode state by passing {@code null} as the
14701 * {@code admin} argument.
14702 *
14703 * @param admin which {@link DeviceAdminReceiver} this request is associated with, or
14704 * {@code null} if the caller is not a device admin.
14705 * @return {@code true} if Common Criteria mode is enabled, {@code false} otherwise.
14706 */
14707 public boolean isCommonCriteriaModeEnabled(@Nullable ComponentName admin) {
14708 throwIfParentInstance("isCommonCriteriaModeEnabled");
14709 if (mService != null) {
14710 try {
14711 return mService.isCommonCriteriaModeEnabled(admin);
14712 } catch (RemoteException e) {
14713 throw e.rethrowFromSystemServer();
14714 }
14715 }
14716 return false;
14717 }
14718
14719 /**
14720 * Called by profile owner of an organization-owned managed profile to check whether
14721 * personal apps are suspended.
14722 *
14723 * @return a bitmask of reasons for personal apps suspension or
14724 * {@link #PERSONAL_APPS_NOT_SUSPENDED} if apps are not suspended.
14725 * @see #setPersonalAppsSuspended
14726 */
14727 public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(
14728 @NonNull ComponentName admin) {
14729 throwIfParentInstance("getPersonalAppsSuspendedReasons");
14730 if (mService != null) {
14731 try {
14732 return mService.getPersonalAppsSuspendedReasons(admin);
14733 } catch (RemoteException re) {
14734 throw re.rethrowFromSystemServer();
14735 }
14736 }
14737 return 0;
14738 }
14739
14740 /**
14741 * Called by a profile owner of an organization-owned managed profile to suspend personal
14742 * apps on the device. When personal apps are suspended the device can only be used for calls.
14743 *
14744 * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
14745 * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
14746 * in the profile owner package. Profile owner implementation that uses personal apps suspension
14747 * must handle this intent.
14748 *
14749 * @param admin Which {@link DeviceAdminReceiver} this request is associated with
14750 * @param suspended Whether personal apps should be suspended.
14751 * @throws IllegalStateException if the profile owner doesn't have an activity that handles
14752 * {@link #ACTION_CHECK_POLICY_COMPLIANCE}
14753 */
14754 public void setPersonalAppsSuspended(@NonNull ComponentName admin, boolean suspended) {
14755 throwIfParentInstance("setPersonalAppsSuspended");
14756 if (mService != null) {
14757 try {
14758 mService.setPersonalAppsSuspended(admin, suspended);
14759 } catch (RemoteException re) {
14760 throw re.rethrowFromSystemServer();
14761 }
14762 }
14763 }
14764
14765 /**
14766 * Called by a profile owner of an organization-owned managed profile to set maximum time
14767 * the profile is allowed to be turned off. If the profile is turned off for longer, personal
14768 * apps are suspended on the device.
14769 *
14770 * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
14771 * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
14772 * in the profile owner package. Profile owner implementation that uses personal apps suspension
14773 * must handle this intent.
14774 *
14775 * @param admin Which {@link DeviceAdminReceiver} this request is associated with
14776 * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if
14777 * not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a
14778 * smaller non-zero vaulue, 72 hours will be set instead.
14779 * @throws IllegalStateException if the profile owner doesn't have an activity that handles
14780 * {@link #ACTION_CHECK_POLICY_COMPLIANCE}
14781 * @see #setPersonalAppsSuspended
14782 */
14783 public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) {
14784 throwIfParentInstance("setManagedProfileMaximumTimeOff");
14785 if (mService != null) {
14786 try {
14787 mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis);
14788 } catch (RemoteException re) {
14789 throw re.rethrowFromSystemServer();
14790 }
14791 }
14792 }
14793
14794 /**
14795 * Called by a profile owner of an organization-owned managed profile to get maximum time
14796 * the profile is allowed to be turned off.
14797 *
14798 * @param admin Which {@link DeviceAdminReceiver} this request is associated with
14799 * @return Maximum time the profile is allowed to be off in milliseconds or 0 if not limited.
14800 * @see #setPersonalAppsSuspended
14801 */
14802 public long getManagedProfileMaximumTimeOff(@NonNull ComponentName admin) {
14803 throwIfParentInstance("getManagedProfileMaximumTimeOff");
14804 if (mService != null) {
14805 try {
14806 return mService.getManagedProfileMaximumTimeOff(admin);
14807 } catch (RemoteException re) {
14808 throw re.rethrowFromSystemServer();
14809 }
14810 }
14811 return 0;
14812 }
14813
14814 /**
14815 * Called by a profile owner of an organization-owned managed profile to acknowledge that the
14816 * device is compliant and the user can turn the profile off if needed according to the maximum
14817 * time off policy.
14818 *
14819 * This method should be called when the device is deemed compliant after getting
14820 * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback in
14821 * case it is overridden. Before this method is called the user is still free to turn the
14822 * profile off, but the timer won't be reset, so personal apps will be suspended sooner.
14823 *
14824 * DPCs only need acknowledging device compliance if they override
14825 * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)}, otherwise
14826 * compliance is acknowledged automatically.
14827 *
14828 * @throws IllegalStateException if the user isn't unlocked
14829 * @see #isComplianceAcknowledgementRequired()
14830 * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
14831 * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
14832 */
14833 public void acknowledgeDeviceCompliant() {
14834 throwIfParentInstance("acknowledgeDeviceCompliant");
14835 if (mService != null) {
14836 try {
14837 mService.acknowledgeDeviceCompliant();
14838 } catch (RemoteException re) {
14839 throw re.rethrowFromSystemServer();
14840 }
14841 }
14842 }
14843
14844 /**
14845 * Called by a profile owner of an organization-owned managed profile to query whether it needs
14846 * to acknowledge device compliance to allow the user to turn the profile off if needed
14847 * according to the maximum profile time off policy.
14848 *
14849 * Normally when acknowledgement is needed the DPC gets a
14850 * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback.
14851 * But if the callback was not delivered or handled for some reason, this method can be used to
14852 * verify if acknowledgement is needed.
14853 *
14854 * @throws IllegalStateException if the user isn't unlocked
14855 * @see #acknowledgeDeviceCompliant()
14856 * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
14857 * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
14858 */
14859 public boolean isComplianceAcknowledgementRequired() {
14860 throwIfParentInstance("isComplianceAcknowledgementRequired");
14861 if (mService != null) {
14862 try {
14863 return mService.isComplianceAcknowledgementRequired();
14864 } catch (RemoteException re) {
14865 throw re.rethrowFromSystemServer();
14866 }
14867 }
14868 return false;
14869 }
14870
14871 /**
14872 * Returns {@code true} when {@code userId} has a profile owner that is capable of resetting
14873 * password in RUNNING_LOCKED state. For that it should have at least one direct boot aware
14874 * component and have an active password reset token. Can only be called by the system.
14875 * @hide
14876 */
14877 public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
14878 if (mService != null) {
14879 try {
14880 return mService.canProfileOwnerResetPasswordWhenLocked(userId);
14881 } catch (RemoteException re) {
14882 throw re.rethrowFromSystemServer();
14883 }
14884 }
14885 return false;
14886 }
14887
14888 /**
14889 * Used by CTS to set the result of the next safety operation check.
14890 *
14891 * @hide
14892 */
14893 @TestApi
14894 @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
14895 public void setNextOperationSafety(@DevicePolicyOperation int operation,
14896 @OperationSafetyReason int reason) {
14897 if (mService != null) {
14898 try {
14899 mService.setNextOperationSafety(operation, reason);
14900 } catch (RemoteException re) {
14901 throw re.rethrowFromSystemServer();
14902 }
14903 }
14904 }
14905
14906 /**
14907 * Returns an enrollment-specific identifier of this device, which is guaranteed to be the same
14908 * value for the same device, enrolled into the same organization by the same managing app.
14909 * This identifier is high-entropy, useful for uniquely identifying individual devices within
14910 * the same organisation.
14911 * It is available both in a work profile and on a fully-managed device.
14912 * The identifier would be consistent even if the work profile is removed and enrolled again
14913 * (to the same organization), or the device is factory reset and re-enrolled.
14914 *
14915 * Can only be called by the Profile Owner or Device Owner, if the
14916 * {@link #setOrganizationId(String)} was previously called.
14917 * If {@link #setOrganizationId(String)} was not called, then the returned value will be an
14918 * empty string.
14919 *
14920 * <p>Note about access to device identifiers: a device owner, a profile owner of an
14921 * organization-owned device or the delegated certificate installer (holding the
14922 * {@link #DELEGATION_CERT_INSTALL} delegation) on such a device can still obtain hardware
14923 * identifiers by calling e.g. {@link android.os.Build#getSerial()}, in addition to using
14924 * this method. However, a profile owner on a personal (non organization-owned) device, or the
14925 * delegated certificate installer on such a device, cannot obtain hardware identifiers anymore
14926 * and must switch to using this method.
14927 *
14928 * @return A stable, enrollment-specific identifier.
14929 * @throws SecurityException if the caller is not a profile owner or device owner.
14930 */
14931 @NonNull public String getEnrollmentSpecificId() {
14932 throwIfParentInstance("getEnrollmentSpecificId");
14933 if (mService == null) {
14934 return "";
14935 }
14936
14937 try {
14938 return mService.getEnrollmentSpecificId(mContext.getPackageName());
14939 } catch (RemoteException re) {
14940 throw re.rethrowFromSystemServer();
14941 }
14942 }
14943
14944 /**
14945 * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
14946 * generating an enrollment-specific ID for the device, see {@link #getEnrollmentSpecificId()}.
14947 *
14948 * It is recommended that the Enterprise ID is at least 6 characters long, and no more than
14949 * 64 characters.
14950 *
14951 * @param enterpriseId An identifier of the organization this work profile or device is
14952 * enrolled into.
14953 */
14954 public void setOrganizationId(@NonNull String enterpriseId) {
14955 throwIfParentInstance("setOrganizationId");
14956 setOrganizationIdForUser(mContext.getPackageName(), enterpriseId, myUserId());
14957 }
14958
14959 /**
14960 * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
14961 * generating an enrollment-specific ID for the device, see
14962 * {@link #getEnrollmentSpecificId()}.
14963 *
14964 * @hide
14965 */
14966 public void setOrganizationIdForUser(@NonNull String packageName,
14967 @NonNull String enterpriseId, @UserIdInt int userId) {
14968 if (mService == null) {
14969 return;
14970 }
14971 try {
14972 mService.setOrganizationIdForUser(packageName, enterpriseId, userId);
14973 } catch (RemoteException re) {
14974 throw re.rethrowFromSystemServer();
14975 }
14976 }
14977
14978 /**
14979 * Clears organization ID set by the DPC and resets the precomputed enrollment specific ID.
14980 * @hide
14981 */
14982 @TestApi
14983 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
14984 public void clearOrganizationId() {
14985 if (mService == null) {
14986 return;
14987 }
14988 try {
14989 mService.clearOrganizationIdForUser(myUserId());
14990 } catch (RemoteException re) {
14991 throw re.rethrowFromSystemServer();
14992 }
14993 }
14994
14995 /**
14996 * Creates and provisions a managed profile and sets the
14997 * {@link ManagedProfileProvisioningParams#getProfileAdminComponentName()} as the profile
14998 * owner.
14999 *
15000 * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK}
15001 * before calling this method.
15002 *
15003 * @param provisioningParams Params required to provision a managed profile,
15004 * see {@link ManagedProfileProvisioningParams}.
15005 * @return The {@link UserHandle} of the created profile or {@code null} if the service is
15006 * not available.
15007 * @throws SecurityException if the caller does not hold
15008 * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
15009 * @throws ProvisioningException if an error occurred during provisioning.
15010 * @hide
15011 */
15012 @Nullable
15013 @SystemApi
15014 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
15015 public UserHandle createAndProvisionManagedProfile(
15016 @NonNull ManagedProfileProvisioningParams provisioningParams)
15017 throws ProvisioningException {
15018 if (mService == null) {
15019 return null;
15020 }
15021 try {
15022 return mService.createAndProvisionManagedProfile(
15023 provisioningParams, mContext.getPackageName());
15024 } catch (ServiceSpecificException e) {
15025 throw new ProvisioningException(e, e.errorCode, getErrorMessage(e));
15026 } catch (RemoteException e) {
15027 throw e.rethrowFromSystemServer();
15028 }
15029 }
15030
15031 /**
15032 * Called when a managed profile has been provisioned.
15033 *
15034 * @throws SecurityException if the caller does not hold
15035 * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
15036 * @hide
15037 */
15038 @SystemApi
15039 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
15040 public void finalizeWorkProfileProvisioning(
15041 @NonNull UserHandle managedProfileUser, @Nullable Account migratedAccount) {
15042 Objects.requireNonNull(managedProfileUser, "managedProfileUser can't be null");
15043 if (mService == null) {
15044 throw new IllegalStateException("Could not find DevicePolicyManagerService");
15045 }
15046 try {
15047 mService.finalizeWorkProfileProvisioning(managedProfileUser, migratedAccount);
15048 } catch (RemoteException e) {
15049 throw e.rethrowFromSystemServer();
15050 }
15051 }
15052
15053 /**
15054 * The localized error message to show to the end-user. If {@code null}, a generic error
15055 * message will be shown.
15056 */
15057 private String getErrorMessage(ServiceSpecificException e) {
15058 return null;
15059 }
15060
15061
15062 /**
15063 * Provisions a managed device and sets the {@code deviceAdminComponentName} as the device
15064 * owner.
15065 *
15066 * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK}
15067 * before calling this method.
15068 *
15069 * <p>Holders of {@link android.Manifest.permission#PROVISION_DEMO_DEVICE} can call this API
15070 * only if {@link FullyManagedDeviceProvisioningParams#isDemoDevice()} is {@code true}.</p>
15071 *
15072 * @param provisioningParams Params required to provision a fully managed device,
15073 * see {@link FullyManagedDeviceProvisioningParams}.
15074 *
15075 * @throws ProvisioningException if an error occurred during provisioning.
15076 *
15077 * @hide
15078 */
15079 @SystemApi
15080 @RequiresPermission(anyOf = {
15081 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
15082 android.Manifest.permission.PROVISION_DEMO_DEVICE})
15083 public void provisionFullyManagedDevice(
15084 @NonNull FullyManagedDeviceProvisioningParams provisioningParams)
15085 throws ProvisioningException {
15086 if (mService != null) {
15087 try {
15088 mService.provisionFullyManagedDevice(provisioningParams, mContext.getPackageName());
15089 } catch (ServiceSpecificException e) {
15090 throw new ProvisioningException(e, e.errorCode, getErrorMessage(e));
15091 } catch (RemoteException re) {
15092 throw re.rethrowFromSystemServer();
15093 }
15094 }
15095 }
15096
15097 /**
15098 * Resets the default cross profile intent filters that were set during
15099 * {@link #createAndProvisionManagedProfile} between {@code userId} and all it's managed
15100 * profiles if any.
15101 *
15102 * @hide
15103 */
15104 @TestApi
15105 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
15106 public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
15107 if (mService != null) {
15108 try {
15109 mService.resetDefaultCrossProfileIntentFilters(userId);
15110 } catch (RemoteException re) {
15111 throw re.rethrowFromSystemServer();
15112 }
15113 }
15114 }
15115
15116 /**
15117 * Returns true if the caller is running on a device where the admin can grant
15118 * permissions related to device sensors.
15119 * This is a signal that the device is a fully-managed device where personal usage is
15120 * discouraged.
15121 * The list of permissions is listed in
15122 * {@link #setPermissionGrantState(ComponentName, String, String, int)}.
15123 *
15124 * May be called by any app.
15125 * @return true if the app can grant device sensors-related permissions, false otherwise.
15126 */
15127 public boolean canAdminGrantSensorsPermissions() {
15128 throwIfParentInstance("canAdminGrantSensorsPermissions");
15129 if (mService == null) {
15130 return false;
15131 }
15132 try {
15133 return mService.canAdminGrantSensorsPermissionsForUser(myUserId());
15134 } catch (RemoteException re) {
15135 throw re.rethrowFromSystemServer();
15136 }
15137 }
15138
15139 /**
15140 * Sets the device owner type for a managed device (e.g. financed device).
15141 *
15142 * @param admin The {@link DeviceAdminReceiver} that is the device owner.
15143 * @param deviceOwnerType The device owner type is set to. Use
15144 * {@link #DEVICE_OWNER_TYPE_DEFAULT} for the default device owner type. Use
15145 * {@link #DEVICE_OWNER_TYPE_FINANCED} for the financed device owner type.
15146 *
15147 * @throws IllegalStateException When admin is not the device owner, or there is no device
15148 * owner, or attempting to set the device owner type again for the same admin.
15149 * @throws SecurityException If the caller does not have the permission
15150 * {@link permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
15151 *
15152 * @hide
15153 */
15154 @TestApi
15155 public void setDeviceOwnerType(@NonNull ComponentName admin,
15156 @DeviceOwnerType int deviceOwnerType) {
15157 throwIfParentInstance("setDeviceOwnerType");
15158 if (mService != null) {
15159 try {
15160 mService.setDeviceOwnerType(admin, deviceOwnerType);
15161 } catch (RemoteException re) {
15162 throw re.rethrowFromSystemServer();
15163 }
15164 }
15165 }
15166
15167 /**
15168 * Returns the device owner type for the admin used in
15169 * {@link #setDeviceOwnerType(ComponentName, int)}. {@link #DEVICE_OWNER_TYPE_DEFAULT}
15170 * would be returned when the device owner type is not set for the device owner admin.
15171 *
15172 * @param admin The {@link DeviceAdminReceiver} that is the device owner.
15173 *
15174 * @throws IllegalStateException When admin is not the device owner or there is no device owner.
15175 *
15176 * @hide
15177 */
15178 @TestApi
15179 @DeviceOwnerType
15180 public int getDeviceOwnerType(@NonNull ComponentName admin) {
15181 throwIfParentInstance("getDeviceOwnerType");
15182 if (mService != null) {
15183 try {
15184 return mService.getDeviceOwnerType(admin);
15185 } catch (RemoteException re) {
15186 throw re.rethrowFromSystemServer();
15187 }
15188 }
15189 return DEVICE_OWNER_TYPE_DEFAULT;
15190 }
15191
15192 /**
15193 * Called by device owner or profile owner of an organization-owned managed profile to
15194 * enable or disable USB data signaling for the device. When disabled, USB data connections
15195 * (except from charging functions) are prohibited.
15196 *
15197 * <p> This API is not supported on all devices, the caller should call
15198 * {@link #canUsbDataSignalingBeDisabled()} to check whether enabling or disabling USB data
15199 * signaling is supported on the device.
15200 *
15201 * @param enabled whether USB data signaling should be enabled or not.
15202 * @throws SecurityException if the caller is not a device owner or a profile owner on
15203 * an organization-owned managed profile.
15204 * @throws IllegalStateException if disabling USB data signaling is not supported or
15205 * if USB data signaling fails to be enabled/disabled.
15206 */
15207 public void setUsbDataSignalingEnabled(boolean enabled) {
15208 throwIfParentInstance("setUsbDataSignalingEnabled");
15209 if (mService != null) {
15210 try {
15211 mService.setUsbDataSignalingEnabled(mContext.getPackageName(), enabled);
15212 } catch (RemoteException e) {
15213 throw e.rethrowFromSystemServer();
15214 }
15215 }
15216 }
15217
15218 /**
15219 * Returns whether USB data signaling is currently enabled.
15220 *
15221 * <p> When called by a device owner or profile owner of an organization-owned managed profile,
15222 * this API returns whether USB data signaling is currently enabled by that admin. When called
15223 * by any other app, returns whether USB data signaling is currently enabled on the device.
15224 *
15225 * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
15226 */
15227 public boolean isUsbDataSignalingEnabled() {
15228 throwIfParentInstance("isUsbDataSignalingEnabled");
15229 if (mService != null) {
15230 try {
15231 return mService.isUsbDataSignalingEnabled(mContext.getPackageName());
15232 } catch (RemoteException e) {
15233 throw e.rethrowFromSystemServer();
15234 }
15235 }
15236 return true;
15237 }
15238
15239 /**
15240 * Called by the system to check whether USB data signaling is currently enabled for this user.
15241 *
15242 * @param userId which user to check for.
15243 * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
15244 * @hide
15245 */
15246 public boolean isUsbDataSignalingEnabledForUser(@UserIdInt int userId) {
15247 throwIfParentInstance("isUsbDataSignalingEnabledForUser");
15248 if (mService != null) {
15249 try {
15250 return mService.isUsbDataSignalingEnabledForUser(userId);
15251 } catch (RemoteException e) {
15252 throw e.rethrowFromSystemServer();
15253 }
15254 }
15255 return true;
15256 }
15257
15258 /**
15259 * Returns whether enabling or disabling USB data signaling is supported on the device.
15260 *
15261 * @return {@code true} if the device supports enabling and disabling USB data signaling.
15262 */
15263 public boolean canUsbDataSignalingBeDisabled() {
15264 throwIfParentInstance("canUsbDataSignalingBeDisabled");
15265 if (mService != null) {
15266 try {
15267 return mService.canUsbDataSignalingBeDisabled();
15268 } catch (RemoteException re) {
15269 throw re.rethrowFromSystemServer();
15270 }
15271 }
15272 return false;
15273 }
15274
15275 /**
15276 * Gets the list of {@link #isAffiliatedUser() affiliated} users running on foreground.
15277 *
15278 * @return list of {@link #isAffiliatedUser() affiliated} users running on foreground.
15279 *
15280 * @throws SecurityException if the calling application is not a device owner
15281 */
15282 @NonNull
15283 public List<UserHandle> listForegroundAffiliatedUsers() {
15284 if (mService == null) return Collections.emptyList();
15285
15286 try {
15287 return mService.listForegroundAffiliatedUsers();
15288 } catch (RemoteException re) {
15289 throw re.rethrowFromSystemServer();
15290 }
15291 }
15292
15293 /**
15294 * Lists apps that are exempt from policies (such as
15295 * {@link #setPackagesSuspended(ComponentName, String[], boolean)}).
15296 *
15297 * @hide
15298 */
15299 @TestApi
15300 @RequiresPermission(value = android.Manifest.permission.MANAGE_DEVICE_ADMINS)
15301 public @NonNull Set<String> getPolicyExemptApps() {
15302 if (mService == null) return Collections.emptySet();
15303
15304 try {
15305 return new HashSet<>(mService.listPolicyExemptApps());
15306 } catch (RemoteException e) {
15307 throw e.rethrowFromSystemServer();
15308 }
15309 }
15310
15311 /**
15312 * Creates a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent
15313 * from the provided {@code nfcIntent}.
15314 *
15315 * <p>Prerequisites to create the provisioning intent:
15316 *
15317 * <ul>
15318 * <li>{@code nfcIntent}'s action is {@link NfcAdapter#ACTION_NDEF_DISCOVERED}</li>
15319 * <li>{@code nfcIntent}'s NFC properties contain either
15320 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} or
15321 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} </li>
15322 * </ul>
15323 *
15324 * This method returns {@code null} if the prerequisites are not met or if an error occurs
15325 * when reading the NFC properties.
15326 *
15327 * @param nfcIntent the nfc intent generated from scanning a NFC tag
15328 * @return a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent with
15329 * intent extras as read by {@code nfcIntent}'s NFC properties or {@code null} if the
15330 * prerequisites are not met or if an error occurs when reading the NFC properties.
15331 *
15332 * @hide
15333 */
15334 @Nullable
15335 @SystemApi
15336 public Intent createProvisioningIntentFromNfcIntent(@NonNull Intent nfcIntent) {
15337 return ProvisioningIntentHelper.createProvisioningIntentFromNfcIntent(nfcIntent);
15338 }
15339
15340 /**
15341 * Called by device owner or profile owner of an organization-owned managed profile to
15342 * specify the minimum security level required for Wi-Fi networks.
15343 * The device may not connect to networks that do not meet the minimum security level.
15344 * If the current network does not meet the minimum security level set, it will be disconnected.
15345 *
15346 * The following shows the Wi-Fi security levels from the lowest to the highest security level:
15347 * {@link #WIFI_SECURITY_OPEN}
15348 * {@link #WIFI_SECURITY_PERSONAL}
15349 * {@link #WIFI_SECURITY_ENTERPRISE_EAP}
15350 * {@link #WIFI_SECURITY_ENTERPRISE_192}
15351 *
15352 * @param level minimum security level
15353 * @throws SecurityException if the caller is not a device owner or a profile owner on
15354 * an organization-owned managed profile.
15355 */
15356 public void setMinimumRequiredWifiSecurityLevel(@WifiSecurity int level) {
15357 throwIfParentInstance("setMinimumRequiredWifiSecurityLevel");
15358 if (mService != null) {
15359 try {
15360 mService.setMinimumRequiredWifiSecurityLevel(level);
15361 } catch (RemoteException e) {
15362 throw e.rethrowFromSystemServer();
15363 }
15364 }
15365 }
15366
15367 /**
15368 * Returns the current Wi-Fi minimum security level.
15369 *
15370 * @see #setMinimumRequiredWifiSecurityLevel(int)
15371 */
15372 public @WifiSecurity int getMinimumRequiredWifiSecurityLevel() {
15373 throwIfParentInstance("getMinimumRequiredWifiSecurityLevel");
15374 if (mService == null) {
15375 return WIFI_SECURITY_OPEN;
15376 }
15377 try {
15378 return mService.getMinimumRequiredWifiSecurityLevel();
15379 } catch (RemoteException e) {
15380 throw e.rethrowFromSystemServer();
15381 }
15382 }
15383
15384 /**
15385 * Called by device owner or profile owner of an organization-owned managed profile to
15386 * specify the Wi-Fi SSID policy ({@link WifiSsidPolicy}).
15387 * Wi-Fi SSID policy specifies the SSID restriction the network must satisfy
15388 * in order to be eligible for a connection. Providing a null policy results in the
15389 * deactivation of the SSID restriction
15390 *
15391 * @param policy Wi-Fi SSID policy
15392 * @throws SecurityException if the caller is not a device owner or a profile owner on
15393 * an organization-owned managed profile.
15394 */
15395 public void setWifiSsidPolicy(@Nullable WifiSsidPolicy policy) {
15396 throwIfParentInstance("setWifiSsidPolicy");
15397 if (mService == null) {
15398 return;
15399 }
15400 try {
15401 mService.setWifiSsidPolicy(policy);
15402 } catch (RemoteException e) {
15403 throw e.rethrowFromSystemServer();
15404 }
15405
15406 }
15407
15408 /**
15409 * Returns the current Wi-Fi SSID policy.
15410 * If the policy has not been set, it will return NULL.
15411 *
15412 * @see #setWifiSsidPolicy(WifiSsidPolicy)
15413 * @throws SecurityException if the caller is not a device owner or a profile owner on
15414 * an organization-owned managed profile or a system app.
15415 */
15416 @Nullable
15417 public WifiSsidPolicy getWifiSsidPolicy() {
15418 throwIfParentInstance("getWifiSsidPolicy");
15419 if (mService == null) {
15420 return null;
15421 }
15422 try {
15423 return mService.getWifiSsidPolicy();
15424 } catch (RemoteException e) {
15425 throw e.rethrowFromSystemServer();
15426 }
15427 }
15428
15429 /**
15430 * Returns a {@link DevicePolicyResourcesManager} containing the required APIs to set, reset,
15431 * and get device policy related resources.
15432 */
15433 @NonNull
15434 public DevicePolicyResourcesManager getResources() {
15435 return mResourcesManager;
15436 }
15437
15438 /**
15439 * Returns a boolean for whether the DPC
15440 * (Device Policy Controller, the agent responsible for enforcing policy)
15441 * has been downloaded during provisioning.
15442 *
15443 * <p>If true is returned, then any attempts to begin setup again should result in factory reset
15444 *
15445 * @hide
15446 */
15447 @SystemApi
15448 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
15449 public boolean isDpcDownloaded() {
15450 throwIfParentInstance("isDpcDownloaded");
15451 if (mService != null) {
15452 try {
15453 return mService.isDpcDownloaded();
15454 } catch (RemoteException e) {
15455 throw e.rethrowFromSystemServer();
15456 }
15457 }
15458 return false;
15459 }
15460
15461 /**
15462 * Indicates that the DPC (Device Policy Controller, the agent responsible for enforcing policy)
15463 * has or has not been downloaded during provisioning.
15464 *
15465 * @param downloaded {@code true} if the dpc has been downloaded during provisioning.
15466 * {@code false} otherwise.
15467 *
15468 * @hide
15469 */
15470 @SystemApi
15471 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
15472 public void setDpcDownloaded(boolean downloaded) {
15473 throwIfParentInstance("setDpcDownloaded");
15474 if (mService != null) {
15475 try {
15476 mService.setDpcDownloaded(downloaded);
15477 } catch (RemoteException e) {
15478 throw e.rethrowFromSystemServer();
15479 }
15480 }
15481 }
15482
15483 /**
15484 * Returns the package name of the device policy management role holder.
15485 *
15486 * <p>If the device policy management role holder is not configured for this device, returns
15487 * {@code null}.
15488 */
15489 @Nullable
15490 public String getDevicePolicyManagementRoleHolderPackage() {
15491 String devicePolicyManagementConfig = mContext.getString(
15492 com.android.internal.R.string.config_devicePolicyManagement);
15493 return extractPackageNameFromDeviceManagerConfig(devicePolicyManagementConfig);
15494 }
15495
15496 /**
15497 * Returns the package name of the device policy management role holder updater.
15498 *
15499 * <p>If the device policy management role holder updater is not configured for this device,
15500 * returns {@code null}.
15501 *
15502 * @hide
15503 */
15504 @Nullable
15505 @TestApi
15506 public String getDevicePolicyManagementRoleHolderUpdaterPackage() {
15507 String devicePolicyManagementUpdaterConfig = mContext.getString(
15508 com.android.internal.R.string.config_devicePolicyManagementUpdater);
15509 if (TextUtils.isEmpty(devicePolicyManagementUpdaterConfig)) {
15510 return null;
15511 }
15512 return devicePolicyManagementUpdaterConfig;
15513 }
15514
15515 /**
15516 * Returns a {@link List} of managed profiles managed by some profile owner within the profile
15517 * group of the given user, or an empty {@link List} if there is not one.
15518 *
15519 * @param user the user whose profile group to look within to return managed profiles
15520 *
15521 * @hide
15522 */
15523 @SystemApi
15524 @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
15525 @NonNull
15526 public List<UserHandle> getPolicyManagedProfiles(@NonNull UserHandle user) {
15527 Objects.requireNonNull(user);
15528 if (mService != null) {
15529 try {
15530 return mService.getPolicyManagedProfiles(user);
15531 } catch (RemoteException e) {
15532 throw e.rethrowFromSystemServer();
15533 }
15534 }
15535 return Collections.emptyList();
15536 }
15537
15538 /**
15539 * Retrieves the package name for a given {@code deviceManagerConfig}.
15540 *
15541 * <p>Valid configs look like:
15542 * <ul>
15543 * <li>{@code com.package.name}</li>
15544 * <li>{@code com.package.name:<SHA256 checksum>}</li>
15545 * </ul>
15546 *
15547 * <p>If the supplied {@code deviceManagerConfig} is {@code null} or empty, returns
15548 * {@code null}.
15549 */
15550 @Nullable
15551 private String extractPackageNameFromDeviceManagerConfig(
15552 @Nullable String deviceManagerConfig) {
15553 if (TextUtils.isEmpty(deviceManagerConfig)) {
15554 return null;
15555 }
15556 if (deviceManagerConfig.contains(":")) {
15557 return deviceManagerConfig.split(":")[0];
15558 }
15559 return deviceManagerConfig;
15560 }
15561
15562 /**
15563 * @return {@code true} if bypassing the device policy management role qualification is allowed
15564 * with the current state of the device.
15565 *
15566 * @hide
15567 */
15568 @SystemApi
15569 @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS)
15570 public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() {
15571 if (mService != null) {
15572 try {
15573 return mService.shouldAllowBypassingDevicePolicyManagementRoleQualification();
15574 } catch (RemoteException e) {
15575 throw e.rethrowFromSystemServer();
15576 }
15577 }
15578 return false;
15579 }
15580 }