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.app.admin.flags.Flags.FLAG_SPLIT_CREATE_MANAGED_PROFILE_ENABLED; 20 import static android.Manifest.permission.INTERACT_ACROSS_USERS; 21 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL; 22 import static android.Manifest.permission.LOCK_DEVICE; 23 import static android.Manifest.permission.MANAGE_DEVICE_ADMINS; 24 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT; 25 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_APPS_CONTROL; 26 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_FUNCTIONS; 27 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CAMERA; 28 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CERTIFICATES; 29 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE; 30 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CONTENT_PROTECTION; 31 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DEFAULT_SMS; 32 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_FACTORY_RESET; 33 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_INPUT_METHODS; 34 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_KEYGUARD; 35 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK; 36 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS; 37 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_TASK; 38 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MTE; 39 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY; 40 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PACKAGE_STATE; 41 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PROFILE_INTERACTION; 42 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES; 43 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RESET_PASSWORD; 44 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS; 45 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SCREEN_CAPTURE; 46 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SECURITY_LOGGING; 47 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_STATUS_BAR; 48 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE; 49 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SYSTEM_UPDATES; 50 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING; 51 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIFI; 52 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIPE_DATA; 53 import static android.Manifest.permission.QUERY_ADMIN_POLICY; 54 import static android.Manifest.permission.QUERY_DEVICE_STOLEN_STATE; 55 import static android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY; 56 import static android.Manifest.permission.SET_TIME; 57 import static android.Manifest.permission.SET_TIME_ZONE; 58 import static android.app.admin.DeviceAdminInfo.HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED; 59 import static android.app.admin.flags.Flags.FLAG_DEVICE_THEFT_API_ENABLED; 60 import static android.app.admin.flags.Flags.FLAG_REMOVE_MANAGED_PROFILE_ENABLED; 61 import static android.app.admin.flags.Flags.onboardingBugreportV2Enabled; 62 import static android.app.admin.flags.Flags.onboardingConsentlessBugreports; 63 import static android.app.admin.flags.Flags.FLAG_SECONDARY_LOCKSCREEN_API_ENABLED; 64 import static android.content.Intent.LOCAL_FLAG_FROM_SYSTEM; 65 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1; 66 import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE; 67 68 import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage; 69 70 import android.Manifest.permission; 71 import android.accounts.Account; 72 import android.annotation.BroadcastBehavior; 73 import android.annotation.CallbackExecutor; 74 import android.annotation.ColorInt; 75 import android.annotation.FlaggedApi; 76 import android.annotation.IntDef; 77 import android.annotation.NonNull; 78 import android.annotation.Nullable; 79 import android.annotation.RequiresFeature; 80 import android.annotation.RequiresPermission; 81 import android.annotation.SdkConstant; 82 import android.annotation.SdkConstant.SdkConstantType; 83 import android.annotation.StringDef; 84 import android.annotation.SupportsCoexistence; 85 import android.annotation.SuppressLint; 86 import android.annotation.SystemApi; 87 import android.annotation.SystemService; 88 import android.annotation.TestApi; 89 import android.annotation.UserHandleAware; 90 import android.annotation.UserIdInt; 91 import android.annotation.WorkerThread; 92 import android.app.Activity; 93 import android.app.IServiceConnection; 94 import android.app.KeyguardManager; 95 import android.app.admin.SecurityLog.SecurityEvent; 96 import android.app.admin.flags.Flags; 97 import android.app.compat.CompatChanges; 98 import android.compat.annotation.ChangeId; 99 import android.compat.annotation.EnabledSince; 100 import android.compat.annotation.UnsupportedAppUsage; 101 import android.content.ComponentName; 102 import android.content.Context; 103 import android.content.Intent; 104 import android.content.IntentFilter; 105 import android.content.ServiceConnection; 106 import android.content.pm.ApplicationInfo; 107 import android.content.pm.IPackageDataObserver; 108 import android.content.pm.PackageManager; 109 import android.content.pm.PackageManager.NameNotFoundException; 110 import android.content.pm.ParceledListSlice; 111 import android.content.pm.UserInfo; 112 import android.graphics.Bitmap; 113 import android.graphics.drawable.Drawable; 114 import android.net.PrivateDnsConnectivityChecker; 115 import android.net.ProxyInfo; 116 import android.net.Uri; 117 import android.nfc.NfcAdapter; 118 import android.os.Binder; 119 import android.os.Build; 120 import android.os.Bundle; 121 import android.os.IpcDataCache; 122 import android.os.ParcelFileDescriptor; 123 import android.os.Parcelable; 124 import android.os.PersistableBundle; 125 import android.os.Process; 126 import android.os.RemoteCallback; 127 import android.os.RemoteException; 128 import android.os.ServiceSpecificException; 129 import android.os.UserHandle; 130 import android.os.UserManager; 131 import android.os.UserManager.UserOperationException; 132 import android.os.UserManager.UserOperationResult; 133 import android.provider.CalendarContract; 134 import android.provider.ContactsContract.Directory; 135 import android.provider.Settings; 136 import android.security.AttestedKeyPair; 137 import android.security.Credentials; 138 import android.security.KeyChain; 139 import android.security.KeyChainException; 140 import android.security.keymaster.KeymasterCertificateChain; 141 import android.security.keystore.AttestationUtils; 142 import android.security.keystore.KeyAttestationException; 143 import android.security.keystore.KeyGenParameterSpec; 144 import android.security.keystore.ParcelableKeyGenParameterSpec; 145 import android.security.keystore.StrongBoxUnavailableException; 146 import android.service.restrictions.RestrictionsReceiver; 147 import android.telephony.TelephonyManager; 148 import android.telephony.data.ApnSetting; 149 import android.text.TextUtils; 150 import android.util.ArraySet; 151 import android.util.DebugUtils; 152 import android.util.Log; 153 import android.util.Pair; 154 155 import com.android.internal.annotations.VisibleForTesting; 156 import com.android.internal.infra.AndroidFuture; 157 import com.android.internal.net.NetworkUtilsInternal; 158 import com.android.internal.os.BackgroundThread; 159 import com.android.internal.os.Zygote; 160 import com.android.internal.util.ArrayUtils; 161 import com.android.internal.util.Preconditions; 162 import com.android.org.conscrypt.TrustedCertificateStore; 163 164 import java.io.ByteArrayInputStream; 165 import java.io.FileNotFoundException; 166 import java.io.IOException; 167 import java.lang.annotation.Retention; 168 import java.lang.annotation.RetentionPolicy; 169 import java.net.InetSocketAddress; 170 import java.net.Proxy; 171 import java.security.KeyFactory; 172 import java.security.KeyPair; 173 import java.security.NoSuchAlgorithmException; 174 import java.security.PrivateKey; 175 import java.security.cert.Certificate; 176 import java.security.cert.CertificateException; 177 import java.security.cert.CertificateFactory; 178 import java.security.cert.X509Certificate; 179 import java.security.spec.InvalidKeySpecException; 180 import java.security.spec.PKCS8EncodedKeySpec; 181 import java.util.ArrayList; 182 import java.util.Arrays; 183 import java.util.Collections; 184 import java.util.HashSet; 185 import java.util.List; 186 import java.util.Map; 187 import java.util.Objects; 188 import java.util.Set; 189 import java.util.concurrent.CompletableFuture; 190 import java.util.concurrent.ExecutionException; 191 import java.util.concurrent.Executor; 192 import java.util.function.Consumer; 193 194 /** 195 * Manages device policy and restrictions applied to the user of the device or 196 * apps running on the device. 197 * 198 * <p>This class contains three types of methods: 199 * <ol><li>Those aimed at <a href="#managingapps">managing apps</a> 200 * <li>Those aimed at the <a href="#roleholder">Device Policy Management Role Holder</a> 201 * <li>Those aimed at <a href="#querying">apps which wish to respect device policy</a> 202 * </ol> 203 * 204 * <p>The intended caller for each API is indicated in its Javadoc. 205 * 206 * <p id="managingapps"><b>Managing Apps</b> 207 * <p>Apps can be made capable of setting device policy ("Managing Apps") either by 208 * being set as a <a href="#deviceadmin">Device Administrator</a>, being set as a 209 * <a href="#devicepolicycontroller">Device Policy Controller</a>, or by holding the 210 * appropriate <a href="#permissions">Permissions</a>. 211 * 212 * <p id="deviceadmin">A <b>Device Administrator</b> is an app which is able to enforce device 213 * policies that it has declared in its device admin XML file. An app can prompt the user to give it 214 * device administator privileges using the {@link #ACTION_ADD_DEVICE_ADMIN} action. 215 * 216 * <p>For more information about Device Administration, read the 217 * <a href="{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> 218 * developer guide. 219 * 220 * <p id="devicepolicycontroller">Device Administrator apps can also be recognised as <b> 221 * Device Policy Controllers</b>. Device Policy Controllers can be one of 222 * two types: 223 * <ul> 224 * <li>A <i id="deviceowner">Device Owner</i>, which only ever exists on the 225 * {@link UserManager#isSystemUser System User} or Main User, is 226 * the most powerful type of Device Policy Controller and can affect policy across the device. 227 * <li>A <i id="profileowner">Profile Owner</i>, which can exist on any user, can 228 * affect policy on the user it is on, and when it is running on 229 * {@link UserManager#isProfile a profile} has 230 * <a href="#profile-on-parent">limited</a> ability to affect policy on its parent. 231 * </ul> 232 * 233 * <p>Additional capabilities can be provided to Device Policy Controllers in 234 * the following circumstances: 235 * <ul> 236 * <li>A Profile Owner on an <a href="#organization-owned">organization owned</a> device has access 237 * to additional abilities, both <a href="#profile-on-parent-organization-owned">affecting policy on the profile's</a> 238 * parent and also the profile itself. 239 * <li>A Profile Owner running on the {@link UserManager#isSystemUser System User} has access to 240 * additional capabilities which affect the {@link UserManager#isSystemUser System User} and 241 * also the whole device. 242 * <li>A Profile Owner running on an <a href="#affiliated">affiliated</a> user has 243 * capabilities similar to that of a <a href="#deviceowner">Device Owner</a> 244 * </ul> 245 * 246 * <p>For more information, see <a href="{@docRoot}work/dpc/build-dpc">Building a Device Policy 247 * Controller</a>. 248 * 249 * <p><a href="#permissions">Permissions</a> are generally only given to apps 250 * fulfilling particular key roles on the device (such as managing 251 * {@link android.devicelock.DeviceLockManager device locks}). 252 * 253 * <p id="roleholder"><b>Device Policy Management Role Holder</b> 254 * <p>One app on the device fulfills the Device Policy Management Role and is trusted with managing 255 * the overall state of Device Policy. This has access to much more powerful methods than 256 * <a href="#managingapps">managing apps</a>. 257 * 258 * <p id="querying"><b>Querying Device Policy</b> 259 * <p>In most cases, regular apps do not need to concern themselves with device 260 * policy, and restrictions will be enforced automatically. There are some cases 261 * where an app may wish to query device policy to provide a better user 262 * experience. Only a small number of policies allow apps to query them directly. 263 * These APIs will typically have no special required permissions. 264 * 265 * <p id="managedprovisioning"><b>Managed Provisioning</b> 266 * <p>Managed Provisioning is the process of recognising an app as a 267 * <a href="#deviceowner">Device Owner</a> or <a href="#profileowner">Profile Owner</a>. It 268 * involves presenting education and consent screens to the user to ensure they 269 * are aware of the capabilities this grants the <a href="#devicepolicycontroller">Device Policy 270 * Controller</a> 271 * 272 * <p>For more information on provisioning, see <a href="{@docRoot}work/dpc/build-dpc">Building a 273 * Device Policy Controller</a>. 274 * 275 * <p id="managed_profile">A <b>Managed Profile</b> enables data separation. For example to use 276 * a device both for personal and corporate usage. The managed profile and its 277 * parent share a launcher. 278 * 279 * <p id="affiliated"><b>Affiliation</b> 280 * <p>Using the {@link #setAffiliationIds} method, a 281 * <a href="#deviceowner">Device Owner</a> can set a list of affiliation ids for the 282 * {@link UserManager#isSystemUser System User}. Any <a href="#profileowner">Profile Owner</a> on 283 * the same device can also call {@link #setAffiliationIds} to set affiliation ids 284 * for the {@link UserManager user} it is on. When there is the same ID 285 * present in both lists, the user is said to be "affiliated" and we can refer to 286 * the <a href="#profileowner">Profile Owner</a> as a "profile owner on an affiliated 287 * user" or an "affiliated profile owner". 288 * 289 * Becoming affiliated grants the <a href="#profileowner">Profile Owner</a> capabilities similar to 290 * that of the <a href="#deviceowner">Device Owner</a>. It also allows use of the 291 * {@link #bindDeviceAdminServiceAsUser} APIs for direct communication between the 292 * <a href="#deviceowner">Device Owner</a> and 293 * affiliated <a href="#profileowner">Profile Owners</a>. 294 * 295 * <p id="organization-owned"><b>Organization Owned</b></p> 296 * An organization owned device is one which is not owned by the person making use of the device and 297 * is instead owned by an organization such as their employer or education provider. These devices 298 * are recognised as being organization owned either by the presence of a 299 * <a href="#deviceowner">device owner</a> or of a 300 * {@link #isOrganizationOwnedDeviceWithManagedProfile profile which has a profile owner is marked 301 * as organization owned}. 302 * 303 * <p id="profile-on-parent-organization-owned">Profile owners running on an 304 * <a href="organization-owned">organization owned</a> device can exercise additional capabilities 305 * using the {@link #getParentProfileInstance(ComponentName)} API which apply to the parent user. 306 * Each API will indicate if it is usable in this way. 307 * 308 * <p id="automotive"><b>Android Automotive</b> 309 * <p>On {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE 310 * "Android Automotive builds"}, some methods can throw 311 * {@link UnsafeStateException "an exception"} if an action is unsafe (for example, if the vehicle 312 * is moving). Callers running on 313 * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE 314 * "Android Automotive builds"} should always check for this exception. 315 */ 316 317 @SystemService(Context.DEVICE_POLICY_SERVICE) 318 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN) 319 public class DevicePolicyManager { 320 321 /** @hide */ 322 public static final String DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG = 323 "deprecate_usermanagerinternal_devicepolicy"; 324 /** @hide */ 325 public static final boolean DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT = true; 326 /** @hide */ 327 public static final String ADD_ISFINANCED_DEVICE_FLAG = 328 "add-isfinanced-device"; 329 /** @hide */ 330 public static final boolean ADD_ISFINANCED_FEVICE_DEFAULT = true; 331 332 private static String TAG = "DevicePolicyManager"; 333 334 private final Context mContext; 335 private final IDevicePolicyManager mService; 336 private final boolean mParentInstance; 337 private final DevicePolicyResourcesManager mResourcesManager; 338 339 /** @hide */ DevicePolicyManager(Context context, IDevicePolicyManager service)340 public DevicePolicyManager(Context context, IDevicePolicyManager service) { 341 this(context, service, false); 342 } 343 344 /** @hide */ 345 @VisibleForTesting DevicePolicyManager(Context context, IDevicePolicyManager service, boolean parentInstance)346 protected DevicePolicyManager(Context context, IDevicePolicyManager service, 347 boolean parentInstance) { 348 mContext = context; 349 mService = service; 350 mParentInstance = parentInstance; 351 mResourcesManager = new DevicePolicyResourcesManager(context, service); 352 } 353 354 /** 355 * Fetch the current value of mService. This is used in the binder cache lambda 356 * expressions. 357 */ getService()358 private IDevicePolicyManager getService() { 359 return mService; 360 } 361 362 /** 363 * Fetch the current value of mParentInstance. This is used in the binder cache 364 * lambda expressions. 365 */ isParentInstance()366 private boolean isParentInstance() { 367 return mParentInstance; 368 } 369 370 /** 371 * Fetch the current value of mContext. This is used in the binder cache lambda 372 * expressions. 373 */ getContext()374 private Context getContext() { 375 return mContext; 376 } 377 378 /** @hide test will override it. */ 379 @VisibleForTesting myUserId()380 protected int myUserId() { 381 return mContext.getUserId(); 382 } 383 384 /** 385 * Activity action: Starts the provisioning flow which sets up a 386 * <a href="#managed-profile">managed profile</a>. 387 * 388 * <p>It is possible to check if provisioning is allowed or not by querying the method 389 * {@link #isProvisioningAllowed(String)}. 390 * 391 * <p>The intent may contain the following extras: 392 * 393 * <table> 394 * <thead> 395 * <tr> 396 * <th>Extra</th> 397 * <th></th> 398 * <th>Supported Versions</th> 399 * </tr> 400 * </thead> 401 * <tbody> 402 * <tr> 403 * <td>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}</td> 404 * <td colspan="2"></td> 405 * </tr> 406 * <tr> 407 * <td>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}</td> 408 * <td></td> 409 * <td>{@link android.os.Build.VERSION_CODES#N}+</td> 410 * </tr> 411 * <tr> 412 * <td>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</td> 413 * <td colspan="2"></td> 414 * </tr> 415 * <tr> 416 * <td>{@link #EXTRA_PROVISIONING_LOGO_URI}</td> 417 * <td colspan="2"></td> 418 * </tr> 419 * <tr> 420 * <td>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}</td> 421 * <td colspan="2"><b>Can only be used by an existing device owner trying to create a 422 * managed profile</b></td> 423 * </tr> 424 * <tr> 425 * <td>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}</td> 426 * <td colspan="2"></td> 427 * </tr> 428 * <tr> 429 * <td>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</td> 430 * <td colspan="2"></td> 431 * </tr> 432 * <tr> 433 * <td>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</td> 434 * <td> 435 * <b>Required if {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} is not 436 * specified. Must match the package name of the calling application.</b> 437 * </td> 438 * <td>{@link android.os.Build.VERSION_CODES#LOLLIPOP}+</td> 439 * </tr> 440 * <tr> 441 * <td>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</td> 442 * <td> 443 * <b>Required if {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is not 444 * specified. Package name must match the package name of the calling 445 * application.</b> 446 * </td> 447 * <td>{@link android.os.Build.VERSION_CODES#M}+</td> 448 * </tr> 449 * <tr> 450 * <td>{@link #EXTRA_PROVISIONING_ALLOW_OFFLINE}</td> 451 * <td colspan="2">On {@link android.os.Build.VERSION_CODES#TIRAMISU}+, when set to 452 * true this will <b>force</b> offline provisioning instead of allowing it</td> 453 * </tr> 454 * </tbody> 455 * </table> 456 * 457 * <p>When <a href="#managedprovisioning">managed provisioning</a> has completed, broadcasts 458 * are sent to the application specified in the provisioning intent. The 459 * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the 460 * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in 461 * the primary profile. 462 * 463 * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has 464 * completed, along with the above broadcast, activity intent 465 * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner. 466 * 467 * <p>If provisioning fails, the managed profile is removed so the device returns to its 468 * previous state. 469 * 470 * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a 471 * result code of {@link android.app.Activity#RESULT_OK} indicates that the synchronous part of 472 * the provisioning flow was successful, although this doesn't guarantee the full flow will 473 * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} indicates 474 * that the user backed-out of provisioning or some precondition for provisioning wasn't met. 475 * 476 * <p>If a <a href="#roleholder">device policy management role holder</a> updater is present on 477 * the device, an internet connection attempt must be made prior to launching this intent. 478 */ 479 // See b/365955253 for additional behaviours of this API. 480 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 481 public static final String ACTION_PROVISION_MANAGED_PROFILE 482 = "android.app.action.PROVISION_MANAGED_PROFILE"; 483 484 /** 485 * Activity action: Starts the provisioning flow which sets up a managed user. 486 * 487 * <p>This intent will typically be sent by a mobile device management application (MDM). 488 * Provisioning configures the user as managed user and sets the MDM as the profile 489 * owner who has full control over the user. Provisioning can only happen before user setup has 490 * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is 491 * allowed. 492 * 493 * <p>The intent contains the following extras: 494 * <ul> 495 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li> 496 * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li> 497 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li> 498 * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li> 499 * </ul> 500 * 501 * <p>If provisioning fails, the device returns to its previous state. 502 * 503 * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a 504 * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of 505 * the provisioning flow was successful, although this doesn't guarantee the full flow will 506 * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies 507 * that the user backed-out of provisioning, or some precondition for provisioning wasn't met. 508 * 509 * @hide 510 */ 511 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 512 public static final String ACTION_PROVISION_MANAGED_USER 513 = "android.app.action.PROVISION_MANAGED_USER"; 514 515 /** 516 * Activity action: Starts the provisioning flow which sets up a managed device. 517 * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}. 518 * 519 * <p> During device owner provisioning a device admin app is set as the owner of the device. 520 * A device owner has full control over the device. The device owner can not be modified by the 521 * user. 522 * 523 * <p> A typical use case would be a device that is owned by a company, but used by either an 524 * employee or client. 525 * 526 * <p> An intent with this action can be sent only on an unprovisioned device. 527 * It is possible to check if provisioning is allowed or not by querying the method 528 * {@link #isProvisioningAllowed(String)}. 529 * 530 * <p>The intent contains the following extras: 531 * <ul> 532 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li> 533 * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li> 534 * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li> 535 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li> 536 * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li> 537 * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li> 538 * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional</li> 539 * </ul> 540 * 541 * <p>When device owner provisioning has completed, an intent of the type 542 * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the 543 * device owner. 544 * 545 * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has 546 * completed, along with the above broadcast, activity intent 547 * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner. 548 * 549 * <p>If provisioning fails, the device is factory reset. 550 * 551 * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part 552 * of the provisioning flow was successful, although this doesn't guarantee the full flow will 553 * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies 554 * that the user backed-out of provisioning, or some precondition for provisioning wasn't met. 555 * 556 * @deprecated to support {@link android.os.Build.VERSION_CODES#S} and later, admin apps must 557 * implement activities with intent filters for the {@link #ACTION_GET_PROVISIONING_MODE} and 558 * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent actions; using {@link 559 * #ACTION_PROVISION_MANAGED_DEVICE} to start provisioning will cause the provisioning to fail; 560 * to additionally support pre-{@link android.os.Build.VERSION_CODES#S}, admin apps must also 561 * continue to use this constant. 562 */ 563 @Deprecated 564 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 565 public static final String ACTION_PROVISION_MANAGED_DEVICE 566 = "android.app.action.PROVISION_MANAGED_DEVICE"; 567 568 /** 569 * Activity action: launch when user provisioning completed, i.e. 570 * {@link #getUserProvisioningState()} returns one of the complete state. 571 * 572 * <p> Please note that the API behavior is not necessarily consistent across various releases, 573 * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default 574 * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only. 575 * 576 * <p> The activity must be protected by permission 577 * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold 578 * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched. 579 * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the 580 * components are not started by this intent. 581 * 582 * @deprecated Starting from Android 13, the system no longer launches an intent with this 583 * action when user provisioning completes. 584 * @hide 585 */ 586 @Deprecated 587 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 588 @SystemApi 589 public static final String ACTION_STATE_USER_SETUP_COMPLETE = 590 "android.app.action.STATE_USER_SETUP_COMPLETE"; 591 592 /** 593 * Activity action: Starts the provisioning flow which sets up a managed device. 594 * 595 * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of 596 * the device. A device owner has full control over the device. The device owner can not be 597 * modified by the user and the only way of resetting the device is via factory reset. 598 * 599 * <p>From version {@link android.os.Build.VERSION_CODES#Q}, the admin app can choose 600 * whether to set up a fully managed device or a managed profile. For the admin app to support 601 * this, it must have an activity with intent filter {@link #ACTION_GET_PROVISIONING_MODE} and 602 * another one with intent filter {@link #ACTION_ADMIN_POLICY_COMPLIANCE}. For example: 603 * <pre> 604 * <activity 605 * android:name=".GetProvisioningModeActivity" 606 * android:label="@string/app_name" 607 * android:permission="android.permission.BIND_DEVICE_ADMIN"> 608 * <intent-filter> 609 * <action 610 * android:name="android.app.action.GET_PROVISIONING_MODE" /> 611 * <category android:name="android.intent.category.DEFAULT" /> 612 * </intent-filter> 613 * </activity> 614 * 615 * <activity 616 * android:name=".PolicyComplianceActivity" 617 * android:label="@string/app_name" 618 * android:permission="android.permission.BIND_DEVICE_ADMIN"> 619 * <intent-filter> 620 * <action 621 * android:name="android.app.action.ADMIN_POLICY_COMPLIANCE" /> 622 * <category android:name="android.intent.category.DEFAULT" /> 623 * </intent-filter> 624 * </activity></pre> 625 * 626 * <p>A typical use case would be a device that is owned by a company, but used by either an 627 * employee or client. 628 * 629 * <p>The provisioning message should be sent to an unprovisioned device. 630 * 631 * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent 632 * by a privileged app with the permission 633 * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}. 634 * 635 * <p>If a device policy management role holder (DPMRH) updater is present on the device, an 636 * internet connection attempt must be made prior to launching this intent. If internet 637 * connection could not be established, provisioning will fail unless {@link 638 * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is explicitly set to {@code true}, in which case 639 * provisioning will continue without using the DPMRH. If an internet connection has been 640 * established, the DPMRH updater will be launched via {@link 641 * #ACTION_UPDATE_DEVICE_MANAGEMENT_ROLE_HOLDER}, which will update the DPMRH if it's not 642 * present on the device, or if it's present and not valid. 643 * 644 * <p>A DPMRH is considered valid if it has intent filters for {@link 645 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}, {@link 646 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link 647 * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION}. 648 * 649 * <p>If a DPMRH is present on the device and valid, the provisioning flow will be deferred to 650 * it via the {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent. 651 * 652 * <p>The provisioning intent contains the following properties: 653 * <ul> 654 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li> 655 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li> 656 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li> 657 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li> 658 * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li> 659 * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li> 660 * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li> 661 * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li> 662 * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li> 663 * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li> 664 * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li> 665 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li> 666 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li> 667 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li> 668 * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li> 669 * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li> 670 * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li> 671 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li> 672 * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA}, optional </li> 673 * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional - when not used for 674 * cloud enrollment, NFC or QR provisioning</li> 675 * </ul> 676 * 677 * @hide 678 */ 679 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 680 @SystemApi 681 public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE = 682 "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE"; 683 684 /** 685 * Activity action: Starts the provisioning flow which sets up a financed device. 686 * 687 * <p>During financed device provisioning, a device admin app is downloaded and set as the owner 688 * of the device. A device owner has full control over the device. The device owner can not be 689 * modified by the user. 690 * 691 * <p>A typical use case would be a device that is bought from the reseller through financing 692 * program. 693 * 694 * <p>An intent with this action can be sent only on an unprovisioned device. 695 * 696 * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent 697 * by a privileged app with the permission 698 * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}. 699 * 700 * <p>The provisioning intent contains the following properties: 701 * <ul> 702 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li> 703 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li> 704 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li> 705 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li> 706 * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li> 707 * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li> 708 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li> 709 * </ul> 710 * 711 * <p>Once the device admin app is set as the device owner, the following APIs are available for 712 * managing polices on the device: 713 * <ul> 714 * <li>{@link #isDeviceManaged()}</li> 715 * <li>{@link #isUninstallBlocked(ComponentName, String)}</li> 716 * <li>{@link #setUninstallBlocked(ComponentName, String, boolean)}</li> 717 * <li>{@link #setUserControlDisabledPackages(ComponentName, List)}</li> 718 * <li>{@link #getUserControlDisabledPackages(ComponentName)}</li> 719 * <li>{@link #setOrganizationName(ComponentName, CharSequence)}</li> 720 * <li>{@link #getOrganizationName(ComponentName)} </li> 721 * <li>{@link #setShortSupportMessage(ComponentName, CharSequence)}</li> 722 * <li>{@link #getShortSupportMessage(ComponentName)}</li> 723 * <li>{@link #isBackupServiceEnabled(ComponentName)}</li> 724 * <li>{@link #setBackupServiceEnabled(ComponentName, boolean)}</li> 725 * <li>{@link #isLockTaskPermitted(String)}</li> 726 * <li>{@link #setLockTaskFeatures(ComponentName, int)}, where the following lock task features 727 * can be set (otherwise a {@link SecurityException} will be thrown):</li> 728 * <ul> 729 * <li>{@link #LOCK_TASK_FEATURE_SYSTEM_INFO}</li> 730 * <li>{@link #LOCK_TASK_FEATURE_KEYGUARD}</li> 731 * <li>{@link #LOCK_TASK_FEATURE_HOME}</li> 732 * <li>{@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}</li> 733 * <li>{@link #LOCK_TASK_FEATURE_NOTIFICATIONS}</li> 734 * <li>{@link #LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK}</li> 735 * </ul> 736 * <li>{@link #getLockTaskFeatures(ComponentName)}</li> 737 * <li>{@link #setLockTaskPackages(ComponentName, String[])}</li> 738 * <li>{@link #getLockTaskPackages(ComponentName)}</li> 739 * <li>{@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}</li> 740 * <li>{@link #clearPackagePersistentPreferredActivities(ComponentName, String)} </li> 741 * <li>{@link #wipeData(int)}</li> 742 * <li>{@link #isDeviceOwnerApp(String)}</li> 743 * <li>{@link #clearDeviceOwnerApp(String)}</li> 744 * <li>{@link #setPermissionGrantState(ComponentName, String, String, int)}, where 745 * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be 746 * {@link #PERMISSION_GRANT_STATE_GRANTED}, {@link #PERMISSION_GRANT_STATE_DENIED}, or 747 * {@link #PERMISSION_GRANT_STATE_DEFAULT} and can <b>only</b> be applied to the device admin 748 * app (otherwise a {@link SecurityException} will be thrown)</li> 749 * <li>{@link #getPermissionGrantState(ComponentName, String, String)}, where 750 * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be 751 * used and device admin app is the only package that can be used to retrieve the permission 752 * permission grant state for (otherwise a {@link SecurityException} will be thrown)</li> 753 * <li>{@link #addUserRestriction(ComponentName, String)}, where the following user restrictions 754 * are permitted (otherwise a {@link SecurityException} will be thrown):</li> 755 * <ul> 756 * <li>{@link UserManager#DISALLOW_ADD_USER}</li> 757 * <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li> 758 * <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li> 759 * <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li> 760 * <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li> 761 * <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li> 762 * </ul> 763 * <li>{@link #getUserRestrictions(ComponentName)}</li> 764 * <li>{@link #clearUserRestriction(ComponentName, String)}, where the following user 765 * restrictions are permitted (otherwise a {@link SecurityException} will be thrown):</li> 766 * <ul> 767 * <li>{@link UserManager#DISALLOW_ADD_USER}</li> 768 * <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li> 769 * <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li> 770 * <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li> 771 * <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li> 772 * <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li> 773 * </ul> 774 * </ul> 775 * 776 * @hide 777 */ 778 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 779 @SystemApi 780 public static final String ACTION_PROVISION_FINANCED_DEVICE = 781 "android.app.action.PROVISION_FINANCED_DEVICE"; 782 783 /** 784 * Activity action: Finalizes management provisioning, should be used after user-setup 785 * has been completed and {@link #getUserProvisioningState()} returns one of: 786 * <ul> 787 * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li> 788 * <li>{@link #STATE_USER_SETUP_COMPLETE}</li> 789 * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li> 790 * </ul> 791 * 792 * <p>If a device policy management role holder (DPMRH) is present on the device and 793 * valid, the provisioning flow will be deferred to it via the {@link 794 * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION} intent. 795 * 796 * @hide 797 */ 798 @SystemApi 799 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 800 public static final String ACTION_PROVISION_FINALIZATION 801 = "android.app.action.PROVISION_FINALIZATION"; 802 803 /** 804 * Activity action: starts the managed profile provisioning flow inside the device policy 805 * management role holder. 806 * 807 * <p>During the managed profile provisioning flow, the platform-provided provisioning handler 808 * will delegate provisioning to the device policy management role holder, by firing this 809 * intent. Third-party mobile device management applications attempting to fire this intent will 810 * receive a {@link SecurityException}. 811 * 812 * <p>Device policy management role holders are required to have a handler for this intent 813 * action. 814 * 815 * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility 816 * of the role holder to restore its state from this extra. This is the same {@link Bundle} 817 * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}. 818 * 819 * <p>A result code of {@link Activity#RESULT_OK} implies that managed profile provisioning 820 * finished successfully. If it did not, a result code of {@link Activity#RESULT_CANCELED} 821 * is used instead. 822 * 823 * @see #ACTION_PROVISION_MANAGED_PROFILE 824 * 825 * @hide 826 */ 827 @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP) 828 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 829 @SystemApi 830 public static final String ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE = 831 "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_PROFILE"; 832 833 /** 834 * Result code that can be returned by the {@link 835 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link 836 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if a work 837 * profile has been created. 838 * 839 * @hide 840 */ 841 @SystemApi 842 public static final int RESULT_WORK_PROFILE_CREATED = 122; 843 844 /** 845 * Result code that can be returned by the {@link 846 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link 847 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if the 848 * device owner was set. 849 * 850 * @hide 851 */ 852 @SystemApi 853 public static final int RESULT_DEVICE_OWNER_SET = 123; 854 855 /** 856 * Activity action: starts the trusted source provisioning flow inside the device policy 857 * management role holder. 858 * 859 * <p>During the trusted source provisioning flow, the platform-provided provisioning handler 860 * will delegate provisioning to the device policy management role holder, by firing this 861 * intent. Third-party mobile device management applications attempting to fire this intent will 862 * receive a {@link SecurityException}. 863 * 864 * <p>Device policy management role holders are required to have a handler for this intent 865 * action. 866 * 867 * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility 868 * of the role holder to restore its state from this extra. This is the same {@link Bundle} 869 * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}. 870 * 871 * <p>The result codes can be either {@link #RESULT_WORK_PROFILE_CREATED}, {@link 872 * #RESULT_DEVICE_OWNER_SET} or {@link Activity#RESULT_CANCELED} if provisioning failed. 873 * 874 * @see #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE 875 * 876 * @hide 877 */ 878 @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP) 879 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 880 @SystemApi 881 public static final String ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE = 882 "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE"; 883 884 /** 885 * Activity action: starts the provisioning finalization flow inside the device policy 886 * management role holder. 887 * 888 * <p>During the provisioning finalization flow, the platform-provided provisioning handler 889 * will delegate provisioning to the device policy management role holder, by firing this 890 * intent. Third-party mobile device management applications attempting to fire this intent will 891 * receive a {@link SecurityException}. 892 * 893 * <p>Device policy management role holders are required to have a handler for this intent 894 * action. 895 * 896 * <p>This handler forwards the result from the admin app's {@link 897 * #ACTION_ADMIN_POLICY_COMPLIANCE} handler. Result code {@link Activity#RESULT_CANCELED} 898 * implies the provisioning finalization flow has failed. 899 * 900 * @see #ACTION_PROVISION_FINALIZATION 901 * 902 * @hide 903 */ 904 @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP) 905 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 906 @SystemApi 907 public static final String ACTION_ROLE_HOLDER_PROVISION_FINALIZATION = 908 "android.app.action.ROLE_HOLDER_PROVISION_FINALIZATION"; 909 910 /** 911 * {@link Activity} result code which can be returned by {@link 912 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link 913 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} to signal that an update 914 * to the role holder is required. 915 * 916 * <p>This result code can be accompanied by {@link #EXTRA_ROLE_HOLDER_STATE}. 917 * 918 * @hide 919 */ 920 @SystemApi 921 public static final int RESULT_UPDATE_ROLE_HOLDER = 2; 922 923 /** 924 * A {@link PersistableBundle} extra which the role holder can use to describe its own state 925 * when it returns {@link #RESULT_UPDATE_ROLE_HOLDER}. 926 * 927 * <p>If {@link #RESULT_UPDATE_ROLE_HOLDER} was accompanied by this extra, after the update 928 * completes, the role holder's {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} or {@link 929 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent will be relaunched, 930 * which will contain this extra. It is the role holder's responsibility to restore its 931 * state from this extra. 932 * 933 * <p>The content of this {@link PersistableBundle} is entirely up to the role holder. It 934 * should contain anything the role holder needs to restore its original state when it gets 935 * restarted. 936 * 937 * @hide 938 */ 939 @SystemApi 940 public static final String EXTRA_ROLE_HOLDER_STATE = "android.app.extra.ROLE_HOLDER_STATE"; 941 942 /** 943 * A {@code boolean} extra which determines whether to force a role holder update, regardless 944 * of any internal conditions {@link #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} might 945 * have. 946 * 947 * <p>This extra can be provided to intents with action {@link 948 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}. 949 * 950 * @hide 951 */ 952 @SystemApi 953 public static final String EXTRA_FORCE_UPDATE_ROLE_HOLDER = 954 "android.app.extra.FORCE_UPDATE_ROLE_HOLDER"; 955 956 /** 957 * A boolean extra indicating whether offline provisioning should be used. 958 * 959 * <p>The default value is {@code false}. 960 */ 961 // See b/365955253 for detailed behaviours of this API. 962 public static final String EXTRA_PROVISIONING_ALLOW_OFFLINE = 963 "android.app.extra.PROVISIONING_ALLOW_OFFLINE"; 964 965 /** 966 * A String extra holding a url that specifies the download location of the device policy 967 * management role holder package. 968 * 969 * <p>This is only meant to be used in cases when a specific variant of the role holder package 970 * is needed (such as a debug variant). If not provided, the default variant of the device 971 * manager role holder package is downloaded. 972 * 973 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} 974 * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 975 * provisioning via an NFC bump. 976 * 977 * @hide 978 */ 979 @SystemApi 980 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION = 981 "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION"; 982 983 /** 984 * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the 985 * android package archive at the download location specified in {@link 986 * #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}. 987 * 988 * <p>The signatures of an android package archive can be obtained using 989 * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag 990 * {@link android.content.pm.PackageManager#GET_SIGNING_CERTIFICATES}. 991 * 992 * <p>If {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION} is provided, it must 993 * be accompanied by this extra. The provided checksum must match the checksum of any signature 994 * of the file at the download location. If the checksum does not match an error will be shown 995 * to the user and the user will be asked to factory reset the device. 996 * 997 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} 998 * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 999 * provisioning via an NFC bump. 1000 * 1001 * @hide 1002 */ 1003 @SystemApi 1004 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM = 1005 "android.app.extra.PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM"; 1006 1007 /** 1008 * A String extra holding a http cookie header which should be used in the http request to the 1009 * url specified in {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}. 1010 * 1011 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} 1012 * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1013 * provisioning via an NFC bump. 1014 * 1015 * @hide 1016 */ 1017 @SystemApi 1018 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER = 1019 "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER"; 1020 1021 /** 1022 * An extra of type {@link android.os.PersistableBundle} that allows the provisioning initiator 1023 * to pass data to the device policy management role holder. 1024 * 1025 * <p>The device policy management role holder will receive this extra via the {@link 1026 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent. 1027 * 1028 * <p>The contents of this extra are up to the contract between the provisioning initiator 1029 * and the device policy management role holder. 1030 * 1031 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} 1032 * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1033 * provisioning via an NFC bump. 1034 * 1035 * @hide 1036 */ 1037 @SystemApi 1038 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE = 1039 "android.app.extra.PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE"; 1040 1041 /** 1042 * A String extra containing the package name of the provisioning initiator. 1043 * 1044 * <p>Use in an intent with action {@link 1045 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}. 1046 * 1047 * @hide 1048 */ 1049 @SystemApi 1050 public static final String EXTRA_ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE = 1051 "android.app.extra.ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE"; 1052 1053 /** 1054 * An {@link Intent} result extra specifying the {@link Intent} to be launched after 1055 * provisioning is finalized. 1056 * 1057 * <p>If {@link #EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT} is set to {@code false}, 1058 * this result will be supplied as part of the result {@link Intent} for provisioning actions 1059 * such as {@link #ACTION_PROVISION_MANAGED_PROFILE}. This result will also be supplied as 1060 * part of the result {@link Intent} for the device policy management role holder provisioning 1061 * actions. 1062 */ 1063 public static final String EXTRA_RESULT_LAUNCH_INTENT = 1064 "android.app.extra.RESULT_LAUNCH_INTENT"; 1065 1066 /** 1067 * A boolean extra that determines whether the provisioning flow should launch the resulting 1068 * launch intent, if one is supplied by the device policy management role holder via {@link 1069 * #EXTRA_RESULT_LAUNCH_INTENT}. Default value is {@code false}. 1070 * 1071 * <p>If {@code true}, the resulting intent will be launched by the provisioning flow, if one 1072 * is supplied by the device policy management role holder. 1073 * 1074 * <p>If {@code false}, the resulting intent will be returned as {@link 1075 * #EXTRA_RESULT_LAUNCH_INTENT} to the provisioning initiator, if one is supplied by the device 1076 * manager role holder. It will be the responsibility of the provisioning initiator to launch 1077 * this {@link Intent} after provisioning completes. 1078 * 1079 * <p>This extra is respected when provided via the provisioning intent actions such as {@link 1080 * #ACTION_PROVISION_MANAGED_PROFILE}. 1081 */ 1082 public static final String EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT = 1083 "android.app.extra.PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT"; 1084 1085 /** 1086 * Action: Bugreport sharing with device owner has been accepted by the user. 1087 * 1088 * @hide 1089 */ 1090 public static final String ACTION_BUGREPORT_SHARING_ACCEPTED = 1091 "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED"; 1092 1093 /** 1094 * Action: Bugreport sharing with device owner has been declined by the user. 1095 * 1096 * @hide 1097 */ 1098 public static final String ACTION_BUGREPORT_SHARING_DECLINED = 1099 "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED"; 1100 1101 /** 1102 * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}. 1103 * 1104 * @hide 1105 */ 1106 public static final String ACTION_REMOTE_BUGREPORT_DISPATCH = 1107 "android.intent.action.REMOTE_BUGREPORT_DISPATCH"; 1108 1109 /** 1110 * Extra for shared bugreport's SHA-256 hash. 1111 * 1112 * @hide 1113 */ 1114 public static final String EXTRA_REMOTE_BUGREPORT_HASH = 1115 "android.intent.extra.REMOTE_BUGREPORT_HASH"; 1116 1117 /** 1118 * Extra for shared bugreport's nonce in long integer type. 1119 * 1120 * @hide 1121 */ 1122 public static final String EXTRA_REMOTE_BUGREPORT_NONCE = 1123 "android.intent.extra.REMOTE_BUGREPORT_NONCE"; 1124 1125 /** 1126 * Extra for remote bugreport notification shown type. 1127 * 1128 * @hide 1129 */ 1130 public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE = 1131 "android.app.extra.bugreport_notification_type"; 1132 1133 /** 1134 * Default value for preferential network service enabling. 1135 * 1136 * @hide 1137 */ 1138 public static final boolean PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT = false; 1139 1140 /** 1141 * Notification type for a started remote bugreport flow. 1142 * 1143 * @hide 1144 */ 1145 public static final int NOTIFICATION_BUGREPORT_STARTED = 1; 1146 1147 /** 1148 * Notification type for a bugreport that has already been accepted to be shared, but is still 1149 * being taken. 1150 * 1151 * @hide 1152 */ 1153 public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2; 1154 1155 /** 1156 * Notification type for a bugreport that has been taken and can be shared or declined. 1157 * 1158 * @hide 1159 */ 1160 public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3; 1161 1162 /** 1163 * Default and maximum timeout in milliseconds after which unlocking with weak auth times out, 1164 * i.e. the user has to use a strong authentication method like password, PIN or pattern. 1165 * 1166 * @hide 1167 */ 1168 public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h 1169 1170 /** 1171 * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that is 1172 * passed directly to the <a href="#devicepolicycontroller">Device Policy Controller</a> 1173 * after <a href="#managed-provisioning">provisioning</a>. 1174 * 1175 * <p> 1176 * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with 1177 * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC 1178 * message should contain a stringified {@link java.util.Properties} instance, whose string 1179 * properties will be converted into a {@link android.os.PersistableBundle} and passed to the 1180 * management application after provisioning. 1181 */ 1182 public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE = 1183 "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE"; 1184 1185 /** 1186 * A String extra holding the package name of the application that 1187 * will be set as <a href="#devicepolicycontroller">Device Policy Controller</a>. 1188 * 1189 * <p>When this extra is set, the application must have exactly one 1190 * {@link DeviceAdminReceiver device admin receiver}. This receiver will be set as the 1191 * <a href="#devicepolicycontroller">Device Policy Controller</a>. 1192 * 1193 * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. 1194 */ 1195 @Deprecated 1196 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME 1197 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME"; 1198 1199 /** 1200 * A ComponentName extra indicating the {@link DeviceAdminReceiver device admin receiver} of 1201 * the application that will be set as the <a href="#devicepolicycontroller"> 1202 * Device Policy Controller</a>. 1203 * 1204 * <p>If an application starts provisioning directly via an intent with action 1205 * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this 1206 * component has to match the package name of the application that started provisioning. 1207 * 1208 * <p>This component is set as device owner and active admin when device owner provisioning is 1209 * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC 1210 * message containing an NFC record with MIME type 1211 * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be 1212 * flattened to a string, via {@link ComponentName#flattenToShortString()}. 1213 */ 1214 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME 1215 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME"; 1216 1217 /** 1218 * An {@link android.accounts.Account} extra holding the account to migrate during managed 1219 * profile provisioning. 1220 * 1221 * <p>If the account supplied is present in the user, it will be copied, along with its 1222 * credentials to the managed profile and removed from the user. 1223 */ 1224 public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE 1225 = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE"; 1226 1227 /** 1228 * Boolean extra to indicate that the 1229 * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE migrated account} should be kept. 1230 * 1231 * <p>If it's set to {@code true}, the account will not be removed from the user after it is 1232 * migrated to the newly created user or profile. 1233 * 1234 * <p>Defaults to {@code false} 1235 * 1236 * @see #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE 1237 */ 1238 public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION 1239 = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION"; 1240 1241 /** 1242 * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the 1243 * device. 1244 */ 1245 @Deprecated 1246 public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS 1247 = "android.app.extra.PROVISIONING_EMAIL_ADDRESS"; 1248 1249 /** 1250 * A integer extra indicating the predominant color to show during the provisioning. 1251 * Refer to {@link android.graphics.Color} for how the color is represented. 1252 * 1253 * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or 1254 * {@link #ACTION_PROVISION_MANAGED_DEVICE}. 1255 * 1256 * @deprecated Color customization is no longer supported in the provisioning flow. 1257 */ 1258 @Deprecated 1259 public static final String EXTRA_PROVISIONING_MAIN_COLOR = 1260 "android.app.extra.PROVISIONING_MAIN_COLOR"; 1261 1262 /** 1263 * A Boolean extra that can be used by the mobile device management application to skip the 1264 * disabling of system apps during provisioning when set to {@code true}. 1265 * 1266 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC}, an intent with action 1267 * {@link #ACTION_PROVISION_MANAGED_PROFILE} that starts profile owner provisioning or 1268 * set as an extra to the intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity. 1269 */ 1270 public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED = 1271 "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED"; 1272 1273 /** 1274 * A String extra holding the time zone {@link android.app.AlarmManager} that the device 1275 * will be set to. 1276 * 1277 * <p>Use only for device owner provisioning. This extra can be returned by the admin app when 1278 * performing the admin-integrated provisioning flow as a result of the {@link 1279 * #ACTION_GET_PROVISIONING_MODE} activity. 1280 * 1281 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1282 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1283 */ 1284 public static final String EXTRA_PROVISIONING_TIME_ZONE 1285 = "android.app.extra.PROVISIONING_TIME_ZONE"; 1286 1287 /** 1288 * A Long extra holding the wall clock time (in milliseconds) to be set on the device's 1289 * {@link android.app.AlarmManager}. 1290 * 1291 * <p>Use only for device owner provisioning. This extra can be returned by the admin app when 1292 * performing the admin-integrated provisioning flow as a result of the {@link 1293 * #ACTION_GET_PROVISIONING_MODE} activity. 1294 * 1295 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1296 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1297 */ 1298 public static final String EXTRA_PROVISIONING_LOCAL_TIME 1299 = "android.app.extra.PROVISIONING_LOCAL_TIME"; 1300 1301 /** 1302 * A String extra holding the {@link java.util.Locale} that the device will be set to. 1303 * Format: xx_yy, where xx is the language code, and yy the country code. 1304 * 1305 * <p>Use only for device owner provisioning. This extra can be returned by the admin app when 1306 * performing the admin-integrated provisioning flow as a result of the {@link 1307 * #ACTION_GET_PROVISIONING_MODE} activity. 1308 * 1309 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1310 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1311 */ 1312 public static final String EXTRA_PROVISIONING_LOCALE 1313 = "android.app.extra.PROVISIONING_LOCALE"; 1314 1315 /** 1316 * A String extra holding the ssid of the wifi network that should be used during nfc device 1317 * owner provisioning for downloading the mobile device management application. 1318 * 1319 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1320 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1321 */ 1322 public static final String EXTRA_PROVISIONING_WIFI_SSID 1323 = "android.app.extra.PROVISIONING_WIFI_SSID"; 1324 1325 /** 1326 * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID} 1327 * is hidden or not. 1328 * 1329 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1330 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1331 */ 1332 public static final String EXTRA_PROVISIONING_WIFI_HIDDEN 1333 = "android.app.extra.PROVISIONING_WIFI_HIDDEN"; 1334 1335 /** 1336 * A String extra indicating the security type of the wifi network in 1337 * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA}, 1338 * {@code WEP} or {@code EAP}. 1339 * 1340 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1341 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1342 */ 1343 public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE 1344 = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE"; 1345 1346 /** 1347 * A String extra holding the password of the wifi network in 1348 * {@link #EXTRA_PROVISIONING_WIFI_SSID}. 1349 * 1350 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1351 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1352 */ 1353 public static final String EXTRA_PROVISIONING_WIFI_PASSWORD = 1354 "android.app.extra.PROVISIONING_WIFI_PASSWORD"; 1355 1356 /** 1357 * The EAP method of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID} 1358 * and could be one of {@code PEAP}, {@code TLS}, {@code TTLS}, {@code PWD}, {@code SIM}, 1359 * {@code AKA} or {@code AKA_PRIME}. This is only used if the 1360 * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}. 1361 * 1362 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1363 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1364 */ 1365 public static final String EXTRA_PROVISIONING_WIFI_EAP_METHOD = 1366 "android.app.extra.PROVISIONING_WIFI_EAP_METHOD"; 1367 1368 /** 1369 * The phase 2 authentication of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID} 1370 * and could be one of {@code NONE}, {@code PAP}, {@code MSCHAP}, {@code MSCHAPV2}, {@code GTC}, 1371 * {@code SIM}, {@code AKA} or {@code AKA_PRIME}. This is only used if the 1372 * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}. 1373 * 1374 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1375 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1376 */ 1377 public static final String EXTRA_PROVISIONING_WIFI_PHASE2_AUTH = 1378 "android.app.extra.PROVISIONING_WIFI_PHASE2_AUTH"; 1379 1380 /** 1381 * The CA certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This should 1382 * be an X.509 certificate Base64 encoded DER format, ie. PEM representation of a certificate 1383 * without header, footer and line breaks. <a href= 1384 * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only 1385 * used if the {@link 1386 * #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}. 1387 * 1388 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1389 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1390 */ 1391 public static final String EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE = 1392 "android.app.extra.PROVISIONING_WIFI_CA_CERTIFICATE"; 1393 1394 /** 1395 * The user certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This 1396 * should be an X.509 certificate and private key Base64 encoded DER format, ie. PEM 1397 * representation of a certificate and key without header, footer and line breaks. <a href= 1398 * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only 1399 * used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}. 1400 * 1401 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1402 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1403 */ 1404 public static final String EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE = 1405 "android.app.extra.PROVISIONING_WIFI_USER_CERTIFICATE"; 1406 1407 /** 1408 * The identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used 1409 * if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}. 1410 * 1411 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1412 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1413 */ 1414 public static final String EXTRA_PROVISIONING_WIFI_IDENTITY = 1415 "android.app.extra.PROVISIONING_WIFI_IDENTITY"; 1416 1417 /** 1418 * The anonymous identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is 1419 * only used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}. 1420 * 1421 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1422 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1423 */ 1424 1425 public static final String EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY = 1426 "android.app.extra.PROVISIONING_WIFI_ANONYMOUS_IDENTITY"; 1427 /** 1428 * The domain of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used if 1429 * the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}. 1430 * 1431 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1432 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1433 */ 1434 public static final String EXTRA_PROVISIONING_WIFI_DOMAIN = 1435 "android.app.extra.PROVISIONING_WIFI_DOMAIN"; 1436 1437 /** 1438 * A String extra holding the proxy host for the wifi network in 1439 * {@link #EXTRA_PROVISIONING_WIFI_SSID}. 1440 * 1441 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1442 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1443 */ 1444 public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST 1445 = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST"; 1446 1447 /** 1448 * An int extra holding the proxy port for the wifi network in 1449 * {@link #EXTRA_PROVISIONING_WIFI_SSID}. 1450 * 1451 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1452 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1453 */ 1454 public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT 1455 = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT"; 1456 1457 /** 1458 * A String extra holding the proxy bypass for the wifi network in 1459 * {@link #EXTRA_PROVISIONING_WIFI_SSID}. 1460 * 1461 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1462 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1463 */ 1464 public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS 1465 = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS"; 1466 1467 /** 1468 * A String extra holding the proxy auto-config (PAC) URL for the wifi network in 1469 * {@link #EXTRA_PROVISIONING_WIFI_SSID}. 1470 * 1471 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1472 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1473 */ 1474 public static final String EXTRA_PROVISIONING_WIFI_PAC_URL 1475 = "android.app.extra.PROVISIONING_WIFI_PAC_URL"; 1476 1477 /** 1478 * A String extra holding a url that specifies the download location of the device admin 1479 * package. When not provided it is assumed that the device admin package is already installed. 1480 * 1481 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1482 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1483 */ 1484 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION 1485 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION"; 1486 1487 /** 1488 * A String extra holding the localized name of the organization under management. 1489 * 1490 * The name is displayed only during provisioning. 1491 * 1492 * <p>Use in an intent with action {@link #ACTION_PROVISION_FINANCED_DEVICE} 1493 * 1494 * @hide 1495 */ 1496 @SystemApi 1497 public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME = 1498 "android.app.extra.PROVISIONING_ORGANIZATION_NAME"; 1499 1500 /** 1501 * A String extra holding a url to the website of the device provider so the user can open it 1502 * during provisioning. If the url is not HTTPS, an error will be shown. 1503 * 1504 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} 1505 * or {@link #ACTION_PROVISION_FINANCED_DEVICE} 1506 * 1507 * @hide 1508 */ 1509 @SystemApi 1510 public static final String EXTRA_PROVISIONING_SUPPORT_URL = 1511 "android.app.extra.PROVISIONING_SUPPORT_URL"; 1512 1513 /** 1514 * A String extra holding the localized name of the device admin package. It should be the same 1515 * as the app label of the package. 1516 * 1517 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} 1518 * or {@link #ACTION_PROVISION_FINANCED_DEVICE} 1519 * 1520 * @deprecated This extra is no longer respected in the provisioning flow. 1521 * @hide 1522 */ 1523 @Deprecated 1524 @SystemApi 1525 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL = 1526 "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL"; 1527 1528 /** 1529 * A {@link Uri} extra pointing to the app icon of device admin package. This image will be 1530 * shown during the provisioning. 1531 * <h5>The following URI schemes are accepted:</h5> 1532 * <ul> 1533 * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li> 1534 * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li> 1535 * </ul> 1536 * 1537 * <p> It is the responsibility of the caller to provide an image with a reasonable 1538 * pixel density for the device. 1539 * 1540 * <p> If a content: URI is passed, the intent should have the flag 1541 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the 1542 * {@link android.content.ClipData} of the intent too. 1543 * 1544 * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} 1545 * or {@link #ACTION_PROVISION_FINANCED_DEVICE} 1546 * 1547 * @deprecated This extra is no longer respected in the provisioning flow. 1548 * @hide 1549 */ 1550 @SystemApi 1551 @Deprecated 1552 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI = 1553 "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI"; 1554 1555 /** 1556 * An int extra holding a minimum required version code for the device admin package. If the 1557 * device admin is already installed on the device, it will only be re-downloaded from 1558 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the 1559 * installed package is less than this version code. 1560 * 1561 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1562 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1563 */ 1564 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE 1565 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE"; 1566 1567 /** 1568 * A String extra holding a http cookie header which should be used in the http request to the 1569 * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}. 1570 * 1571 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1572 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1573 */ 1574 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER 1575 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER"; 1576 1577 /** 1578 * A String extra holding the URL-safe base64 encoded SHA-256 hash of the file at download 1579 * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}. 1580 * 1581 * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be 1582 * present. The provided checksum must match the checksum of the file at the download 1583 * location. If the checksum doesn't match an error will be shown to the user and the user will 1584 * be asked to factory reset the device. 1585 * 1586 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1587 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1588 * 1589 * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP} 1590 * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported. 1591 * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in 1592 * addition to SHA-1. From {@link android.os.Build.VERSION_CODES#Q}, only SHA-256 hash is 1593 * supported. 1594 */ 1595 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM 1596 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM"; 1597 1598 /** 1599 * A boolean extra indicating the admin of a fully-managed device opts out of controlling 1600 * permission grants for sensor-related permissions, 1601 * see {@link #setPermissionGrantState(ComponentName, String, String, int)}. 1602 * 1603 * The default for this extra is {@code false} - by default, the admin of a fully-managed 1604 * device has the ability to grant sensors-related permissions. 1605 * 1606 * <p>Use only for device owner provisioning. This extra can be returned by the 1607 * admin app when performing the admin-integrated provisioning flow as a result of the 1608 * {@link #ACTION_GET_PROVISIONING_MODE} activity. 1609 * 1610 * <p>This extra may also be provided to the admin app via an intent extra for {@link 1611 * #ACTION_GET_PROVISIONING_MODE}. 1612 * 1613 * @see #ACTION_GET_PROVISIONING_MODE 1614 */ 1615 public static final String EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT = 1616 "android.app.extra.PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT"; 1617 1618 /** 1619 * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the 1620 * android package archive at the download location specified in {@link 1621 * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}. 1622 * 1623 * <p>The signatures of an android package archive can be obtained using 1624 * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag 1625 * {@link android.content.pm.PackageManager#GET_SIGNATURES}. 1626 * 1627 * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be 1628 * present. The provided checksum must match the checksum of any signature of the file at 1629 * the download location. If the checksum does not match an error will be shown to the user and 1630 * the user will be asked to factory reset the device. 1631 * 1632 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner 1633 * provisioning via an NFC bump. It can also be used for QR code provisioning. 1634 */ 1635 public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM 1636 = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM"; 1637 1638 /** 1639 * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile 1640 * has completed successfully. 1641 * 1642 * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning 1643 * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}. 1644 * 1645 * <p>This intent will contain the following extras 1646 * <ul> 1647 * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed 1648 * profile.</li> 1649 * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to 1650 * be migrated at provisioning time, if any.</li> 1651 * </ul> 1652 */ 1653 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 1654 public static final String ACTION_MANAGED_PROFILE_PROVISIONED 1655 = "android.app.action.MANAGED_PROFILE_PROVISIONED"; 1656 1657 /** 1658 * Activity action: This activity action is sent to indicate that provisioning of a managed 1659 * profile or managed device has completed successfully. It'll be sent at the same time as 1660 * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be 1661 * delivered faster as it's an activity intent. 1662 * 1663 * <p>The intent is only sent to the new device or profile owner. 1664 * 1665 * @see #ACTION_PROVISION_MANAGED_PROFILE 1666 * @see #ACTION_PROVISION_MANAGED_DEVICE 1667 */ 1668 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 1669 public static final String ACTION_PROVISIONING_SUCCESSFUL = 1670 "android.app.action.PROVISIONING_SUCCESSFUL"; 1671 1672 /** 1673 * A boolean extra indicating whether device encryption can be skipped as part of 1674 * <a href="#managed-provisioning">provisioning</a>. 1675 * 1676 * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action 1677 * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning. 1678 * 1679 * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an 1680 * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}. 1681 */ 1682 public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION = 1683 "android.app.extra.PROVISIONING_SKIP_ENCRYPTION"; 1684 1685 /** 1686 * A {@link Uri} extra pointing to a logo image. This image will be shown during the 1687 * provisioning. If this extra is not passed, a default image will be shown. 1688 * 1689 * <p><b>The following URI schemes are accepted:</b> 1690 * <ul> 1691 * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li> 1692 * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li> 1693 * </ul> 1694 * 1695 * <p>It is the responsibility of the caller to provide an image with a reasonable 1696 * pixel density for the device. 1697 * 1698 * <p>If a content: URI is passed, the intent should also have the flag 1699 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the 1700 * {@link android.content.ClipData} of the intent. 1701 * 1702 * @deprecated Logo customization is no longer supported in the 1703 * <a href="#managedprovisioning">provisioning flow</a>. 1704 */ 1705 @Deprecated 1706 public static final String EXTRA_PROVISIONING_LOGO_URI = 1707 "android.app.extra.PROVISIONING_LOGO_URI"; 1708 1709 /** 1710 * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents. 1711 * 1712 * <p>Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER} 1713 * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer 1714 * content. 1715 * 1716 * <p> The extra typically contains one disclaimer from the company of mobile device 1717 * management application (MDM), and one disclaimer from the organization. 1718 * 1719 * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[] 1720 * 1721 * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored. 1722 * 1723 * <p> Can be used in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}. This 1724 * extra can also be returned by the admin app when performing the admin-integrated 1725 * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity. 1726 */ 1727 public static final String EXTRA_PROVISIONING_DISCLAIMERS = 1728 "android.app.extra.PROVISIONING_DISCLAIMERS"; 1729 1730 /** 1731 * A String extra of localized disclaimer header. 1732 * 1733 * <p>The extra is typically the company name of mobile device management application (MDM) 1734 * or the organization name. 1735 * 1736 * <p>{@link ApplicationInfo#FLAG_SYSTEM System apps} can also insert a disclaimer by declaring 1737 * an application-level meta-data in {@code AndroidManifest.xml}. 1738 * 1739 * <p>For example: 1740 * <pre> 1741 * <meta-data 1742 * android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER" 1743 * android:resource="@string/disclaimer_header" 1744 * /></pre> 1745 * 1746 * <p>This must be accompanied with another extra using the key 1747 * {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. 1748 */ 1749 public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER = 1750 "android.app.extra.PROVISIONING_DISCLAIMER_HEADER"; 1751 1752 /** 1753 * A {@link Uri} extra pointing to disclaimer content. 1754 * 1755 * <h5>The following URI schemes are accepted:</h5> 1756 * <ul> 1757 * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li> 1758 * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li> 1759 * </ul> 1760 * 1761 * <p>Styled text is supported. This is parsed by {@link android.text.Html#fromHtml(String)} 1762 * and displayed in a {@link android.widget.TextView}. 1763 * 1764 * <p>If a <code>content:</code> URI is passed, the intent should also have the 1765 * flag {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the 1766 * {@link android.content.ClipData} of the intent. 1767 * 1768 * <p>{@link ApplicationInfo#FLAG_SYSTEM System apps} can also insert a 1769 * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}. 1770 * 1771 * <p>For example: 1772 * 1773 * <pre> 1774 * <meta-data 1775 * android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT" 1776 * android:resource="@string/disclaimer_content" 1777 * /></pre> 1778 * 1779 * <p>This must be accompanied with another extra using the key 1780 * {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. 1781 */ 1782 public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT = 1783 "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"; 1784 1785 /** 1786 * A boolean extra indicating if the user consent steps from the 1787 * <a href="#managed-provisioning">provisioning flow</a> should be skipped. 1788 * 1789 * <p>If unspecified, defaults to {@code false}. 1790 * 1791 * @deprecated this extra is no longer relevant as device owners cannot create managed profiles 1792 */ 1793 @Deprecated 1794 public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT = 1795 "android.app.extra.PROVISIONING_SKIP_USER_CONSENT"; 1796 1797 /** 1798 * A boolean extra indicating if the education screens from the provisioning flow should be 1799 * skipped. If unspecified, defaults to {@code false}. 1800 * 1801 * <p>This extra can be set in the following ways: 1802 * <ul> 1803 * <li>By the admin app when performing the admin-integrated 1804 * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity</li> 1805 * <li>For managed account enrollment</li> 1806 * </ul> 1807 * 1808 * <p>If the education screens are skipped, it is the admin application's responsibility 1809 * to display its own user education screens. 1810 */ 1811 public static final String EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS = 1812 "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS"; 1813 1814 /** 1815 * A boolean extra indicating if mobile data should be used during the provisioning flow 1816 * for downloading the admin app. If {@link #EXTRA_PROVISIONING_WIFI_SSID} is also specified, 1817 * wifi network will be used instead. 1818 * 1819 * <p>Default value is {@code false}. 1820 * 1821 * <p>If this extra is set to {@code true} and {@link #EXTRA_PROVISIONING_WIFI_SSID} is not 1822 * specified, this extra has different behaviour depending on the way provisioning is triggered: 1823 * <ul> 1824 * <li> 1825 * For provisioning started via a QR code or an NFC tag, mobile data is always used for 1826 * downloading the admin app. 1827 * </li> 1828 * <li> 1829 * For all other provisioning methods, a mobile data connection check is made at the start 1830 * of provisioning. If mobile data is connected at that point, the admin app download will 1831 * happen using mobile data. If mobile data is not connected at that point, the end-user 1832 * will be asked to pick a wifi network and the admin app download will proceed over wifi. 1833 * </li> 1834 * </ul> 1835 */ 1836 public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA = 1837 "android.app.extra.PROVISIONING_USE_MOBILE_DATA"; 1838 1839 /** 1840 * Possible values for {@link #EXTRA_PROVISIONING_TRIGGER}. 1841 * 1842 * @hide 1843 */ 1844 @IntDef(prefix = { "PROVISIONING_TRIGGER_" }, value = { 1845 PROVISIONING_TRIGGER_UNSPECIFIED, 1846 PROVISIONING_TRIGGER_CLOUD_ENROLLMENT, 1847 PROVISIONING_TRIGGER_QR_CODE, 1848 PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER, 1849 PROVISIONING_TRIGGER_MANAGED_ACCOUNT, 1850 PROVISIONING_TRIGGER_NFC 1851 }) 1852 @Retention(RetentionPolicy.SOURCE) 1853 public @interface ProvisioningTrigger {} 1854 1855 /** 1856 * Flags for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES}. 1857 * 1858 * @hide 1859 */ 1860 @IntDef(flag = true, prefix = { "FLAG_SUPPORTED_MODES_" }, value = { 1861 FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED, 1862 FLAG_SUPPORTED_MODES_PERSONALLY_OWNED, 1863 FLAG_SUPPORTED_MODES_DEVICE_OWNER 1864 }) 1865 @Retention(RetentionPolicy.SOURCE) 1866 public @interface ProvisioningConfiguration {} 1867 1868 /** 1869 * An int extra holding the provisioning trigger. It could be one of 1870 * {@link #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT}, {@link #PROVISIONING_TRIGGER_QR_CODE}, 1871 * {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} or {@link 1872 * #PROVISIONING_TRIGGER_UNSPECIFIED}. 1873 * 1874 * <p>Use in an intent with action {@link 1875 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}. 1876 * @hide 1877 */ 1878 @SystemApi 1879 public static final String EXTRA_PROVISIONING_TRIGGER = 1880 "android.app.extra.PROVISIONING_TRIGGER"; 1881 1882 /** 1883 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning 1884 * trigger has not been specified. 1885 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT 1886 * @see #PROVISIONING_TRIGGER_QR_CODE 1887 * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT 1888 * @see #PROVISIONING_TRIGGER_NFC 1889 * @hide 1890 */ 1891 @SystemApi 1892 public static final int PROVISIONING_TRIGGER_UNSPECIFIED = 0; 1893 1894 /** 1895 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning 1896 * trigger is cloud enrollment. 1897 * @see #PROVISIONING_TRIGGER_QR_CODE 1898 * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT 1899 * @see #PROVISIONING_TRIGGER_UNSPECIFIED 1900 * @see #PROVISIONING_TRIGGER_NFC 1901 * @hide 1902 */ 1903 @SystemApi 1904 public static final int PROVISIONING_TRIGGER_CLOUD_ENROLLMENT = 1; 1905 1906 /** 1907 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning 1908 * trigger is the QR code scanner. 1909 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT 1910 * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT 1911 * @see #PROVISIONING_TRIGGER_UNSPECIFIED 1912 * @see #PROVISIONING_TRIGGER_NFC 1913 * @hide 1914 */ 1915 @SystemApi 1916 public static final int PROVISIONING_TRIGGER_QR_CODE = 2; 1917 1918 /** 1919 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning 1920 * trigger is persistent device owner enrollment. 1921 * <p>This constant is meant to represent a specific type of managed account provisioning which 1922 * provisions a device to a device owner by invoking the standard provisioning flow (where 1923 * the ManagedProvisioning component downloads and installs the admin app), as opposed to 1924 * relying on the provisioning trigger to handle download and install of the admin app. 1925 * <p>As of {@link android.os.Build.VERSION_CODES#S}, this constant is no longer used in favor 1926 * of the more general {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} which handles all managed 1927 * account provisioning types. 1928 * @deprecated Use the broader {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} instead 1929 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT 1930 * @see #PROVISIONING_TRIGGER_QR_CODE 1931 * @see #PROVISIONING_TRIGGER_UNSPECIFIED 1932 * @see #PROVISIONING_TRIGGER_NFC 1933 * @hide 1934 */ 1935 @SystemApi 1936 @Deprecated 1937 public static final int PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER = 3; 1938 1939 /** 1940 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning 1941 * trigger is managed account enrollment. 1942 * <p> 1943 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT 1944 * @see #PROVISIONING_TRIGGER_QR_CODE 1945 * @see #PROVISIONING_TRIGGER_UNSPECIFIED 1946 * @see #PROVISIONING_TRIGGER_NFC 1947 * @hide 1948 */ 1949 @SystemApi 1950 public static final int PROVISIONING_TRIGGER_MANAGED_ACCOUNT = 4; 1951 1952 /** 1953 * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning is 1954 * triggered by tapping an NFC tag. 1955 * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT 1956 * @see #PROVISIONING_TRIGGER_QR_CODE 1957 * @see #PROVISIONING_TRIGGER_UNSPECIFIED 1958 * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT 1959 * @hide 1960 */ 1961 @SystemApi 1962 public static final int PROVISIONING_TRIGGER_NFC = 5; 1963 1964 /** 1965 * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning is 1966 * organization-owned. 1967 * 1968 * <p>Using this value indicates the admin app can only be provisioned in either a 1969 * fully-managed device or a corporate-owned work profile. This will cause the admin app's 1970 * {@link #ACTION_GET_PROVISIONING_MODE} activity to have the {@link 1971 * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link 1972 * #PROVISIONING_MODE_MANAGED_PROFILE} and {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}. 1973 * 1974 * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}. In 1975 * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have 1976 * the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link 1977 * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and 1978 * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}. 1979 * 1980 * @hide 1981 */ 1982 @SystemApi 1983 public static final int FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED = 1; 1984 1985 /** 1986 * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning 1987 * is personally-owned. 1988 * 1989 * <p>Using this flag will cause the admin app's {@link #ACTION_GET_PROVISIONING_MODE} 1990 * activity to have the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra 1991 * contain only {@link #PROVISIONING_MODE_MANAGED_PROFILE}. 1992 * 1993 * <p>Also, if this flag is set, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity 1994 * will not receive the {@link #EXTRA_PROVISIONING_IMEI} and {@link 1995 * #EXTRA_PROVISIONING_SERIAL_NUMBER} extras. 1996 * 1997 * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}. In 1998 * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have the 1999 * {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link 2000 * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and 2001 * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}. 2002 * 2003 * @hide 2004 */ 2005 @SystemApi 2006 public static final int FLAG_SUPPORTED_MODES_PERSONALLY_OWNED = 1 << 1; 2007 2008 /** 2009 * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that the only 2010 * supported provisioning mode is device owner. 2011 * 2012 * @hide 2013 */ 2014 @SystemApi 2015 public static final int FLAG_SUPPORTED_MODES_DEVICE_OWNER = 1 << 2; 2016 2017 /** 2018 * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and 2019 * {@link #setMinimumRequiredWifiSecurityLevel(int)}: no minimum security level. 2020 * 2021 * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant 2022 * represents the current minimum security level required. 2023 * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the 2024 * minimum security level a Wi-Fi network must meet. 2025 * 2026 * @see #WIFI_SECURITY_PERSONAL 2027 * @see #WIFI_SECURITY_ENTERPRISE_EAP 2028 * @see #WIFI_SECURITY_ENTERPRISE_192 2029 */ 2030 public static final int WIFI_SECURITY_OPEN = 0; 2031 2032 /** 2033 * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and 2034 * {@link #setMinimumRequiredWifiSecurityLevel(int)}: personal network such as WEP, WPA2-PSK. 2035 * 2036 * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant 2037 * represents the current minimum security level required. 2038 * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the 2039 * minimum security level a Wi-Fi network must meet. 2040 * 2041 * @see #WIFI_SECURITY_OPEN 2042 * @see #WIFI_SECURITY_ENTERPRISE_EAP 2043 * @see #WIFI_SECURITY_ENTERPRISE_192 2044 */ 2045 public static final int WIFI_SECURITY_PERSONAL = 1; 2046 2047 /** 2048 * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and 2049 * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise EAP network. 2050 * 2051 * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant 2052 * represents the current minimum security level required. 2053 * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the 2054 * minimum security level a Wi-Fi network must meet. 2055 * 2056 * @see #WIFI_SECURITY_OPEN 2057 * @see #WIFI_SECURITY_PERSONAL 2058 * @see #WIFI_SECURITY_ENTERPRISE_192 2059 */ 2060 public static final int WIFI_SECURITY_ENTERPRISE_EAP = 2; 2061 2062 /** 2063 * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and 2064 * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise 192 bit network. 2065 * 2066 * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant 2067 * represents the current minimum security level required. 2068 * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the 2069 * minimum security level a Wi-Fi network must meet. 2070 * 2071 * @see #WIFI_SECURITY_OPEN 2072 * @see #WIFI_SECURITY_PERSONAL 2073 * @see #WIFI_SECURITY_ENTERPRISE_EAP 2074 */ 2075 public static final int WIFI_SECURITY_ENTERPRISE_192 = 3; 2076 2077 /** 2078 * Possible Wi-Fi minimum security levels 2079 * 2080 * @hide */ 2081 @Retention(RetentionPolicy.SOURCE) 2082 @IntDef(prefix = {"WIFI_SECURITY_"}, value = { 2083 WIFI_SECURITY_OPEN, 2084 WIFI_SECURITY_PERSONAL, 2085 WIFI_SECURITY_ENTERPRISE_EAP, 2086 WIFI_SECURITY_ENTERPRISE_192}) 2087 public @interface WifiSecurity {} 2088 2089 /** 2090 * This MIME type is used for starting the device owner provisioning. 2091 * 2092 * <p>During device owner provisioning a device admin app is set as the owner of the device. 2093 * A device owner has full control over the device. The device owner can not be modified by the 2094 * user and the only way of resetting the device is if the device owner app calls a factory 2095 * reset. 2096 * 2097 * <p> A typical use case would be a device that is owned by a company, but used by either an 2098 * employee or client. 2099 * 2100 * <p> The NFC message must be sent to an unprovisioned device. 2101 * 2102 * <p>The NFC record must contain a serialized {@link java.util.Properties} object which 2103 * contains the following properties: 2104 * <ul> 2105 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li> 2106 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li> 2107 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li> 2108 * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li> 2109 * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li> 2110 * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li> 2111 * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li> 2112 * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li> 2113 * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li> 2114 * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li> 2115 * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li> 2116 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li> 2117 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li> 2118 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li> 2119 * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li> 2120 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from {@link 2121 * android.os.Build.VERSION_CODES#M} </li> 2122 * <li>{@link #EXTRA_PROVISIONING_WIFI_EAP_METHOD}, optional, supported from {@link 2123 * android.os.Build.VERSION_CODES#Q}</li> 2124 * <li>{@link #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}, optional, supported from {@link 2125 * android.os.Build.VERSION_CODES#Q}</li> 2126 * <li>{@link #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}, optional, supported from {@link 2127 * android.os.Build.VERSION_CODES#Q}</li> 2128 * <li>{@link #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}, optional, supported from {@link 2129 * android.os.Build.VERSION_CODES#Q}</li> 2130 * <li>{@link #EXTRA_PROVISIONING_WIFI_IDENTITY}, optional, supported from {@link 2131 * android.os.Build.VERSION_CODES#Q}</li> 2132 * <li>{@link #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}, optional, supported from {@link 2133 * android.os.Build.VERSION_CODES#Q}</li> 2134 * <li>{@link #EXTRA_PROVISIONING_WIFI_DOMAIN}, optional, supported from {@link 2135 * android.os.Build.VERSION_CODES#Q}</li></ul> 2136 * 2137 * <p> 2138 * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain 2139 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of 2140 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only 2141 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported). 2142 */ 2143 public static final String MIME_TYPE_PROVISIONING_NFC 2144 = "application/com.android.managedprovisioning"; 2145 2146 /** 2147 * Activity action: ask the user to add a new device administrator to the system. 2148 * The desired policy is the ComponentName of the policy in the 2149 * {@link #EXTRA_DEVICE_ADMIN} extra field. This will invoke a UI to 2150 * bring the user through adding the device administrator to the system (or 2151 * allowing them to reject it). 2152 * 2153 * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION} 2154 * field to provide the user with additional explanation (in addition 2155 * to your component's description) about what is being added. 2156 * 2157 * <p>If your administrator is already active, this will ordinarily return immediately (without 2158 * user intervention). However, if your administrator has been updated and is requesting 2159 * additional uses-policy flags, the user will be presented with the new list. New policies 2160 * will not be available to the updated administrator until the user has accepted the new list. 2161 */ 2162 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 2163 public static final String ACTION_ADD_DEVICE_ADMIN 2164 = "android.app.action.ADD_DEVICE_ADMIN"; 2165 2166 /** 2167 * @hide 2168 * Activity action: ask the user to add a new device administrator as the profile owner 2169 * for this user. Only system apps can launch this intent. 2170 * 2171 * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN} 2172 * extra field. This will invoke a UI to bring the user through adding the profile owner admin 2173 * to remotely control restrictions on the user. 2174 * 2175 * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the 2176 * result of whether or not the user approved the action. If approved, the result will 2177 * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well 2178 * as a profile owner. 2179 * 2180 * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION} 2181 * field to provide the user with additional explanation (in addition 2182 * to your component's description) about what is being added. 2183 * 2184 * <p>If there is already a profile owner active or the caller is not a system app, the 2185 * operation will return a failure result. 2186 */ 2187 @SystemApi 2188 public static final String ACTION_SET_PROFILE_OWNER 2189 = "android.app.action.SET_PROFILE_OWNER"; 2190 2191 /** 2192 * @hide 2193 * Name of the profile owner admin that controls the user. 2194 */ 2195 @SystemApi 2196 public static final String EXTRA_PROFILE_OWNER_NAME 2197 = "android.app.extra.PROFILE_OWNER_NAME"; 2198 2199 /** 2200 * Broadcast action: send when any policy admin changes a policy. 2201 * This is generally used to find out when a new policy is in effect. 2202 * 2203 * If the profile owner of an organization-owned managed profile changes some user 2204 * restriction explicitly on the parent user, this broadcast will <em>not</em> be 2205 * sent to the parent user. 2206 * @hide 2207 */ 2208 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 2209 public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED 2210 = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED"; 2211 2212 /** 2213 * Broadcast action: sent when the device owner is set, changed or cleared. 2214 * 2215 * This broadcast is sent only to the primary user. 2216 * @see #ACTION_PROVISION_MANAGED_DEVICE 2217 * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle) 2218 */ 2219 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 2220 public static final String ACTION_DEVICE_OWNER_CHANGED 2221 = "android.app.action.DEVICE_OWNER_CHANGED"; 2222 2223 /** 2224 * Broadcast action: sent when the factory reset protection (FRP) policy is changed. 2225 * 2226 * @see #setFactoryResetProtectionPolicy 2227 * @hide 2228 */ 2229 @RequiresPermission(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION) 2230 @SystemApi 2231 public static final String ACTION_RESET_PROTECTION_POLICY_CHANGED = 2232 "android.app.action.RESET_PROTECTION_POLICY_CHANGED"; 2233 2234 /** 2235 * Broadcast action: sent when there is a location update on a device in lost mode. This 2236 * broadcast is explicitly sent to the device policy controller app only. 2237 * 2238 * @see DevicePolicyManager#sendLostModeLocationUpdate 2239 * @hide 2240 */ 2241 @SystemApi 2242 public static final String ACTION_LOST_MODE_LOCATION_UPDATE = 2243 "android.app.action.LOST_MODE_LOCATION_UPDATE"; 2244 2245 /** 2246 * Extra used with {@link #ACTION_LOST_MODE_LOCATION_UPDATE} to send the location of a device 2247 * in lost mode. Value is {@code Location}. 2248 * 2249 * @see DevicePolicyManager#sendLostModeLocationUpdate 2250 * @hide 2251 */ 2252 @SystemApi 2253 public static final String EXTRA_LOST_MODE_LOCATION = 2254 "android.app.extra.LOST_MODE_LOCATION"; 2255 2256 /** 2257 * The ComponentName of the administrator component. 2258 * 2259 * @see #ACTION_ADD_DEVICE_ADMIN 2260 */ 2261 public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN"; 2262 2263 /** 2264 * An optional CharSequence providing additional explanation for why the 2265 * admin is being added. 2266 * 2267 * @see #ACTION_ADD_DEVICE_ADMIN 2268 */ 2269 public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION"; 2270 2271 /** 2272 * Constant to indicate the feature of disabling the camera. Used as argument to 2273 * {@link #createAdminSupportIntent(String)}. 2274 * @see #setCameraDisabled(ComponentName, boolean) 2275 */ 2276 public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera"; 2277 2278 /** 2279 * Constant to indicate the feature of disabling screen captures. Used as argument to 2280 * {@link #createAdminSupportIntent(String)}. 2281 * @see #setScreenCaptureDisabled(ComponentName, boolean) 2282 */ 2283 public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture"; 2284 2285 /** 2286 * Constant to indicate the feature of suspending app. Use it as the value of 2287 * {@link #EXTRA_RESTRICTION}. 2288 * @hide 2289 */ 2290 public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages"; 2291 2292 /** 2293 * A String indicating a specific restricted feature. Can be a user restriction from the 2294 * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values 2295 * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}. 2296 * @see #createAdminSupportIntent(String) 2297 * @hide 2298 */ 2299 @SystemApi 2300 public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION"; 2301 2302 /** 2303 * Activity action: have the user enter a new password. 2304 * 2305 * <p>For admin apps, this activity should be launched after using {@link 2306 * #setPasswordQuality(ComponentName, int)}, or {@link 2307 * #setPasswordMinimumLength(ComponentName, int)} to have the user enter a new password that 2308 * meets the current requirements. You can use {@link #isActivePasswordSufficient()} to 2309 * determine whether you need to have the user select a new password in order to meet the 2310 * current constraints. Upon being resumed from this activity, you can check the new 2311 * password characteristics to see if they are sufficient. 2312 * 2313 * <p>Non-admin apps can use {@link #getPasswordComplexity()} to check the current screen lock 2314 * complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest 2315 * to users how complex the app wants the new screen lock to be. Note that both {@link 2316 * #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the 2317 * calling app to have the permission {@link permission#REQUEST_PASSWORD_COMPLEXITY}. 2318 * 2319 * <p>If the intent is launched from within a managed profile with a profile 2320 * owner built against {@link android.os.Build.VERSION_CODES#M} or before, 2321 * this will trigger entering a new password for the parent of the profile. 2322 * For all other cases it will trigger entering a new password for the user 2323 * or profile it is launched from. 2324 * 2325 * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD 2326 */ 2327 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 2328 public static final String ACTION_SET_NEW_PASSWORD 2329 = "android.app.action.SET_NEW_PASSWORD"; 2330 2331 /** 2332 * An integer indicating the complexity level of the new password an app would like the user to 2333 * set when launching the action {@link #ACTION_SET_NEW_PASSWORD}. 2334 * 2335 * <p>Must be one of 2336 * <ul> 2337 * <li>{@link #PASSWORD_COMPLEXITY_HIGH} 2338 * <li>{@link #PASSWORD_COMPLEXITY_MEDIUM} 2339 * <li>{@link #PASSWORD_COMPLEXITY_LOW} 2340 * <li>{@link #PASSWORD_COMPLEXITY_NONE} 2341 * </ul> 2342 * 2343 * <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}. 2344 */ 2345 @RequiresPermission(REQUEST_PASSWORD_COMPLEXITY) 2346 public static final String EXTRA_PASSWORD_COMPLEXITY = 2347 "android.app.extra.PASSWORD_COMPLEXITY"; 2348 2349 /** 2350 * Constant for {@link #getPasswordComplexity()} and 2351 * {@link #setRequiredPasswordComplexity(int)}: no password. 2352 * 2353 * <p> When returned from {@link #getPasswordComplexity()}, the constant represents 2354 * the exact complexity band the password is in. 2355 * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity 2356 * band which the password must meet. 2357 */ 2358 public static final int PASSWORD_COMPLEXITY_NONE = 0; 2359 2360 /** 2361 * Constant for {@link #getPasswordComplexity()} and 2362 * {@link #setRequiredPasswordComplexity(int)}. 2363 * Define the low password complexity band as: 2364 * <ul> 2365 * <li>pattern 2366 * <li>PIN with repeating (4444) or ordered (1234, 4321, 2468) sequences 2367 * </ul> 2368 * 2369 * <p> When returned from {@link #getPasswordComplexity()}, the constant represents 2370 * the exact complexity band the password is in. 2371 * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity 2372 * band which the password must meet. 2373 * 2374 * @see #PASSWORD_QUALITY_SOMETHING 2375 * @see #PASSWORD_QUALITY_NUMERIC 2376 */ 2377 public static final int PASSWORD_COMPLEXITY_LOW = 0x10000; 2378 2379 /** 2380 * Constant for {@link #getPasswordComplexity()} and 2381 * {@link #setRequiredPasswordComplexity(int)}. 2382 * Define the medium password complexity band as: 2383 * <ul> 2384 * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at 2385 * least 4 2386 * <li>alphabetic, length at least 4 2387 * <li>alphanumeric, length at least 4 2388 * </ul> 2389 * 2390 * <p> When returned from {@link #getPasswordComplexity()}, the constant represents 2391 * the exact complexity band the password is in. 2392 * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity 2393 * band which the password must meet. 2394 * 2395 * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX 2396 * @see #PASSWORD_QUALITY_ALPHABETIC 2397 * @see #PASSWORD_QUALITY_ALPHANUMERIC 2398 */ 2399 public static final int PASSWORD_COMPLEXITY_MEDIUM = 0x30000; 2400 2401 /** 2402 * Constant for {@link #getPasswordComplexity()} and 2403 * {@link #setRequiredPasswordComplexity(int)}. 2404 * Define the high password complexity band as: 2405 * <ul> 2406 * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at 2407 * least 8 2408 * <li>alphabetic, length at least 6 2409 * <li>alphanumeric, length at least 6 2410 * </ul> 2411 * 2412 * <p> When returned from {@link #getPasswordComplexity()}, the constant represents 2413 * the exact complexity band the password is in. 2414 * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity 2415 * band which the password must meet. 2416 * 2417 * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX 2418 * @see #PASSWORD_QUALITY_ALPHABETIC 2419 * @see #PASSWORD_QUALITY_ALPHANUMERIC 2420 */ 2421 public static final int PASSWORD_COMPLEXITY_HIGH = 0x50000; 2422 2423 /** 2424 * A boolean extra for {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} requesting that only 2425 * device password requirement is enforced during the parent profile password enrolment flow. 2426 * <p> Normally when enrolling password for the parent profile, both the device-wide password 2427 * requirement (requirement set via {@link #getParentProfileInstance(ComponentName)} instance) 2428 * and the profile password requirement are enforced, if the profile currently does not have a 2429 * separate work challenge. By setting this to {@code true}, profile password requirement is 2430 * explicitly disregarded. 2431 * 2432 * @see #isActivePasswordSufficientForDeviceRequirement() 2433 */ 2434 public static final String EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY = 2435 "android.app.extra.DEVICE_PASSWORD_REQUIREMENT_ONLY"; 2436 2437 /** 2438 * @hide 2439 */ 2440 @Retention(RetentionPolicy.SOURCE) 2441 @IntDef(prefix = {"PASSWORD_COMPLEXITY_"}, value = { 2442 PASSWORD_COMPLEXITY_NONE, 2443 PASSWORD_COMPLEXITY_LOW, 2444 PASSWORD_COMPLEXITY_MEDIUM, 2445 PASSWORD_COMPLEXITY_HIGH, 2446 }) 2447 public @interface PasswordComplexity {} 2448 2449 /** 2450 * Indicates that nearby streaming is not controlled by policy, which means nearby streaming is 2451 * allowed. 2452 */ 2453 public static final int NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY = 0; 2454 2455 /** Indicates that nearby streaming is disabled. */ 2456 public static final int NEARBY_STREAMING_DISABLED = 1; 2457 2458 /** Indicates that nearby streaming is enabled. */ 2459 public static final int NEARBY_STREAMING_ENABLED = 2; 2460 2461 /** 2462 * Indicates that nearby streaming is enabled only to devices offering a comparable level of 2463 * security, with the same authenticated managed account. 2464 */ 2465 public static final int NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY = 3; 2466 2467 /** 2468 * @hide 2469 */ 2470 @Retention(RetentionPolicy.SOURCE) 2471 @IntDef(prefix = {"NEARBY_STREAMING_"}, value = { 2472 NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY, 2473 NEARBY_STREAMING_DISABLED, 2474 NEARBY_STREAMING_ENABLED, 2475 NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY, 2476 }) 2477 public @interface NearbyStreamingPolicy {} 2478 2479 /** 2480 * Activity action: have the user enter a new password for the parent profile. 2481 * If the intent is launched from within a managed profile, this will trigger 2482 * entering a new password for the parent of the profile. The caller can optionally 2483 * set {@link #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY} to only enforce device-wide 2484 * password requirement. In all other cases the behaviour is identical to 2485 * {@link #ACTION_SET_NEW_PASSWORD}. 2486 */ 2487 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 2488 public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD 2489 = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD"; 2490 2491 /** 2492 * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when 2493 * Network logging was enabled and the user tapped the notification. 2494 * <p class="note">This is a protected intent that can only be sent by the system.</p> 2495 * @hide 2496 */ 2497 public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG 2498 = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG"; 2499 2500 /** 2501 * Broadcast Action: Sent after application delegation scopes are changed. The new delegation 2502 * scopes will be sent in an {@code ArrayList<String>} extra identified by the 2503 * {@link #EXTRA_DELEGATION_SCOPES} key. 2504 * 2505 * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the 2506 * system.</p> 2507 */ 2508 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 2509 public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED = 2510 "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED"; 2511 2512 /** 2513 * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the 2514 * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast. 2515 */ 2516 public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES"; 2517 2518 /** 2519 * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in 2520 * the parent profile to access intents sent from the managed profile. 2521 * That is, when an app in the managed profile calls 2522 * {@link Activity#startActivity(Intent)}, the intent can be resolved by a 2523 * matching activity in the parent profile. 2524 */ 2525 public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001; 2526 2527 /** 2528 * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in 2529 * the managed profile to access intents sent from the parent profile. 2530 * That is, when an app in the parent profile calls 2531 * {@link Activity#startActivity(Intent)}, the intent can be resolved by a 2532 * matching activity in the managed profile. 2533 */ 2534 public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002; 2535 2536 /** 2537 * Broadcast action: notify that a new local system update policy has been set by the device 2538 * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}. 2539 */ 2540 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 2541 public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED 2542 = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED"; 2543 2544 /** 2545 * Broadcast action from ManagedProvisioning to notify that the latest change to 2546 * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully 2547 * applied (cross profile intent filters updated). Only usesd for CTS tests. 2548 * @hide 2549 */ 2550 @SuppressLint("ActionValue") 2551 @TestApi 2552 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 2553 public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED = 2554 "android.app.action.DATA_SHARING_RESTRICTION_APPLIED"; 2555 2556 /** 2557 * Broadcast action: notify that a value of {@link Settings.Global#DEVICE_POLICY_CONSTANTS} 2558 * has been changed. 2559 * @hide 2560 */ 2561 @SuppressLint("ActionValue") 2562 @TestApi 2563 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 2564 public static final String ACTION_DEVICE_POLICY_CONSTANTS_CHANGED = 2565 "android.app.action.DEVICE_POLICY_CONSTANTS_CHANGED"; 2566 2567 /** 2568 * Permission policy to prompt user for new permission requests for runtime permissions. 2569 * Already granted or denied permissions are not affected by this. 2570 */ 2571 public static final int PERMISSION_POLICY_PROMPT = 0; 2572 2573 /** 2574 * Permission policy to always grant new permission requests for runtime permissions. 2575 * Already granted or denied permissions are not affected by this. 2576 */ 2577 public static final int PERMISSION_POLICY_AUTO_GRANT = 1; 2578 2579 /** 2580 * Permission policy to always deny new permission requests for runtime permissions. 2581 * Already granted or denied permissions are not affected by this. 2582 */ 2583 public static final int PERMISSION_POLICY_AUTO_DENY = 2; 2584 2585 /** 2586 * Possible policy values for permissions. 2587 * 2588 * @hide 2589 */ 2590 @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = { 2591 PERMISSION_GRANT_STATE_DEFAULT, 2592 PERMISSION_GRANT_STATE_GRANTED, 2593 PERMISSION_GRANT_STATE_DENIED 2594 }) 2595 @Retention(RetentionPolicy.SOURCE) 2596 public @interface PermissionGrantState {} 2597 2598 /** 2599 * Runtime permission state: The user can manage the permission 2600 * through the UI. 2601 */ 2602 public static final int PERMISSION_GRANT_STATE_DEFAULT = 0; 2603 2604 /** 2605 * Runtime permission state: The permission is granted to the app 2606 * and the user cannot manage the permission through the UI. 2607 */ 2608 public static final int PERMISSION_GRANT_STATE_GRANTED = 1; 2609 2610 /** 2611 * Runtime permission state: The permission is denied to the app 2612 * and the user cannot manage the permission through the UI. 2613 */ 2614 public static final int PERMISSION_GRANT_STATE_DENIED = 2; 2615 2616 /** 2617 * Delegation of certificate installation and management. This scope grants access to the 2618 * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert}, 2619 * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs. 2620 * This scope also grants the ability to read identifiers that the delegating device owner or 2621 * profile owner can obtain. See {@link #getEnrollmentSpecificId()}. 2622 */ 2623 public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install"; 2624 2625 /** 2626 * Delegation of application restrictions management. This scope grants access to the 2627 * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs. 2628 */ 2629 public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions"; 2630 2631 /** 2632 * Delegation of application uninstall block. This scope grants access to the 2633 * {@link #setUninstallBlocked} API. 2634 */ 2635 public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall"; 2636 2637 /** 2638 * Delegation of permission policy and permission grant state. This scope grants access to the 2639 * {@link #setPermissionPolicy}, {@link #getPermissionGrantState}, 2640 * and {@link #setPermissionGrantState} APIs. 2641 */ 2642 public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant"; 2643 2644 /** 2645 * Delegation of package access state. This scope grants access to the 2646 * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and 2647 * {@link #setPackagesSuspended} APIs. 2648 */ 2649 public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access"; 2650 2651 /** 2652 * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp} 2653 * API. 2654 */ 2655 public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app"; 2656 2657 /** 2658 * Delegation for installing existing packages. This scope grants access to the 2659 * {@link #installExistingPackage} API. 2660 */ 2661 public static final String DELEGATION_INSTALL_EXISTING_PACKAGE = 2662 "delegation-install-existing-package"; 2663 2664 /** 2665 * Delegation of management of uninstalled packages. This scope grants access to the 2666 * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs. 2667 */ 2668 public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES = 2669 "delegation-keep-uninstalled-packages"; 2670 2671 /** 2672 * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and 2673 * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving 2674 * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner or Profile Owner 2675 * will no longer receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback. 2676 * There can be at most one app that has this delegation. 2677 * If another app already had delegated network logging access, 2678 * it will lose the delegation when a new app is delegated. 2679 * 2680 * <p> Device Owner can grant this access since Android 10. Profile Owner of a managed profile 2681 * can grant this access since Android 12. 2682 */ 2683 public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging"; 2684 2685 /** 2686 * Grants access to selection of KeyChain certificates on behalf of requesting apps. 2687 * Once granted the app will start receiving 2688 * {@link DelegatedAdminReceiver#onChoosePrivateKeyAlias}. The caller (PO/DO) will 2689 * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}. 2690 * There can be at most one app that has this delegation. 2691 * If another app already had delegated certificate selection access, 2692 * it will lose the delegation when a new app is delegated. 2693 * <p> The delegated app can also call {@link #grantKeyPairToApp} and 2694 * {@link #revokeKeyPairFromApp} to directly grant KeyChain keys to other apps. 2695 * <p> Can be granted by Device Owner or Profile Owner. 2696 */ 2697 public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection"; 2698 2699 /** 2700 * Grants access to {@link #setSecurityLoggingEnabled}, {@link #isSecurityLoggingEnabled}, 2701 * {@link #retrieveSecurityLogs}, and {@link #retrievePreRebootSecurityLogs}. Once granted the 2702 * delegated app will start receiving {@link DelegatedAdminReceiver#onSecurityLogsAvailable} 2703 * callback, and Device owner or Profile Owner will no longer receive the 2704 * {@link DeviceAdminReceiver#onSecurityLogsAvailable} callback. There can be at most one app 2705 * that has this delegation. If another app already had delegated security logging access, it 2706 * will lose the delegation when a new app is delegated. 2707 * 2708 * <p> Can only be granted by Device Owner or Profile Owner of an organization-owned 2709 * managed profile. 2710 */ 2711 public static final String DELEGATION_SECURITY_LOGGING = "delegation-security-logging"; 2712 2713 /** 2714 * No management for current user in-effect. This is the default. 2715 * @hide 2716 */ 2717 @SystemApi 2718 public static final int STATE_USER_UNMANAGED = 0; 2719 2720 /** 2721 * Management partially setup, user setup needs to be completed. 2722 * @hide 2723 */ 2724 @SystemApi 2725 public static final int STATE_USER_SETUP_INCOMPLETE = 1; 2726 2727 /** 2728 * Management partially setup, user setup completed. 2729 * @hide 2730 */ 2731 @SystemApi 2732 public static final int STATE_USER_SETUP_COMPLETE = 2; 2733 2734 /** 2735 * Management setup and active on current user. 2736 * @hide 2737 */ 2738 @SystemApi 2739 public static final int STATE_USER_SETUP_FINALIZED = 3; 2740 2741 /** 2742 * Management partially setup on a managed profile. 2743 * @hide 2744 */ 2745 @SystemApi 2746 public static final int STATE_USER_PROFILE_COMPLETE = 4; 2747 2748 /** 2749 * Management setup on a managed profile. 2750 * <p>This is used as an intermediate state after {@link #STATE_USER_PROFILE_COMPLETE} once the 2751 * work profile has been created. 2752 * @hide 2753 */ 2754 @SystemApi 2755 public static final int STATE_USER_PROFILE_FINALIZED = 5; 2756 2757 /** 2758 * @hide 2759 */ 2760 @IntDef(prefix = { "STATE_USER_" }, value = { 2761 STATE_USER_UNMANAGED, 2762 STATE_USER_SETUP_INCOMPLETE, 2763 STATE_USER_SETUP_COMPLETE, 2764 STATE_USER_SETUP_FINALIZED, 2765 STATE_USER_PROFILE_COMPLETE, 2766 STATE_USER_PROFILE_FINALIZED 2767 }) 2768 @Retention(RetentionPolicy.SOURCE) 2769 public @interface UserProvisioningState {} 2770 2771 /** 2772 * Result code for {@link #checkProvisioningPrecondition}. 2773 * 2774 * <p>Unknown error code returned for {@link #ACTION_PROVISION_MANAGED_DEVICE}, 2775 * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}. 2776 * 2777 * @hide 2778 */ 2779 @SystemApi 2780 public static final int STATUS_UNKNOWN_ERROR = -1; 2781 2782 /** 2783 * Result code for {@link #checkProvisioningPrecondition}. 2784 * 2785 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE}, 2786 * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER} 2787 * when provisioning is allowed. 2788 * 2789 * @hide 2790 */ 2791 @SystemApi 2792 public static final int STATUS_OK = 0; 2793 2794 /** 2795 * Result code for {@link #checkProvisioningPrecondition}. 2796 * 2797 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the device already has a 2798 * device owner. 2799 * 2800 * @hide 2801 */ 2802 @SystemApi 2803 public static final int STATUS_HAS_DEVICE_OWNER = 1; 2804 2805 /** 2806 * Result code for {@link #checkProvisioningPrecondition}. 2807 * 2808 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user has a profile owner 2809 * and for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set. 2810 * 2811 * @hide 2812 */ 2813 @SystemApi 2814 public static final int STATUS_USER_HAS_PROFILE_OWNER = 2; 2815 2816 /** 2817 * Result code for {@link #checkProvisioningPrecondition}. 2818 * 2819 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user isn't running. 2820 * 2821 * @hide 2822 */ 2823 @SystemApi 2824 public static final int STATUS_USER_NOT_RUNNING = 3; 2825 2826 /** 2827 * Result code for {@link #checkProvisioningPrecondition}. 2828 * 2829 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the device has already been 2830 * setup and for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup. 2831 * 2832 * @hide 2833 */ 2834 @SystemApi 2835 public static final int STATUS_USER_SETUP_COMPLETED = 4; 2836 2837 /** 2838 * Code used to indicate that the device also has a user other than the system user. 2839 * 2840 * @hide 2841 */ 2842 @SystemApi 2843 public static final int STATUS_NONSYSTEM_USER_EXISTS = 5; 2844 2845 /** 2846 * Code used to indicate that device has an account that prevents provisioning. 2847 * 2848 * @hide 2849 */ 2850 @SystemApi 2851 public static final int STATUS_ACCOUNTS_NOT_EMPTY = 6; 2852 2853 /** 2854 * Result code for {@link #checkProvisioningPrecondition}. 2855 * 2856 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the user is not a system user. 2857 * 2858 * @hide 2859 */ 2860 @SystemApi 2861 public static final int STATUS_NOT_SYSTEM_USER = 7; 2862 2863 /** 2864 * Result code for {@link #checkProvisioningPrecondition}. 2865 * 2866 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and 2867 * {@link #ACTION_PROVISION_MANAGED_USER} when the device is a watch and is already paired. 2868 * 2869 * @hide 2870 */ 2871 @SystemApi 2872 public static final int STATUS_HAS_PAIRED = 8; 2873 2874 /** 2875 * Result code for {@link #checkProvisioningPrecondition}. 2876 * 2877 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and 2878 * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users. 2879 * 2880 * @see {@link PackageManager#FEATURE_MANAGED_USERS} 2881 * @hide 2882 */ 2883 @SystemApi 2884 public static final int STATUS_MANAGED_USERS_NOT_SUPPORTED = 9; 2885 2886 /** 2887 * Result code for {@link #checkProvisioningPrecondition}. 2888 * 2889 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user and 2890 * for {@link #ACTION_PROVISION_MANAGED_DEVICE} on devices running headless system user mode 2891 * and the user is a system user. 2892 * 2893 * @hide 2894 */ 2895 @SystemApi 2896 public static final int STATUS_SYSTEM_USER = 10; 2897 2898 /** 2899 * Result code for {@link #checkProvisioningPrecondition}. 2900 * 2901 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more 2902 * managed profiles. 2903 * 2904 * @hide 2905 */ 2906 @SystemApi 2907 public static final int STATUS_CANNOT_ADD_MANAGED_PROFILE = 11; 2908 2909 /** 2910 * Result code for {@link #checkProvisioningPrecondition}. 2911 * 2912 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE}, 2913 * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support device 2914 * admins. 2915 * 2916 * @hide 2917 */ 2918 @SystemApi 2919 public static final int STATUS_DEVICE_ADMIN_NOT_SUPPORTED = 13; 2920 2921 /** 2922 * TODO (b/137101239): clean up split system user codes 2923 * Result code for {@link #checkProvisioningPrecondition}. 2924 * 2925 * @hide 2926 * @deprecated not used anymore but can't be removed since it's a @TestApi. 2927 */ 2928 @Deprecated 2929 @TestApi 2930 public static final int STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14; 2931 2932 /** 2933 * Result code for {@link #checkProvisioningPrecondition}. 2934 * 2935 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and 2936 * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support provisioning. 2937 * 2938 * @hide 2939 */ 2940 @SystemApi 2941 public static final int STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS = 15; 2942 2943 /** 2944 * Result code for {@link #checkProvisioningPrecondition}. 2945 * 2946 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when provisioning a DPC which does 2947 * not support headless system user mode on a headless system user mode device. 2948 * 2949 * @hide 2950 */ 2951 @SystemApi 2952 public static final int STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED = 16; 2953 2954 /** 2955 * Result code for {@link #checkProvisioningPrecondition}. 2956 * 2957 * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when provisioning a DPC into the 2958 * {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER} mode but only the system 2959 * user exists on the device. 2960 * 2961 * @hide 2962 */ 2963 @SystemApi 2964 public static final int STATUS_HEADLESS_ONLY_SYSTEM_USER = 17; 2965 2966 /** 2967 * Result codes for {@link #checkProvisioningPrecondition} indicating all the provisioning pre 2968 * conditions. 2969 * 2970 * @hide 2971 */ 2972 @Retention(RetentionPolicy.SOURCE) 2973 @IntDef(prefix = { "STATUS_" }, value = { 2974 STATUS_UNKNOWN_ERROR, STATUS_OK, STATUS_HAS_DEVICE_OWNER, STATUS_USER_HAS_PROFILE_OWNER, 2975 STATUS_USER_NOT_RUNNING, STATUS_USER_SETUP_COMPLETED, STATUS_NOT_SYSTEM_USER, 2976 STATUS_HAS_PAIRED, STATUS_MANAGED_USERS_NOT_SUPPORTED, STATUS_SYSTEM_USER, 2977 STATUS_CANNOT_ADD_MANAGED_PROFILE, STATUS_DEVICE_ADMIN_NOT_SUPPORTED, 2978 STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER, 2979 STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS, 2980 STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED, STATUS_HEADLESS_ONLY_SYSTEM_USER 2981 }) 2982 public @interface ProvisioningPrecondition {} 2983 2984 /** 2985 * Disable all configurable SystemUI features during LockTask mode. This includes, 2986 * <ul> 2987 * <li>system info area in the status bar (connectivity icons, clock, etc.) 2988 * <li>notifications (including alerts, icons, and the notification shade) 2989 * <li>Home button 2990 * <li>Recents button and UI 2991 * <li>global actions menu (i.e. power button menu) 2992 * <li>keyguard 2993 * </ul> 2994 * 2995 * @see #setLockTaskFeatures(ComponentName, int) 2996 */ 2997 public static final int LOCK_TASK_FEATURE_NONE = 0; 2998 2999 /** 3000 * Enable the system info area in the status bar during LockTask mode. The system info area 3001 * usually occupies the right side of the status bar (although this can differ across OEMs). It 3002 * includes all system information indicators, such as date and time, connectivity, battery, 3003 * vibration mode, etc. 3004 * 3005 * @see #setLockTaskFeatures(ComponentName, int) 3006 */ 3007 public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1; 3008 3009 /** 3010 * Enable notifications during LockTask mode. This includes notification icons on the status 3011 * bar, heads-up notifications, and the expandable notification shade. Note that the Quick 3012 * Settings panel remains disabled. This feature flag can only be used in combination with 3013 * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)} 3014 * throws an {@link IllegalArgumentException} if this feature flag is defined without 3015 * {@link #LOCK_TASK_FEATURE_HOME}. 3016 * 3017 * @see #setLockTaskFeatures(ComponentName, int) 3018 */ 3019 public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1; 3020 3021 /** 3022 * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has 3023 * to be registered as the default launcher with 3024 * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its 3025 * package needs to be allowlisted for LockTask with 3026 * {@link #setLockTaskPackages(ComponentName, String[])}. 3027 * 3028 * @see #setLockTaskFeatures(ComponentName, int) 3029 */ 3030 public static final int LOCK_TASK_FEATURE_HOME = 1 << 2; 3031 3032 /** 3033 * Enable the Overview button and the Overview screen during LockTask mode. This feature flag 3034 * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and 3035 * {@link #setLockTaskFeatures(ComponentName, int)} will throw an 3036 * {@link IllegalArgumentException} if this feature flag is defined without 3037 * {@link #LOCK_TASK_FEATURE_HOME}. 3038 * 3039 * @see #setLockTaskFeatures(ComponentName, int) 3040 */ 3041 public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3; 3042 3043 /** 3044 * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when 3045 * the user long-presses the power button, for example. Note that the user may not be able to 3046 * power off the device if this flag is not set. 3047 * 3048 * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is 3049 * called for the first time. 3050 * 3051 * @see #setLockTaskFeatures(ComponentName, int) 3052 */ 3053 public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4; 3054 3055 /** 3056 * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with 3057 * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect. 3058 * If this flag is not set, the keyguard will not be shown even if the user has a lock screen 3059 * credential. 3060 * 3061 * @see #setLockTaskFeatures(ComponentName, int) 3062 */ 3063 public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5; 3064 3065 /** 3066 * Enable blocking of non-allowlisted activities from being started into a locked task. 3067 * 3068 * @see #setLockTaskFeatures(ComponentName, int) 3069 */ 3070 public static final int LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK = 1 << 6; 3071 3072 /** 3073 * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}. 3074 * 3075 * @hide 3076 */ 3077 @Retention(RetentionPolicy.SOURCE) 3078 @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = { 3079 LOCK_TASK_FEATURE_NONE, 3080 LOCK_TASK_FEATURE_SYSTEM_INFO, 3081 LOCK_TASK_FEATURE_NOTIFICATIONS, 3082 LOCK_TASK_FEATURE_HOME, 3083 LOCK_TASK_FEATURE_OVERVIEW, 3084 LOCK_TASK_FEATURE_GLOBAL_ACTIONS, 3085 LOCK_TASK_FEATURE_KEYGUARD, 3086 LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK 3087 }) 3088 public @interface LockTaskFeature {} 3089 3090 /** 3091 * Service action: Action for a service that device owner and profile owner can optionally 3092 * own. If a device owner or a profile owner has such a service, the system tries to keep 3093 * a bound connection to it, in order to keep their process always running. 3094 * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN} 3095 * permission. 3096 */ 3097 @SdkConstant(SdkConstantType.SERVICE_ACTION) 3098 public static final String ACTION_DEVICE_ADMIN_SERVICE 3099 = "android.app.action.DEVICE_ADMIN_SERVICE"; 3100 3101 /** @hide */ 3102 @Retention(RetentionPolicy.SOURCE) 3103 @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = { 3104 ID_TYPE_BASE_INFO, 3105 ID_TYPE_SERIAL, 3106 ID_TYPE_IMEI, 3107 ID_TYPE_MEID, 3108 ID_TYPE_INDIVIDUAL_ATTESTATION 3109 }) 3110 public @interface AttestationIdType {} 3111 3112 /** 3113 * Specifies that the device should attest its manufacturer details. For use with 3114 * {@link #generateKeyPair}. 3115 * 3116 * @see #generateKeyPair 3117 */ 3118 public static final int ID_TYPE_BASE_INFO = 1; 3119 3120 /** 3121 * Specifies that the device should attest its serial number. For use with 3122 * {@link #generateKeyPair}. 3123 * 3124 * @see #generateKeyPair 3125 */ 3126 public static final int ID_TYPE_SERIAL = 2; 3127 3128 /** 3129 * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}. 3130 * 3131 * @see #generateKeyPair 3132 */ 3133 public static final int ID_TYPE_IMEI = 4; 3134 3135 /** 3136 * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}. 3137 * 3138 * @see #generateKeyPair 3139 */ 3140 public static final int ID_TYPE_MEID = 8; 3141 3142 /** 3143 * Specifies that the device should attest using an individual attestation certificate. 3144 * For use with {@link #generateKeyPair}. 3145 * 3146 * @see #generateKeyPair 3147 */ 3148 public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16; 3149 3150 /** 3151 * Service-specific error code for {@link #generateKeyPair}: 3152 * Indicates the call has failed due to StrongBox unavailability. 3153 * @hide 3154 */ 3155 public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1; 3156 3157 /** 3158 * Specifies that the calling app should be granted access to the installed credentials 3159 * immediately. Otherwise, access to the credentials will be gated by user approval. 3160 * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} 3161 * 3162 * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int) 3163 */ 3164 public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1; 3165 3166 /** 3167 * Specifies that a user can select the key via the Certificate Selection prompt. 3168 * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted 3169 * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}. 3170 * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} 3171 * 3172 * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int) 3173 */ 3174 public static final int INSTALLKEY_SET_USER_SELECTABLE = 2; 3175 3176 /** 3177 * Broadcast action: sent when the profile owner is set, changed or cleared. 3178 * 3179 * This broadcast is sent only to the user managed by the new profile owner. 3180 * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle) 3181 */ 3182 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 3183 public static final String ACTION_PROFILE_OWNER_CHANGED = 3184 "android.app.action.PROFILE_OWNER_CHANGED"; 3185 3186 /** @hide */ 3187 @Retention(RetentionPolicy.SOURCE) 3188 @IntDef(prefix = {"PRIVATE_DNS_MODE_"}, value = { 3189 PRIVATE_DNS_MODE_UNKNOWN, 3190 PRIVATE_DNS_MODE_OFF, 3191 PRIVATE_DNS_MODE_OPPORTUNISTIC, 3192 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME 3193 }) 3194 public @interface PrivateDnsMode {} 3195 3196 /** 3197 * Specifies that the Private DNS setting is in an unknown state. 3198 */ 3199 public static final int PRIVATE_DNS_MODE_UNKNOWN = 0; 3200 3201 /** 3202 * Specifies that Private DNS was turned off completely. 3203 */ 3204 public static final int PRIVATE_DNS_MODE_OFF = 1; 3205 3206 /** 3207 * Specifies that the device owner requested opportunistic DNS over TLS 3208 */ 3209 public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2; 3210 3211 /** 3212 * Specifies that the device owner configured a specific host to use for Private DNS. 3213 */ 3214 public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3; 3215 3216 /** 3217 * Callback used in {@link #installSystemUpdate} to indicate that there was an error while 3218 * trying to install an update. 3219 */ 3220 public abstract static class InstallSystemUpdateCallback { 3221 /** Represents an unknown error while trying to install an update. */ 3222 public static final int UPDATE_ERROR_UNKNOWN = 1; 3223 3224 /** Represents the update file being intended for different OS version. */ 3225 public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2; 3226 3227 /** 3228 * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong 3229 * compression method is used. 3230 */ 3231 public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3; 3232 3233 /** Represents that the file could not be found. */ 3234 public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4; 3235 3236 /** Represents the battery being too low to apply an update. */ 3237 public static final int UPDATE_ERROR_BATTERY_LOW = 5; 3238 3239 /** 3240 * Method invoked when there was an error while installing an update. 3241 * 3242 * <p>The given error message is not intended to be user-facing. It is intended to be 3243 * reported back to the IT admin to be read. 3244 */ onInstallUpdateError( @nstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage)3245 public void onInstallUpdateError( 3246 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) { 3247 } 3248 } 3249 3250 /** 3251 * @hide 3252 */ 3253 @IntDef(prefix = { "UPDATE_ERROR_" }, value = { 3254 InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, 3255 InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION, 3256 InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID, 3257 InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND, 3258 InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW 3259 }) 3260 @Retention(RetentionPolicy.SOURCE) 3261 public @interface InstallUpdateCallbackErrorConstants {} 3262 3263 /** 3264 * The selected mode has been set successfully. If the mode is 3265 * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid 3266 * and reachable. 3267 */ 3268 public static final int PRIVATE_DNS_SET_NO_ERROR = 0; 3269 3270 /** 3271 * If the {@code privateDnsHost} provided was of a valid hostname but that host was found 3272 * to not support DNS-over-TLS. 3273 */ 3274 public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1; 3275 3276 /** 3277 * General failure to set the Private DNS mode, not due to one of the reasons listed above. 3278 */ 3279 public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2; 3280 3281 /** 3282 * @hide 3283 */ 3284 @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = { 3285 PRIVATE_DNS_SET_NO_ERROR, 3286 PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING, 3287 PRIVATE_DNS_SET_ERROR_FAILURE_SETTING 3288 }) 3289 @Retention(RetentionPolicy.SOURCE) 3290 public @interface PrivateDnsModeErrorCodes {} 3291 3292 /** 3293 * Activity action: Starts the administrator to get the mode for the provisioning. 3294 * This intent may contain the following extras: 3295 * <ul> 3296 * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li> 3297 * <li>{@link #EXTRA_PROVISIONING_IMEI}</li> 3298 * <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li> 3299 * <li>{@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}</li> 3300 * <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT}</li> 3301 * </ul> 3302 * 3303 * <p>The target activity should return one of the following values in 3304 * {@link #EXTRA_PROVISIONING_MODE} as result: 3305 * <ul> 3306 * <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li> 3307 * <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li> 3308 * </ul> 3309 * 3310 * <p>If performing fully-managed device provisioning and the admin app desires to show its 3311 * own education screens, the target activity can additionally return 3312 * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>. 3313 * 3314 * <p>The target activity may also return the account that needs to be migrated from primary 3315 * user to managed profile in case of a profile owner provisioning in 3316 * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result. 3317 * 3318 * <p>The target activity may also include the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} 3319 * extra in the intent result. The values of this {@link android.os.PersistableBundle} will be 3320 * sent as an intent extra of the same name to the {@link #ACTION_ADMIN_POLICY_COMPLIANCE} 3321 * activity, along with the values of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra 3322 * that are already supplied to this activity. 3323 * 3324 * <p>Other extras the target activity may include in the intent result: 3325 * <ul> 3326 * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li> 3327 * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}</li> 3328 * <li>{@link #EXTRA_PROVISIONING_KEEP_SCREEN_ON}</li> 3329 * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION} for work profile 3330 * provisioning</li> 3331 * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED} for work profile 3332 * provisioning</li> 3333 * <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} for fully-managed 3334 * device provisioning</li> 3335 * <li>{@link #EXTRA_PROVISIONING_LOCALE} for fully-managed device provisioning</li> 3336 * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} for fully-managed device provisioning</li> 3337 * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE} for fully-managed device provisioning</li> 3338 * </ul> 3339 * 3340 * @see #ACTION_ADMIN_POLICY_COMPLIANCE 3341 */ 3342 public static final String ACTION_GET_PROVISIONING_MODE = 3343 "android.app.action.GET_PROVISIONING_MODE"; 3344 3345 /** 3346 * A string extra holding the IMEI (International Mobile Equipment Identity) of the device. 3347 */ 3348 public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI"; 3349 3350 /** 3351 * A string extra holding the serial number of the device. 3352 */ 3353 public static final String EXTRA_PROVISIONING_SERIAL_NUMBER = 3354 "android.app.extra.PROVISIONING_SERIAL_NUMBER"; 3355 3356 /** 3357 * An intent extra holding the provisioning mode returned by the administrator. 3358 * The value of this extra must be one of the values provided in {@link 3359 * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}, which is provided as an intent extra to 3360 * the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity. 3361 * 3362 * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE 3363 * @see #PROVISIONING_MODE_MANAGED_PROFILE 3364 */ 3365 public static final String EXTRA_PROVISIONING_MODE = 3366 "android.app.extra.PROVISIONING_MODE"; 3367 3368 /** 3369 * An integer extra indication what provisioning modes should be available for the admin app 3370 * to pick. 3371 * 3372 * <p>The default value is {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}. 3373 * 3374 * <p>The value of this extra will determine the contents of the {@link 3375 * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array that is passed to the admin app as an 3376 * extra to its {@link #ACTION_GET_PROVISIONING_MODE} activity. 3377 * 3378 * <p>If one of the possible admin app choices is a personally-owned work profile, then the 3379 * IMEI and serial number will not be passed to the admin app's {@link 3380 * #ACTION_GET_PROVISIONING_MODE} activity via the {@link #EXTRA_PROVISIONING_IMEI} and {@link 3381 * #EXTRA_PROVISIONING_SERIAL_NUMBER} respectively. 3382 * 3383 * <p>The allowed flag combinations are: 3384 * <ul> 3385 * <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}</li> 3386 * <li>{@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li> 3387 * <li>{@link #FLAG_SUPPORTED_MODES_DEVICE_OWNER}</li> 3388 * <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED} 3389 * | {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li> 3390 * </ul> 3391 * 3392 * <p>This extra is only respected when provided alongside the {@link 3393 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action. 3394 * 3395 * @see #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED 3396 * @see #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED 3397 * @see #FLAG_SUPPORTED_MODES_DEVICE_OWNER 3398 * @hide 3399 */ 3400 @SystemApi 3401 public static final String EXTRA_PROVISIONING_SUPPORTED_MODES = 3402 "android.app.extra.PROVISIONING_SUPPORTED_MODES"; 3403 3404 /** 3405 * A boolean extra which determines whether to skip the ownership disclaimer screen during the 3406 * provisioning flow. The default value is {@code false}. 3407 * 3408 * If the value is {@code true}, the provisioning initiator must display a device ownership 3409 * disclaimer screen similar to that provided in AOSP. 3410 * 3411 * <p>This extra is only respected when provided alongside the {@link 3412 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action. 3413 * 3414 * @hide 3415 */ 3416 @SystemApi 3417 public static final String EXTRA_PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER = 3418 "android.app.extra.PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER"; 3419 3420 /** 3421 * An {@link ArrayList} of {@link Integer} extra specifying the allowed provisioning modes. 3422 * <p>This extra will be passed to the admin app's {@link #ACTION_GET_PROVISIONING_MODE} 3423 * activity, whose result intent must contain {@link #EXTRA_PROVISIONING_MODE} set to one of 3424 * the values in this array. 3425 * <p>If the value set to {@link #EXTRA_PROVISIONING_MODE} is not in the array, 3426 * provisioning will fail. 3427 * @see #PROVISIONING_MODE_MANAGED_PROFILE 3428 * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE 3429 */ 3430 public static final String EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES = 3431 "android.app.extra.PROVISIONING_ALLOWED_PROVISIONING_MODES"; 3432 3433 /** 3434 * The provisioning mode for fully managed device. 3435 */ 3436 public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1; 3437 3438 /** 3439 * The provisioning mode for managed profile. 3440 */ 3441 public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2; 3442 3443 /** 3444 * The provisioning mode for a managed profile on a personal device. 3445 * <p>This mode is only available when the provisioning initiator has explicitly instructed the 3446 * provisioning flow to support managed profile on a personal device provisioning. In that case, 3447 * {@link #PROVISIONING_MODE_MANAGED_PROFILE} corresponds to an organization-owned managed 3448 * profile, whereas this constant corresponds to a personally-owned managed profile. 3449 * 3450 * @see #EXTRA_PROVISIONING_MODE 3451 */ 3452 public static final int PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE = 3; 3453 3454 /** 3455 * A {@code boolean} flag that indicates whether the provisioning flow should return before 3456 * starting the admin app's {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. The default value 3457 * is {@code true}. 3458 * 3459 * <p>If this extra is set to {@code true}, then when the provisioning flow returns back to the 3460 * provisioning initiator, provisioning will not be complete. The provisioning initiator can 3461 * use this opportunity to do its own preparatory steps prior to the launch of the admin app's 3462 * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. It is the responsibility of the 3463 * provisioning initiator to ensure that the provisioning flow is then resumed and completed. 3464 * 3465 * <p>If this extra is set to {@code false}, then when the provisioning flow returns back to 3466 * the provisioning initiator, provisioning will be complete. Note that device owner 3467 * provisioning is not currently supported for the this scenario. 3468 * 3469 * <p>This extra is only respected when provided alongside the {@link 3470 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action. 3471 * 3472 * @hide 3473 */ 3474 @SystemApi 3475 public static final String EXTRA_PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE = 3476 "android.app.extra.PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE"; 3477 3478 /** 3479 * A {@code boolean} flag that indicates whether the screen should be on throughout the 3480 * provisioning flow. 3481 * 3482 * <p>This extra can either be passed as an extra to the {@link 3483 * #ACTION_PROVISION_MANAGED_PROFILE} intent, or it can be returned by the 3484 * admin app when performing the admin-integrated provisioning flow as a result of the 3485 * {@link #ACTION_GET_PROVISIONING_MODE} activity. 3486 * 3487 * @deprecated from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the flag wouldn't 3488 * be functional. The screen is kept on throughout the provisioning flow. 3489 */ 3490 3491 @Deprecated 3492 public static final String EXTRA_PROVISIONING_KEEP_SCREEN_ON = 3493 "android.app.extra.PROVISIONING_KEEP_SCREEN_ON"; 3494 3495 /** 3496 * Activity action: Starts the administrator to show policy compliance for the provisioning. 3497 * This action is used any time that the administrator has an opportunity to show policy 3498 * compliance before the end of setup wizard. This could happen as part of the admin-integrated 3499 * provisioning flow (in which case this gets sent after {@link #ACTION_GET_PROVISIONING_MODE}), 3500 * or it could happen during provisioning finalization if the administrator supports 3501 * finalization during setup wizard. 3502 * 3503 * <p>Intents with this action may also be supplied with the {@link 3504 * #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra. 3505 * 3506 * @see #ACTION_GET_PROVISIONING_MODE 3507 */ 3508 public static final String ACTION_ADMIN_POLICY_COMPLIANCE = 3509 "android.app.action.ADMIN_POLICY_COMPLIANCE"; 3510 3511 /** 3512 * Activity action: Starts the device policy management role holder updater. 3513 * 3514 * <p>The activity must handle the device policy management role holder update and set the 3515 * intent result. This can include {@link Activity#RESULT_OK} if the update was successful, 3516 * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if 3517 * it encounters a problem that may be solved by relaunching it again, {@link 3518 * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED} if role holder 3519 * provisioning is disabled, or {@link 3520 * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if it encounters 3521 * any other problem that will not be solved by relaunching it again. 3522 * 3523 * <p>If this activity has additional internal conditions which are not met, it should return 3524 * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR}. 3525 * 3526 * @hide 3527 */ 3528 @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP) 3529 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 3530 @SystemApi 3531 public static final String ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER = 3532 "android.app.action.UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER"; 3533 3534 /** 3535 * Result code that can be returned by the {@link 3536 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem 3537 * that may be solved by relaunching it again. 3538 * 3539 * @hide 3540 */ 3541 @SystemApi 3542 public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR = 3543 1; 3544 3545 /** 3546 * Result code that can be returned by the {@link 3547 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem that 3548 * will not be solved by relaunching it again. 3549 * 3550 * @hide 3551 */ 3552 @SystemApi 3553 public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR = 3554 2; 3555 3556 /** 3557 * Result code that can be returned by the {@link 3558 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if role holder provisioning 3559 * is disabled. 3560 * 3561 * @hide 3562 */ 3563 @SystemApi 3564 public static final int 3565 RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED = 3; 3566 3567 /** 3568 * An {@code int} extra that specifies one of {@link 3569 * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING} or {@link 3570 * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING}. 3571 * 3572 * <p>The failure strategy specifies how the platform should handle a failed device policy 3573 * management role holder update via {@link 3574 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} when {@link 3575 * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is not set or set to {@code false}. 3576 * 3577 * <p>This extra may be supplied as part of the {@link 3578 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} result intent. 3579 * 3580 * <p>Default value is {@link #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING}. 3581 * 3582 * @hide 3583 */ 3584 public static final String EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY = 3585 "android.app.extra.ROLE_HOLDER_UPDATE_FAILURE_STRATEGY"; 3586 3587 /** 3588 * Possible values for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY}. 3589 * 3590 * @hide 3591 */ 3592 @IntDef(prefix = { "ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_" }, value = { 3593 ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING, 3594 ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING 3595 }) 3596 @Retention(RetentionPolicy.SOURCE) 3597 public @interface RoleHolderUpdateFailureStrategy {} 3598 3599 /** 3600 * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon 3601 * failure to update the role holder, provisioning should fail. 3602 * 3603 * @hide 3604 */ 3605 public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING = 1; 3606 3607 /** 3608 * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon 3609 * failure to update the role holder, provisioning should fallback to be platform-driven. 3610 * 3611 * @hide 3612 */ 3613 public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING = 3614 2; 3615 3616 /** 3617 * An {@code int} extra which contains the result code of the last attempt to update 3618 * the device policy management role holder via {@link 3619 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}. 3620 * 3621 * <p>This extra is provided to the device policy management role holder via either {@link 3622 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link 3623 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} when started after the role holder 3624 * had previously returned {@link #RESULT_UPDATE_ROLE_HOLDER}. 3625 * 3626 * <p>If the role holder update had failed, the role holder can use the value of this extra to 3627 * make a decision whether to fail the provisioning flow or to carry on with the older version 3628 * of the role holder. 3629 * 3630 * <p>Possible values can be: 3631 * <ul> 3632 * <li>{@link Activity#RESULT_OK} if the update was successful 3633 * <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if it 3634 * encounters a problem that may be solved by relaunching it again. 3635 * <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if 3636 * it encounters a problem that will not be solved by relaunching it again. 3637 * <li>Any other value returned by {@link 3638 * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} 3639 * </ul> 3640 * 3641 * @hide 3642 */ 3643 @SystemApi 3644 public static final String EXTRA_ROLE_HOLDER_UPDATE_RESULT_CODE = 3645 "android.app.extra.ROLE_HOLDER_UPDATE_RESULT_CODE"; 3646 3647 /** 3648 * An {@link Intent} extra which resolves to a custom user consent screen. 3649 * 3650 * <p>If this extra is provided to the device policy management role holder via either {@link 3651 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link 3652 * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE}, the device policy management role holder must 3653 * launch this intent which shows the custom user consent screen, replacing its own standard 3654 * consent screen. 3655 * 3656 * <p>If this extra is provided, it is the responsibility of the intent handler to show the 3657 * list of disclaimers which are normally shown by the standard consent screen: 3658 * <ul> 3659 * <li>Disclaimers set by the IT admin via the {@link #EXTRA_PROVISIONING_DISCLAIMERS} 3660 * provisioning extra</li> 3661 * <li>For fully-managed device provisioning, disclaimers defined in system apps via the 3662 * {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER} and {@link 3663 * #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} metadata in their manifests</li> 3664 * <li>General disclaimer relevant to the provisioning mode</li> 3665 * </ul> 3666 * 3667 * <p>When this {@link Intent} is started, the following intent extras will be supplied: 3668 * <ul> 3669 * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li> 3670 * <li>{@link #EXTRA_PROVISIONING_MODE}</li> 3671 * <li>{@link #EXTRA_PROVISIONING_LOCALE}</li> 3672 * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME}</li> 3673 * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}</li> 3674 * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}</li> 3675 * </ul> 3676 * 3677 * <p>If the custom consent screens are granted by the user {@link Activity#RESULT_OK} is 3678 * returned, otherwise {@link Activity#RESULT_CANCELED} is returned. The device policy 3679 * management role holder should ensure that the provisioning flow terminates immediately if 3680 * consent is not granted by the user. 3681 * 3682 * @hide 3683 */ 3684 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 3685 @SystemApi 3686 public static final String EXTRA_PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT = 3687 "android.app.extra.PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT"; 3688 3689 /** 3690 * Activity action: attempts to establish network connection 3691 * 3692 * <p>This intent can be accompanied by any of the relevant provisioning extras related to 3693 * network connectivity, such as: 3694 * <ul> 3695 * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}</li> 3696 * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN}</li> 3697 * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}</li> 3698 * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}</li> 3699 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}</li> 3700 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT}</li> 3701 * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}</li> 3702 * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}</li> 3703 * <li>{@code #EXTRA_PROVISIONING_WIFI_EAP_METHOD}</li> 3704 * <li>{@code #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}</li> 3705 * <li>{@code #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}</li> 3706 * <li>{@code #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}</li> 3707 * <li>{@code #EXTRA_PROVISIONING_WIFI_IDENTITY}</li> 3708 * <li>{@code #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}</li> 3709 * <li>{@code #EXTRA_PROVISIONING_WIFI_DOMAIN}</li> 3710 * </ul> 3711 * 3712 * <p>If there are provisioning extras related to network connectivity, this activity 3713 * attempts to connect to the specified network. Otherwise it prompts the end-user to connect. 3714 * 3715 * <p>This activity is meant to be started by the provisioning initiator prior to starting 3716 * {@link #ACTION_PROVISION_MANAGED_PROFILE} or {@link 3717 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}. 3718 * 3719 * <p>Note that network connectivity is still also handled when provisioning via {@link 3720 * #ACTION_PROVISION_MANAGED_PROFILE} or {@link 3721 * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}. {@link 3722 * #ACTION_ESTABLISH_NETWORK_CONNECTION} should only be used in cases when the provisioning 3723 * initiator would like to do some additional logic after the network connectivity step and 3724 * before the start of provisioning. 3725 * 3726 * If network connection is established, {@link Activity#RESULT_OK} will be returned. Otherwise 3727 * the result will be {@link Activity#RESULT_CANCELED}. 3728 * 3729 * @hide 3730 */ 3731 @RequiresPermission(android.Manifest.permission.DISPATCH_PROVISIONING_MESSAGE) 3732 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 3733 @SystemApi 3734 public static final String ACTION_ESTABLISH_NETWORK_CONNECTION = 3735 "android.app.action.ESTABLISH_NETWORK_CONNECTION"; 3736 3737 /** 3738 * Maximum supported password length. Kind-of arbitrary. 3739 * @hide 3740 */ 3741 public static final int MAX_PASSWORD_LENGTH = 16; 3742 3743 /** 3744 * Service Action: Service implemented by a device owner or profile owner supervision app to 3745 * provide a secondary lockscreen. 3746 * @hide 3747 */ 3748 @SystemApi 3749 public static final String ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE = 3750 "android.app.action.BIND_SECONDARY_LOCKSCREEN_SERVICE"; 3751 3752 /** 3753 * Return value for {@link #getPersonalAppsSuspendedReasons} when personal apps are not 3754 * suspended. 3755 */ 3756 public static final int PERSONAL_APPS_NOT_SUSPENDED = 0; 3757 3758 /** 3759 * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal 3760 * apps are suspended by an admin explicitly via {@link #setPersonalAppsSuspended}. 3761 */ 3762 public static final int PERSONAL_APPS_SUSPENDED_EXPLICITLY = 1 << 0; 3763 3764 /** 3765 * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal apps are 3766 * suspended by framework because managed profile was off for longer than allowed by policy. 3767 * @see #setManagedProfileMaximumTimeOff 3768 */ 3769 public static final int PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT = 1 << 1; 3770 3771 /** 3772 * @hide 3773 */ 3774 @IntDef(flag = true, prefix = { "PERSONAL_APPS_" }, value = { 3775 PERSONAL_APPS_NOT_SUSPENDED, 3776 PERSONAL_APPS_SUSPENDED_EXPLICITLY, 3777 PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT 3778 }) 3779 @Retention(RetentionPolicy.SOURCE) 3780 public @interface PersonalAppsSuspensionReason {} 3781 3782 /** 3783 * The default device owner type for a managed device. 3784 * 3785 * @hide 3786 */ 3787 @TestApi 3788 public static final int DEVICE_OWNER_TYPE_DEFAULT = 0; 3789 3790 /** 3791 * The device owner type for a financed device. 3792 * 3793 * @hide 3794 */ 3795 @TestApi 3796 public static final int DEVICE_OWNER_TYPE_FINANCED = 1; 3797 3798 /** 3799 * Different device owner types for a managed device. 3800 * 3801 * @hide 3802 */ 3803 @Retention(RetentionPolicy.SOURCE) 3804 @IntDef(prefix = { "DEVICE_OWNER_TYPE_" }, value = { 3805 DEVICE_OWNER_TYPE_DEFAULT, 3806 DEVICE_OWNER_TYPE_FINANCED 3807 }) 3808 public @interface DeviceOwnerType {} 3809 3810 /** @hide */ 3811 @TestApi 3812 public static final int OPERATION_LOCK_NOW = 1; 3813 /** @hide */ 3814 @TestApi 3815 public static final int OPERATION_SWITCH_USER = 2; 3816 /** @hide */ 3817 @TestApi 3818 public static final int OPERATION_START_USER_IN_BACKGROUND = 3; 3819 /** @hide */ 3820 @TestApi 3821 public static final int OPERATION_STOP_USER = 4; 3822 /** @hide */ 3823 @TestApi 3824 public static final int OPERATION_CREATE_AND_MANAGE_USER = 5; 3825 /** @hide */ 3826 @TestApi 3827 public static final int OPERATION_REMOVE_USER = 6; 3828 /** @hide */ 3829 @TestApi 3830 public static final int OPERATION_REBOOT = 7; 3831 /** @hide */ 3832 @TestApi 3833 public static final int OPERATION_WIPE_DATA = 8; 3834 /** @hide */ 3835 @TestApi 3836 public static final int OPERATION_LOGOUT_USER = 9; 3837 /** @hide */ 3838 @TestApi 3839 public static final int OPERATION_SET_USER_RESTRICTION = 10; 3840 /** @hide */ 3841 @TestApi 3842 public static final int OPERATION_SET_SYSTEM_SETTING = 11; 3843 /** @hide */ 3844 @TestApi 3845 public static final int OPERATION_SET_KEYGUARD_DISABLED = 12; 3846 /** @hide */ 3847 @TestApi 3848 public static final int OPERATION_SET_STATUS_BAR_DISABLED = 13; 3849 /** @hide */ 3850 @TestApi 3851 public static final int OPERATION_SET_SYSTEM_UPDATE_POLICY = 14; 3852 /** @hide */ 3853 @TestApi 3854 public static final int OPERATION_SET_APPLICATION_HIDDEN = 15; 3855 /** @hide */ 3856 @TestApi 3857 public static final int OPERATION_SET_APPLICATION_RESTRICTIONS = 16; 3858 /** @hide */ 3859 @TestApi 3860 public static final int OPERATION_SET_KEEP_UNINSTALLED_PACKAGES = 17; 3861 /** @hide */ 3862 @TestApi 3863 public static final int OPERATION_SET_LOCK_TASK_FEATURES = 18; 3864 /** @hide */ 3865 @TestApi 3866 public static final int OPERATION_SET_LOCK_TASK_PACKAGES = 19; 3867 /** @hide */ 3868 @TestApi 3869 public static final int OPERATION_SET_PACKAGES_SUSPENDED = 20; 3870 /** @hide */ 3871 @TestApi 3872 public static final int OPERATION_SET_TRUST_AGENT_CONFIGURATION = 21; 3873 /** @hide */ 3874 @TestApi 3875 public static final int OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES = 22; 3876 /** @hide */ 3877 @TestApi 3878 public static final int OPERATION_CLEAR_APPLICATION_USER_DATA = 23; 3879 /** @hide */ 3880 @TestApi 3881 public static final int OPERATION_INSTALL_CA_CERT = 24; 3882 /** @hide */ 3883 @TestApi 3884 public static final int OPERATION_INSTALL_KEY_PAIR = 25; 3885 /** @hide */ 3886 @TestApi 3887 public static final int OPERATION_INSTALL_SYSTEM_UPDATE = 26; 3888 /** @hide */ 3889 @TestApi 3890 public static final int OPERATION_REMOVE_ACTIVE_ADMIN = 27; 3891 /** @hide */ 3892 @TestApi 3893 public static final int OPERATION_REMOVE_KEY_PAIR = 28; 3894 /** @hide */ 3895 @TestApi 3896 public static final int OPERATION_REQUEST_BUGREPORT = 29; 3897 /** @hide */ 3898 @TestApi 3899 public static final int OPERATION_SET_ALWAYS_ON_VPN_PACKAGE = 30; 3900 /** @hide */ 3901 @TestApi 3902 public static final int OPERATION_SET_CAMERA_DISABLED = 31; 3903 /** @hide */ 3904 @TestApi 3905 public static final int OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY = 32; 3906 /** @hide */ 3907 @TestApi 3908 public static final int OPERATION_SET_GLOBAL_PRIVATE_DNS = 33; 3909 /** @hide */ 3910 @TestApi 3911 public static final int OPERATION_SET_LOGOUT_ENABLED = 34; 3912 /** @hide */ 3913 @TestApi 3914 public static final int OPERATION_SET_MASTER_VOLUME_MUTED = 35; 3915 /** @hide */ 3916 @TestApi 3917 public static final int OPERATION_SET_OVERRIDE_APNS_ENABLED = 36; 3918 /** @hide */ 3919 @TestApi 3920 public static final int OPERATION_SET_PERMISSION_GRANT_STATE = 37; 3921 /** @hide */ 3922 @TestApi 3923 public static final int OPERATION_SET_PERMISSION_POLICY = 38; 3924 /** @hide */ 3925 @TestApi 3926 public static final int OPERATION_SET_RESTRICTIONS_PROVIDER = 39; 3927 /** @hide */ 3928 @TestApi 3929 public static final int OPERATION_UNINSTALL_CA_CERT = 40; 3930 /** @hide */ 3931 @TestApi 3932 @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED) 3933 public static final int OPERATION_SET_CONTENT_PROTECTION_POLICY = 41; 3934 3935 /** @hide */ 3936 @TestApi 3937 @FlaggedApi(android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER) 3938 public static final int OPERATION_SET_APP_FUNCTIONS_POLICY = 42; 3939 3940 private static final String PREFIX_OPERATION = "OPERATION_"; 3941 3942 /** @hide */ 3943 @IntDef(prefix = PREFIX_OPERATION, value = { 3944 OPERATION_LOCK_NOW, 3945 OPERATION_SWITCH_USER, 3946 OPERATION_START_USER_IN_BACKGROUND, 3947 OPERATION_STOP_USER, 3948 OPERATION_CREATE_AND_MANAGE_USER, 3949 OPERATION_REMOVE_USER, 3950 OPERATION_REBOOT, 3951 OPERATION_WIPE_DATA, 3952 OPERATION_LOGOUT_USER, 3953 OPERATION_SET_USER_RESTRICTION, 3954 OPERATION_SET_SYSTEM_SETTING, 3955 OPERATION_SET_KEYGUARD_DISABLED, 3956 OPERATION_SET_STATUS_BAR_DISABLED, 3957 OPERATION_SET_SYSTEM_UPDATE_POLICY, 3958 OPERATION_SET_APPLICATION_HIDDEN, 3959 OPERATION_SET_APPLICATION_RESTRICTIONS, 3960 OPERATION_SET_KEEP_UNINSTALLED_PACKAGES, 3961 OPERATION_SET_LOCK_TASK_FEATURES, 3962 OPERATION_SET_LOCK_TASK_PACKAGES, 3963 OPERATION_SET_PACKAGES_SUSPENDED, 3964 OPERATION_SET_TRUST_AGENT_CONFIGURATION, 3965 OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES, 3966 OPERATION_CLEAR_APPLICATION_USER_DATA, 3967 OPERATION_INSTALL_CA_CERT, 3968 OPERATION_INSTALL_KEY_PAIR, 3969 OPERATION_INSTALL_SYSTEM_UPDATE, 3970 OPERATION_REMOVE_ACTIVE_ADMIN, 3971 OPERATION_REMOVE_KEY_PAIR, 3972 OPERATION_REQUEST_BUGREPORT, 3973 OPERATION_SET_ALWAYS_ON_VPN_PACKAGE, 3974 OPERATION_SET_CAMERA_DISABLED, 3975 OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY, 3976 OPERATION_SET_GLOBAL_PRIVATE_DNS, 3977 OPERATION_SET_LOGOUT_ENABLED, 3978 OPERATION_SET_MASTER_VOLUME_MUTED, 3979 OPERATION_SET_OVERRIDE_APNS_ENABLED, 3980 OPERATION_SET_PERMISSION_GRANT_STATE, 3981 OPERATION_SET_PERMISSION_POLICY, 3982 OPERATION_SET_RESTRICTIONS_PROVIDER, 3983 OPERATION_UNINSTALL_CA_CERT, 3984 OPERATION_SET_CONTENT_PROTECTION_POLICY, 3985 OPERATION_SET_APP_FUNCTIONS_POLICY 3986 }) 3987 @Retention(RetentionPolicy.SOURCE) 3988 public static @interface DevicePolicyOperation { 3989 } 3990 3991 /** @hide */ 3992 @TestApi 3993 @NonNull operationToString(@evicePolicyOperation int operation)3994 public static String operationToString(@DevicePolicyOperation int operation) { 3995 return DebugUtils.constantToString(DevicePolicyManager.class, PREFIX_OPERATION, operation); 3996 } 3997 3998 private static final String PREFIX_OPERATION_SAFETY_REASON = "OPERATION_SAFETY_REASON_"; 3999 4000 /** @hide */ 4001 @IntDef(prefix = PREFIX_OPERATION_SAFETY_REASON, value = { 4002 OPERATION_SAFETY_REASON_NONE, 4003 OPERATION_SAFETY_REASON_DRIVING_DISTRACTION 4004 }) 4005 @Retention(RetentionPolicy.SOURCE) 4006 public static @interface OperationSafetyReason { 4007 } 4008 4009 /** @hide */ 4010 @TestApi 4011 public static final int OPERATION_SAFETY_REASON_NONE = -1; 4012 4013 /** 4014 * Indicates that a {@link UnsafeStateException} was thrown because the operation would distract 4015 * the driver of the vehicle. 4016 */ 4017 public static final int OPERATION_SAFETY_REASON_DRIVING_DISTRACTION = 1; 4018 4019 /** 4020 * Prevent an app from being suspended. 4021 * 4022 * @hide 4023 */ 4024 @SystemApi 4025 public static final int EXEMPT_FROM_SUSPENSION = 0; 4026 4027 /** 4028 * Prevent an app from dismissible notifications. Starting from Android U, notifications with 4029 * the ongoing parameter can be dismissed by a user on an unlocked device. An app with 4030 * this exemption can create non-dismissible notifications. 4031 * 4032 * @hide 4033 */ 4034 @SystemApi 4035 public static final int EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS = 1; 4036 4037 /** 4038 * Allows an application to start an activity while running in the background. 4039 * 4040 * @hide 4041 */ 4042 @SystemApi 4043 public static final int EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION = 2; 4044 4045 /** 4046 * Prevent an app from entering hibernation. 4047 * 4048 * @hide 4049 */ 4050 @SystemApi 4051 public static final int EXEMPT_FROM_HIBERNATION = 3; 4052 4053 /** 4054 * Exempt an app from all power-related restrictions, including app standby. 4055 * In addition, the app will be able to start foreground services from the background, 4056 * and the user will not be able to stop foreground services run by the app. 4057 * 4058 * <p><strong>Note:</strong> This option does NOT exempt apps from Doze mode. In fact, 4059 * DPC apps themselves are not automatically exempted from Doze mode either. 4060 * 4061 * @hide 4062 */ 4063 @SystemApi 4064 public static final int EXEMPT_FROM_POWER_RESTRICTIONS = 4; 4065 4066 /** 4067 * Exemptions to platform restrictions, given to an application through 4068 * {@link #setApplicationExemptions(String, Set)}. 4069 * 4070 * @hide 4071 */ 4072 @IntDef(prefix = { "EXEMPT_FROM_"}, value = { 4073 EXEMPT_FROM_SUSPENSION, 4074 EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS, 4075 EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION, 4076 EXEMPT_FROM_HIBERNATION, 4077 EXEMPT_FROM_POWER_RESTRICTIONS 4078 }) 4079 @Retention(RetentionPolicy.SOURCE) 4080 public @interface ApplicationExemptionConstants {} 4081 4082 /** 4083 * Broadcast action: notify system apps (e.g. settings, SysUI, etc) that the device management 4084 * resources with IDs {@link #EXTRA_RESOURCE_IDS} has been updated, the updated resources can be 4085 * retrieved using {@link DevicePolicyResourcesManager#getDrawable} and 4086 * {@link DevicePolicyResourcesManager#getString}. 4087 * 4088 * <p>This broadcast is sent to registered receivers only. 4089 * 4090 * <p> {@link #EXTRA_RESOURCE_TYPE} will be included to identify the type of resource being 4091 * updated. 4092 */ 4093 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 4094 public static final String ACTION_DEVICE_POLICY_RESOURCE_UPDATED = 4095 "android.app.action.DEVICE_POLICY_RESOURCE_UPDATED"; 4096 4097 /** 4098 * An {@code int} extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate the type 4099 * of the resource being updated, the type can be {@link #EXTRA_RESOURCE_TYPE_DRAWABLE} or 4100 * {@link #EXTRA_RESOURCE_TYPE_STRING} 4101 */ 4102 public static final String EXTRA_RESOURCE_TYPE = 4103 "android.app.extra.RESOURCE_TYPE"; 4104 4105 /** 4106 * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type 4107 * {@link Drawable} is being updated. 4108 */ 4109 public static final int EXTRA_RESOURCE_TYPE_DRAWABLE = 1; 4110 4111 /** 4112 * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type 4113 * {@link String} is being updated. 4114 */ 4115 public static final int EXTRA_RESOURCE_TYPE_STRING = 2; 4116 4117 /** 4118 * An integer array extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate which 4119 * resource IDs (i.e. strings and drawables) have been updated. 4120 */ 4121 public static final String EXTRA_RESOURCE_IDS = 4122 "android.app.extra.RESOURCE_IDS"; 4123 4124 /** 4125 * Broadcast Action: Broadcast sent to indicate that the device financing state has changed. 4126 * 4127 * <p>This occurs when, for example, a financing kiosk app has been added or removed. 4128 * 4129 * <p>To query the current device financing state see {@link #isDeviceFinanced}. 4130 * 4131 * <p>This will be delivered to the following apps if they include a receiver for this action 4132 * in their manifest: 4133 * <ul> 4134 * <li>Device owner admins. 4135 * <li>Organization-owned profile owner admins 4136 * <li>The supervision app 4137 * <li>The device management role holder 4138 * </ul> 4139 */ 4140 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION) 4141 @BroadcastBehavior(explicitOnly = true, includeBackground = true) 4142 public static final String ACTION_DEVICE_FINANCING_STATE_CHANGED = 4143 "android.app.admin.action.DEVICE_FINANCING_STATE_CHANGED"; 4144 4145 /** Allow the user to choose whether to enable MTE on the device. */ 4146 public static final int MTE_NOT_CONTROLLED_BY_POLICY = 0; 4147 4148 /** 4149 * Require that MTE be enabled on the device, if supported. Can be set by a device owner or a 4150 * profile owner of an organization-owned managed profile. 4151 */ 4152 public static final int MTE_ENABLED = 1; 4153 4154 /** Require that MTE be disabled on the device. Can be set by a device owner. */ 4155 public static final int MTE_DISABLED = 2; 4156 4157 /** @hide */ 4158 @IntDef( 4159 prefix = {"MTE_"}, 4160 value = {MTE_ENABLED, MTE_DISABLED, MTE_NOT_CONTROLLED_BY_POLICY}) 4161 @Retention(RetentionPolicy.SOURCE) 4162 public static @interface MtePolicy {} 4163 4164 /** 4165 * Called by a device owner, profile owner of an organization-owned device, to set the Memory 4166 * Tagging Extension (MTE) policy. MTE is a CPU extension that allows to protect against certain 4167 * classes of security problems at a small runtime performance cost overhead. 4168 * 4169 * <p>The MTE policy can only be set to {@link #MTE_DISABLED} if called by a device owner. 4170 * Otherwise a {@link SecurityException} will be thrown. 4171 * 4172 * <p>The device needs to be rebooted to apply changes to the MTE policy. 4173 * 4174 * @throws SecurityException if caller is not permitted to set Mte policy 4175 * @throws UnsupportedOperationException if the device does not support MTE 4176 * @param policy the MTE policy to be set 4177 */ 4178 @RequiresPermission(value = MANAGE_DEVICE_POLICY_MTE, conditional = true) setMtePolicy(@tePolicy int policy)4179 public void setMtePolicy(@MtePolicy int policy) { 4180 throwIfParentInstance("setMtePolicy"); 4181 if (mService != null) { 4182 try { 4183 mService.setMtePolicy(policy, mContext.getPackageName()); 4184 } catch (RemoteException e) { 4185 throw e.rethrowFromSystemServer(); 4186 } 4187 } 4188 } 4189 4190 4191 /** 4192 * Similar to the public variant of {@link #setMtePolicy} but for use by the system. 4193 * 4194 * <p>Called by a system service only, meaning that the caller's UID must be equal to 4195 * {@link Process#SYSTEM_UID}. 4196 * 4197 * @throws SecurityException if caller is not permitted to set Mte policy 4198 * @throws UnsupportedOperationException if the device does not support MTE 4199 * @param systemEntity The service entity that adds the restriction. A user restriction set by 4200 * a service entity can only be cleared by the same entity. This can be 4201 * just the calling package name, or any string of the caller's choice 4202 * can be used. 4203 * @param policy the MTE policy to be set 4204 * @hide 4205 */ setMtePolicy(@onNull String systemEntity, @MtePolicy int policy)4206 public void setMtePolicy(@NonNull String systemEntity, @MtePolicy int policy) { 4207 throwIfParentInstance("setMtePolicyForUser"); 4208 if (mService != null) { 4209 try { 4210 mService.setMtePolicyBySystem(systemEntity, policy); 4211 } catch (RemoteException e) { 4212 throw e.rethrowFromSystemServer(); 4213 } 4214 } 4215 } 4216 4217 4218 4219 /** 4220 * Called by a device owner, profile owner of an organization-owned device to 4221 * get the Memory Tagging Extension (MTE) policy 4222 * 4223 * <a href="https://source.android.com/docs/security/test/memory-safety/arm-mte"> 4224 * Learn more about MTE</a> 4225 * 4226 * @throws SecurityException if caller is not permitted to set Mte policy 4227 * @return the currently set MTE policy 4228 */ 4229 @RequiresPermission(value = MANAGE_DEVICE_POLICY_MTE, conditional = true) getMtePolicy()4230 public @MtePolicy int getMtePolicy() { 4231 throwIfParentInstance("setMtePolicy"); 4232 if (mService != null) { 4233 try { 4234 return mService.getMtePolicy(mContext.getPackageName()); 4235 } catch (RemoteException e) { 4236 throw e.rethrowFromSystemServer(); 4237 } 4238 } 4239 return MTE_NOT_CONTROLLED_BY_POLICY; 4240 } 4241 4242 /** 4243 * Get the current MTE state of the device. 4244 * 4245 * <a href="https://source.android.com/docs/security/test/memory-safety/arm-mte"> 4246 * Learn more about MTE</a> 4247 * 4248 * @return whether MTE is currently enabled on the device. 4249 */ isMtePolicyEnforced()4250 public static boolean isMtePolicyEnforced() { 4251 return Zygote.nativeSupportsMemoryTagging(); 4252 } 4253 4254 /** Indicates that content protection is not controlled by policy, allowing user to choose. */ 4255 @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED) 4256 public static final int CONTENT_PROTECTION_NOT_CONTROLLED_BY_POLICY = 0; 4257 4258 /** Indicates that content protection is controlled and disabled by a policy (default). */ 4259 @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED) 4260 public static final int CONTENT_PROTECTION_DISABLED = 1; 4261 4262 /** Indicates that content protection is controlled and enabled by a policy. */ 4263 @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED) 4264 public static final int CONTENT_PROTECTION_ENABLED = 2; 4265 4266 /** @hide */ 4267 @IntDef( 4268 prefix = {"CONTENT_PROTECTION_"}, 4269 value = { 4270 CONTENT_PROTECTION_NOT_CONTROLLED_BY_POLICY, 4271 CONTENT_PROTECTION_DISABLED, 4272 CONTENT_PROTECTION_ENABLED, 4273 }) 4274 @Retention(RetentionPolicy.SOURCE) 4275 public @interface ContentProtectionPolicy {} 4276 4277 /** 4278 * Sets the content protection policy which controls scanning for deceptive apps. 4279 * <p> 4280 * This function can only be called by the device owner, a profile owner of an affiliated user 4281 * or profile, or the profile owner when no device owner is set or holders of the permission 4282 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CONTENT_PROTECTION}. See 4283 * {@link #isAffiliatedUser}. 4284 * Any policy set via this method will be cleared if the user becomes unaffiliated. 4285 * <p> 4286 * After the content protection policy has been set, 4287 * {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle, TargetUser, 4288 * PolicyUpdateResult)} will notify the admin on whether the policy was successfully set or not. 4289 * This callback will contain: 4290 * <ul> 4291 * <li> The policy identifier {@link DevicePolicyIdentifiers#CONTENT_PROTECTION_POLICY} 4292 * <li> The {@link TargetUser} that this policy relates to 4293 * <li> The {@link PolicyUpdateResult}, which will be 4294 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 4295 * reason the policy failed to be set 4296 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 4297 * </ul> 4298 * If there has been a change to the policy, 4299 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 4300 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 4301 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 4302 * will contain the reason why the policy changed. 4303 * 4304 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 4305 * caller is not a device admin. 4306 * @param policy The content protection policy to set. One of {@link 4307 * #CONTENT_PROTECTION_NOT_CONTROLLED_BY_POLICY}, 4308 * {@link #CONTENT_PROTECTION_DISABLED} or {@link #CONTENT_PROTECTION_ENABLED}. 4309 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an 4310 * affiliated user or profile, or the profile owner when no device owner is set or holder of the 4311 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CONTENT_PROTECTION}. 4312 * @see #isAffiliatedUser 4313 */ 4314 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CONTENT_PROTECTION, conditional = true) 4315 @SupportsCoexistence 4316 @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED) setContentProtectionPolicy( @ullable ComponentName admin, @ContentProtectionPolicy int policy)4317 public void setContentProtectionPolicy( 4318 @Nullable ComponentName admin, @ContentProtectionPolicy int policy) { 4319 throwIfParentInstance("setContentProtectionPolicy"); 4320 if (mService != null) { 4321 try { 4322 mService.setContentProtectionPolicy(admin, mContext.getPackageName(), policy); 4323 } catch (RemoteException e) { 4324 throw e.rethrowFromSystemServer(); 4325 } 4326 } 4327 } 4328 4329 /** 4330 * Returns the current content protection policy. 4331 * <p> 4332 * The returned policy will be the current resolved policy rather than the policy set by the 4333 * calling admin. 4334 * 4335 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 4336 * caller is not a device admin. 4337 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an 4338 * affiliated user or profile, or the profile owner when no device owner is set or holder of the 4339 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CONTENT_PROTECTION}. 4340 * @see #isAffiliatedUser 4341 * @see #setContentProtectionPolicy 4342 */ 4343 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CONTENT_PROTECTION, conditional = true) 4344 @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED) 4345 @UserHandleAware getContentProtectionPolicy(@ullable ComponentName admin)4346 public @ContentProtectionPolicy int getContentProtectionPolicy(@Nullable ComponentName admin) { 4347 throwIfParentInstance("getContentProtectionPolicy"); 4348 if (mService != null) { 4349 try { 4350 return mService.getContentProtectionPolicy(admin, mContext.getPackageName(), 4351 myUserId()); 4352 } catch (RemoteException e) { 4353 throw e.rethrowFromSystemServer(); 4354 } 4355 } 4356 return CONTENT_PROTECTION_DISABLED; 4357 } 4358 4359 /** 4360 * Indicates that {@link android.app.appfunctions.AppFunctionManager} is not controlled by 4361 * policy. 4362 * 4363 * <p>If no admin set this policy, it means appfunctions are enabled. 4364 */ 4365 @FlaggedApi(android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER) 4366 public static final int APP_FUNCTIONS_NOT_CONTROLLED_BY_POLICY = 0; 4367 4368 /** Indicates that {@link android.app.appfunctions.AppFunctionManager} is controlled and 4369 * disabled by policy, i.e. no apps in the current user are allowed to expose app functions. 4370 */ 4371 @FlaggedApi(android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER) 4372 public static final int APP_FUNCTIONS_DISABLED = 1; 4373 4374 /** 4375 * Indicates that {@link android.app.appfunctions.AppFunctionManager} is controlled and 4376 * disabled by a policy for cross profile interactions only, i.e. app functions exposed by apps 4377 * in the current user can only be invoked within the same user. 4378 * 4379 * <p>This is different from {@link #APP_FUNCTIONS_DISABLED} in that it only disables cross 4380 * profile interactions (even if the caller has permissions required to interact across users). 4381 * appfunctions can still be used within the a user profile boundary. 4382 */ 4383 @FlaggedApi(android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER) 4384 public static final int APP_FUNCTIONS_DISABLED_CROSS_PROFILE = 2; 4385 4386 /** @hide */ 4387 @IntDef( 4388 prefix = {"APP_FUNCTIONS_"}, 4389 value = { 4390 APP_FUNCTIONS_NOT_CONTROLLED_BY_POLICY, 4391 APP_FUNCTIONS_DISABLED, 4392 APP_FUNCTIONS_DISABLED_CROSS_PROFILE 4393 }) 4394 @Retention(RetentionPolicy.SOURCE) 4395 public @interface AppFunctionsPolicy {} 4396 4397 /** 4398 * Sets the {@link android.app.appfunctions.AppFunctionManager} policy which controls app 4399 * functions operations on the device. An app function is a piece of functionality that apps 4400 * expose to the system for cross-app orchestration. 4401 * 4402 * <p>This function can only be called by a device owner, a profile owner or holders of the 4403 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_FUNCTIONS}. 4404 * 4405 * @param policy The app functions policy to set. One of {@link 4406 * #APP_FUNCTIONS_NOT_CONTROLLED_BY_POLICY}, 4407 * {@link #APP_FUNCTIONS_DISABLED} or 4408 * {@link #APP_FUNCTIONS_DISABLED_CROSS_PROFILE} 4409 * @throws SecurityException if caller is not a device owner, a profile owner or a holder 4410 * of the permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_FUNCTIONS}. 4411 */ 4412 @RequiresPermission(value = MANAGE_DEVICE_POLICY_APP_FUNCTIONS, conditional = true) 4413 @FlaggedApi(android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER) setAppFunctionsPolicy(@ppFunctionsPolicy int policy)4414 public void setAppFunctionsPolicy(@AppFunctionsPolicy int policy) { 4415 throwIfParentInstance("setAppFunctionsPolicy"); 4416 if (mService != null) { 4417 try { 4418 mService.setAppFunctionsPolicy(mContext.getPackageName(), policy); 4419 } catch (RemoteException e) { 4420 throw e.rethrowFromSystemServer(); 4421 } 4422 } 4423 } 4424 4425 /** 4426 * Returns the current {@link android.app.appfunctions.AppFunctionManager} policy. 4427 * 4428 * <p>The returned policy will be the current resolved policy rather than the policy set by the 4429 * calling admin. 4430 * 4431 * @throws SecurityException if caller is not a device owner, a profile owner or a holder 4432 * of the permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_FUNCTIONS}. 4433 */ 4434 @RequiresPermission(value = MANAGE_DEVICE_POLICY_APP_FUNCTIONS, conditional = true) 4435 @FlaggedApi(android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER) getAppFunctionsPolicy()4436 public @AppFunctionsPolicy int getAppFunctionsPolicy() { 4437 throwIfParentInstance("getAppFunctionsPolicy"); 4438 if (mService != null) { 4439 try { 4440 return mService.getAppFunctionsPolicy(mContext.getPackageName(), 4441 myUserId()); 4442 } catch (RemoteException e) { 4443 throw e.rethrowFromSystemServer(); 4444 } 4445 } 4446 return APP_FUNCTIONS_NOT_CONTROLLED_BY_POLICY; 4447 } 4448 4449 /** 4450 * This object is a single place to tack on invalidation and disable calls. All 4451 * binder caches in this class derive from this Config, so all can be invalidated or 4452 * disabled through this Config. 4453 */ 4454 private static final IpcDataCache.Config sDpmCaches = 4455 new IpcDataCache.Config(8, IpcDataCache.MODULE_SYSTEM, "DevicePolicyManagerCaches") 4456 .cacheNulls(true); 4457 4458 /** @hide */ invalidateBinderCaches()4459 public static void invalidateBinderCaches() { 4460 sDpmCaches.invalidateCache(); 4461 } 4462 4463 /** @hide */ disableLocalCaches()4464 public static void disableLocalCaches() { 4465 sDpmCaches.disableAllForCurrentProcess(); 4466 } 4467 4468 /** @hide */ 4469 @NonNull 4470 @TestApi operationSafetyReasonToString(@perationSafetyReason int reason)4471 public static String operationSafetyReasonToString(@OperationSafetyReason int reason) { 4472 return DebugUtils.constantToString(DevicePolicyManager.class, 4473 PREFIX_OPERATION_SAFETY_REASON, reason); 4474 } 4475 4476 /** @hide */ isValidOperationSafetyReason(@perationSafetyReason int reason)4477 public static boolean isValidOperationSafetyReason(@OperationSafetyReason int reason) { 4478 return reason == OPERATION_SAFETY_REASON_DRIVING_DISTRACTION; 4479 } 4480 4481 /** 4482 * Checks if it's safe to run operations that can be affected by the given {@code reason}. 4483 * 4484 * <p><b>Note:</b> notice that the operation safety state might change between the time this 4485 * method returns and the operation's method is called, so calls to the latter could still throw 4486 * a {@link UnsafeStateException} even when this method returns {@code true}. 4487 * 4488 * @param reason currently, only supported reason is 4489 * {@link #OPERATION_SAFETY_REASON_DRIVING_DISTRACTION}. 4490 * 4491 * @return whether it's safe to run operations that can be affected by the given {@code reason}. 4492 */ 4493 // TODO(b/173541467): should it throw SecurityException if caller is not admin? isSafeOperation(@perationSafetyReason int reason)4494 public boolean isSafeOperation(@OperationSafetyReason int reason) { 4495 throwIfParentInstance("isSafeOperation"); 4496 if (mService == null) return false; 4497 4498 try { 4499 return mService.isSafeOperation(reason); 4500 } catch (RemoteException e) { 4501 throw e.rethrowFromSystemServer(); 4502 } 4503 } 4504 4505 /** 4506 * Acknoledges that the new managed user disclaimer was viewed by the (human) user 4507 * so that {@link #ACTION_SHOW_NEW_USER_DISCLAIMER broadcast} is not sent again the next time 4508 * this user is switched to. 4509 * 4510 * @hide 4511 */ 4512 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 4513 android.Manifest.permission.INTERACT_ACROSS_USERS}) 4514 @UserHandleAware 4515 @TestApi 4516 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) acknowledgeNewUserDisclaimer()4517 public void acknowledgeNewUserDisclaimer() { 4518 if (mService != null) { 4519 try { 4520 mService.acknowledgeNewUserDisclaimer(mContext.getUserId()); 4521 } catch (RemoteException e) { 4522 throw e.rethrowFromSystemServer(); 4523 } 4524 } 4525 } 4526 4527 /** 4528 * Checks whether the new managed user disclaimer was viewed by the user. 4529 * 4530 * @hide 4531 */ 4532 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 4533 android.Manifest.permission.INTERACT_ACROSS_USERS}) 4534 @TestApi 4535 @UserHandleAware isNewUserDisclaimerAcknowledged()4536 public boolean isNewUserDisclaimerAcknowledged() { 4537 if (mService != null) { 4538 try { 4539 return mService.isNewUserDisclaimerAcknowledged(mContext.getUserId()); 4540 } catch (RemoteException e) { 4541 throw e.rethrowFromSystemServer(); 4542 } 4543 } 4544 return false; 4545 } 4546 4547 /** 4548 * Return true if the given administrator component is currently active (enabled) in the system. 4549 * 4550 * @param admin The administrator component to check for. 4551 * @return {@code true} if {@code admin} is currently enabled in the system, {@code false} 4552 * otherwise 4553 */ isAdminActive(@onNull ComponentName admin)4554 public boolean isAdminActive(@NonNull ComponentName admin) { 4555 throwIfParentInstance("isAdminActive"); 4556 return isAdminActiveAsUser(admin, myUserId()); 4557 } 4558 4559 /** 4560 * @see #isAdminActive(ComponentName) 4561 * @hide 4562 */ isAdminActiveAsUser(@onNull ComponentName admin, int userId)4563 public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) { 4564 if (mService != null) { 4565 try { 4566 return mService.isAdminActive(admin, userId); 4567 } catch (RemoteException e) { 4568 throw e.rethrowFromSystemServer(); 4569 } 4570 } 4571 return false; 4572 } 4573 4574 /** 4575 * Return true if the given administrator component is currently being removed 4576 * for the user. 4577 * @hide 4578 */ 4579 @TestApi isRemovingAdmin(@onNull ComponentName admin, int userId)4580 public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) { 4581 if (mService != null) { 4582 try { 4583 return mService.isRemovingAdmin(admin, userId); 4584 } catch (RemoteException e) { 4585 throw e.rethrowFromSystemServer(); 4586 } 4587 } 4588 return false; 4589 } 4590 4591 /** 4592 * Return a list of all currently active device administrators' component 4593 * names. If there are no administrators {@code null} may be 4594 * returned. 4595 */ getActiveAdmins()4596 public @Nullable List<ComponentName> getActiveAdmins() { 4597 throwIfParentInstance("getActiveAdmins"); 4598 return getActiveAdminsAsUser(myUserId()); 4599 } 4600 4601 /** 4602 * @see #getActiveAdmins() 4603 * @hide 4604 */ 4605 @UnsupportedAppUsage getActiveAdminsAsUser(int userId)4606 public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) { 4607 if (mService != null) { 4608 try { 4609 return mService.getActiveAdmins(userId); 4610 } catch (RemoteException e) { 4611 throw e.rethrowFromSystemServer(); 4612 } 4613 } 4614 return null; 4615 } 4616 4617 /** 4618 * Used by package administration code to determine if a package can be stopped 4619 * or uninstalled. 4620 * @hide 4621 */ 4622 @SystemApi 4623 @RequiresPermission(INTERACT_ACROSS_USERS_FULL) packageHasActiveAdmins(String packageName)4624 public boolean packageHasActiveAdmins(String packageName) { 4625 return packageHasActiveAdmins(packageName, myUserId()); 4626 } 4627 4628 /** 4629 * Used by package administration code to determine if a package can be stopped 4630 * or uninstalled. 4631 * @hide 4632 */ 4633 @UnsupportedAppUsage packageHasActiveAdmins(String packageName, int userId)4634 public boolean packageHasActiveAdmins(String packageName, int userId) { 4635 if (mService != null) { 4636 try { 4637 return mService.packageHasActiveAdmins(packageName, userId); 4638 } catch (RemoteException e) { 4639 throw e.rethrowFromSystemServer(); 4640 } 4641 } 4642 return false; 4643 } 4644 4645 /** 4646 * Remove a current administration component. This can only be called 4647 * by the application that owns the administration component; if you 4648 * try to remove someone else's component, a security exception will be 4649 * thrown. 4650 * 4651 * <p>Note that the operation is not synchronous and the admin might still be active (as 4652 * indicated by {@link #getActiveAdmins()}) by the time this method returns. 4653 * 4654 * @param admin The administration compononent to remove. 4655 * @throws SecurityException if the caller is not in the owner application of {@code admin}. 4656 */ removeActiveAdmin(@onNull ComponentName admin)4657 public void removeActiveAdmin(@NonNull ComponentName admin) { 4658 throwIfParentInstance("removeActiveAdmin"); 4659 if (mService != null) { 4660 try { 4661 mService.removeActiveAdmin(admin, myUserId()); 4662 } catch (RemoteException e) { 4663 throw e.rethrowFromSystemServer(); 4664 } 4665 } 4666 } 4667 4668 /** 4669 * Returns true if an administrator has been granted a particular device policy. This can be 4670 * used to check whether the administrator was activated under an earlier set of policies, but 4671 * requires additional policies after an upgrade. 4672 * 4673 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an 4674 * active administrator, or an exception will be thrown. 4675 * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}. 4676 * @throws SecurityException if {@code admin} is not an active administrator. 4677 */ hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)4678 public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) { 4679 throwIfParentInstance("hasGrantedPolicy"); 4680 if (mService != null) { 4681 try { 4682 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId()); 4683 } catch (RemoteException e) { 4684 throw e.rethrowFromSystemServer(); 4685 } 4686 } 4687 return false; 4688 } 4689 4690 /** 4691 * Constant for {@link #setPasswordQuality}: the policy has no requirements 4692 * for the password. Note that quality constants are ordered so that higher 4693 * values are more restrictive. 4694 */ 4695 public static final int PASSWORD_QUALITY_UNSPECIFIED = 0; 4696 4697 /** 4698 * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric 4699 * recognition technology. This implies technologies that can recognize the identity of 4700 * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000). 4701 * Note that quality constants are ordered so that higher values are more restrictive. 4702 */ 4703 public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000; 4704 4705 /** 4706 * Constant for {@link #setPasswordQuality}: the policy requires some kind 4707 * of password or pattern, but doesn't care what it is. Note that quality constants 4708 * are ordered so that higher values are more restrictive. 4709 */ 4710 public static final int PASSWORD_QUALITY_SOMETHING = 0x10000; 4711 4712 /** 4713 * Constant for {@link #setPasswordQuality}: the user must have entered a 4714 * password containing at least numeric characters. Note that quality 4715 * constants are ordered so that higher values are more restrictive. 4716 */ 4717 public static final int PASSWORD_QUALITY_NUMERIC = 0x20000; 4718 4719 /** 4720 * Constant for {@link #setPasswordQuality}: the user must have entered a 4721 * password containing at least numeric characters with no repeating (4444) 4722 * or ordered (1234, 4321, 2468) sequences. Note that quality 4723 * constants are ordered so that higher values are more restrictive. 4724 */ 4725 public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000; 4726 4727 /** 4728 * Constant for {@link #setPasswordQuality}: the user must have entered a 4729 * password containing at least alphabetic (or other symbol) characters. 4730 * Note that quality constants are ordered so that higher values are more 4731 * restrictive. 4732 */ 4733 public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000; 4734 4735 /** 4736 * Constant for {@link #setPasswordQuality}: the user must have entered a 4737 * password containing at least <em>both></em> numeric <em>and</em> 4738 * alphabetic (or other symbol) characters. Note that quality constants are 4739 * ordered so that higher values are more restrictive. 4740 */ 4741 public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000; 4742 4743 /** 4744 * Constant for {@link #setPasswordQuality}: allows the admin to set precisely how many 4745 * characters of various types the password should contain to satisfy the policy. The admin 4746 * should set these requirements via {@link #setPasswordMinimumLetters}, 4747 * {@link #setPasswordMinimumNumeric}, {@link #setPasswordMinimumSymbols}, 4748 * {@link #setPasswordMinimumUpperCase}, {@link #setPasswordMinimumLowerCase}, 4749 * {@link #setPasswordMinimumNonLetter}, and {@link #setPasswordMinimumLength}. 4750 * Note that quality constants are ordered so that higher values are more restrictive. 4751 */ 4752 public static final int PASSWORD_QUALITY_COMPLEX = 0x60000; 4753 4754 /** 4755 * Constant for {@link #setPasswordQuality}: the user is not allowed to 4756 * modify password. In case this password quality is set, the password is 4757 * managed by a profile owner. The profile owner can set any password, 4758 * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note 4759 * that quality constants are ordered so that higher values are more 4760 * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is 4761 * the highest. 4762 * @hide 4763 */ 4764 public static final int PASSWORD_QUALITY_MANAGED = 0x80000; 4765 4766 /** 4767 * @hide 4768 * 4769 * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to 4770 * a user with accounts. {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} 4771 * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features 4772 * used by authenticator to exempt their accounts from this: 4773 * 4774 * <ul> 4775 * <li>Non-test-only DO/PO still can't be installed when there are accounts. 4776 * <p>In order to make an apk test-only, add android:testOnly="true" to the 4777 * <application> tag in the manifest. 4778 * 4779 * <li>Test-only DO/PO can be installed even when there are accounts, as long as all the 4780 * accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature. 4781 * Some authenticators claim to have any features, so to detect it, we also check 4782 * {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing 4783 * if any of the accounts have it. 4784 * </ul> 4785 */ 4786 @SystemApi 4787 public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED = 4788 "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED"; 4789 4790 /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */ 4791 @SystemApi 4792 public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED = 4793 "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED"; 4794 4795 /** 4796 * A {@code boolean} metadata to be included in a mainline module's {@code <application>} 4797 * manifest element, which declares that the module should be considered a required app for 4798 * managed users. 4799 * <p>Being declared as a required app prevents removal of this package during the 4800 * provisioning process. 4801 * @hide 4802 */ 4803 @SystemApi 4804 public static final String REQUIRED_APP_MANAGED_USER = "android.app.REQUIRED_APP_MANAGED_USER"; 4805 4806 /** 4807 * A {@code boolean} metadata to be included in a mainline module's {@code <application>} 4808 * manifest element, which declares that the module should be considered a required app for 4809 * managed devices. 4810 * <p>Being declared as a required app prevents removal of this package during the 4811 * provisioning process. 4812 * @hide 4813 */ 4814 @SystemApi 4815 public static final String REQUIRED_APP_MANAGED_DEVICE = 4816 "android.app.REQUIRED_APP_MANAGED_DEVICE"; 4817 4818 /** 4819 * A {@code boolean} metadata to be included in a mainline module's {@code <application>} 4820 * manifest element, which declares that the module should be considered a required app for 4821 * managed profiles. 4822 * <p>Being declared as a required app prevents removal of this package during the 4823 * provisioning process. 4824 * @hide 4825 */ 4826 @SystemApi 4827 public static final String REQUIRED_APP_MANAGED_PROFILE = 4828 "android.app.REQUIRED_APP_MANAGED_PROFILE"; 4829 4830 /** 4831 * Called by an application that is administering the device to set the password restrictions it 4832 * is imposing. After setting this, the user will not be able to enter a new password that is 4833 * not at least as restrictive as what has been set. Note that the current password will remain 4834 * until the user has set a new one, so the change does not take place immediately. To prompt 4835 * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or 4836 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method. 4837 * <p> 4838 * Quality constants are ordered so that higher values are more restrictive; thus the highest 4839 * requested quality constant (between the policy set here, the user's preference, and any other 4840 * considerations) is the one that is in effect. 4841 * <p> 4842 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 4843 * password is always treated as empty. 4844 * <p> 4845 * The calling device admin must have requested 4846 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has 4847 * not, a security exception will be thrown. 4848 * <p> 4849 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the 4850 * {@link DevicePolicyManager} instance returned by 4851 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 4852 * profile. Apps targeting {@link android.os.Build.VERSION_CODES#S} and above, with the 4853 * exception of a profile owner on an organization-owned device (as can be identified by 4854 * {@link #isOrganizationOwnedDeviceWithManagedProfile}), will get a 4855 * {@code IllegalArgumentException} when calling this method on the parent 4856 * {@link DevicePolicyManager} instance. 4857 * 4858 * <p><strong>Note:</strong> Specifying password requirements using this method clears the 4859 * password complexity requirements set using {@link #setRequiredPasswordComplexity(int)}. 4860 * If this method is called on the {@link DevicePolicyManager} instance returned by 4861 * {@link #getParentProfileInstance(ComponentName)}, then password complexity requirements 4862 * set on the primary {@link DevicePolicyManager} must be cleared first by calling 4863 * {@link #setRequiredPasswordComplexity} with {@link #PASSWORD_COMPLEXITY_NONE) first. 4864 * 4865 * <p><string>Note:</strong> this method is ignored on 4866 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}. 4867 * 4868 * @deprecated Prefer using {@link #setRequiredPasswordComplexity(int)}, to require a password 4869 * that satisfies a complexity level defined by the platform, rather than specifying custom 4870 * password requirement. 4871 * Setting custom, overly-complicated password requirements leads to passwords that are hard 4872 * for users to remember and may not provide any security benefits given as Android uses 4873 * hardware-backed throttling to thwart online and offline brute-forcing of the device's 4874 * screen lock. Company-owned devices (fully-managed and organization-owned managed profile 4875 * devices) are able to continue using this method, though it is recommended that 4876 * {@link #setRequiredPasswordComplexity(int)} should be used instead. 4877 * 4878 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 4879 * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED}, 4880 * {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK}, 4881 * {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC}, 4882 * {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC}, 4883 * {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}. 4884 * @throws SecurityException if {@code admin} is not an active administrator, if {@code admin} 4885 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} or if the 4886 * calling app is targeting {@link android.os.Build.VERSION_CODES#S} and above, 4887 * and is calling the method the {@link DevicePolicyManager} instance returned by 4888 * {@link #getParentProfileInstance(ComponentName)}. 4889 * @throws IllegalStateException if the caller is trying to set password quality on the parent 4890 * {@link DevicePolicyManager} instance while password complexity was set on the 4891 * primary {@link DevicePolicyManager} instance. 4892 */ 4893 @Deprecated setPasswordQuality(@onNull ComponentName admin, int quality)4894 public void setPasswordQuality(@NonNull ComponentName admin, int quality) { 4895 if (mService != null) { 4896 try { 4897 mService.setPasswordQuality(admin, quality, mParentInstance); 4898 } catch (RemoteException e) { 4899 throw e.rethrowFromSystemServer(); 4900 } 4901 } 4902 } 4903 4904 /** 4905 * Retrieve the current minimum password quality for a particular admin or all admins that set 4906 * restrictions on this user and its participating profiles. Restrictions on profiles that have 4907 * a separate challenge are not taken into account. 4908 * 4909 * <p>This method can be called on the {@link DevicePolicyManager} instance 4910 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 4911 * restrictions on the parent profile. 4912 * 4913 * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, 4914 * the password is always treated as empty. 4915 * 4916 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 4917 * 4918 * @param admin The name of the admin component to check, or {@code null} to aggregate 4919 * all admins. 4920 */ 4921 @Deprecated getPasswordQuality(@ullable ComponentName admin)4922 public int getPasswordQuality(@Nullable ComponentName admin) { 4923 return getPasswordQuality(admin, myUserId()); 4924 } 4925 4926 /** @hide per-user version */ 4927 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) getPasswordQuality(@ullable ComponentName admin, int userHandle)4928 public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) { 4929 if (mService != null) { 4930 try { 4931 return mService.getPasswordQuality(admin, userHandle, mParentInstance); 4932 } catch (RemoteException e) { 4933 throw e.rethrowFromSystemServer(); 4934 } 4935 } 4936 return PASSWORD_QUALITY_UNSPECIFIED; 4937 } 4938 4939 /** 4940 * Called by an application that is administering the device to set the minimum allowed password 4941 * length. After setting this, the user will not be able to enter a new password that is not at 4942 * least as restrictive as what has been set. Note that the current password will remain until 4943 * the user has set a new one, so the change does not take place immediately. To prompt the user 4944 * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or 4945 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is 4946 * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC} 4947 * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC}, 4948 * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with 4949 * {@link #setPasswordQuality}. If an app targeting SDK level 4950 * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings 4951 * password quality to one of these values first, this method will throw 4952 * {@link IllegalStateException}. 4953 * <p> 4954 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 4955 * password is always treated as empty. 4956 * <p> 4957 * The calling device admin must have requested 4958 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has 4959 * not, a security exception will be thrown. 4960 * <p> 4961 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the 4962 * {@link DevicePolicyManager} instance returned by 4963 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 4964 * profile. 4965 * 4966 * <p><string>Note:</strong> this method is ignored on 4967 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}. 4968 * 4969 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 4970 * 4971 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 4972 * @param length The new desired minimum password length. A value of 0 means there is no 4973 * restriction. 4974 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin} 4975 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} 4976 * @throws IllegalStateException if the calling app is targeting SDK level 4977 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password 4978 * quality requirement prior to calling this method. 4979 */ 4980 @Deprecated setPasswordMinimumLength(@onNull ComponentName admin, int length)4981 public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) { 4982 if (mService != null) { 4983 try { 4984 mService.setPasswordMinimumLength(admin, length, mParentInstance); 4985 } catch (RemoteException e) { 4986 throw e.rethrowFromSystemServer(); 4987 } 4988 } 4989 } 4990 4991 /** 4992 * Retrieve the current minimum password length for a particular admin or all admins that set 4993 * restrictions on this user and its participating profiles. Restrictions on profiles that have 4994 * a separate challenge are not taken into account. 4995 * 4996 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 4997 * password is always treated as empty. 4998 * 4999 * <p>This method can be called on the {@link DevicePolicyManager} instance 5000 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5001 * restrictions on the parent profile. 5002 * 5003 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5004 * 5005 * @param admin The name of the admin component to check, or {@code null} to aggregate 5006 * all admins. 5007 */ 5008 @Deprecated getPasswordMinimumLength(@ullable ComponentName admin)5009 public int getPasswordMinimumLength(@Nullable ComponentName admin) { 5010 return getPasswordMinimumLength(admin, myUserId()); 5011 } 5012 5013 /** @hide per-user version */ 5014 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)5015 public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) { 5016 if (mService != null) { 5017 try { 5018 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance); 5019 } catch (RemoteException e) { 5020 throw e.rethrowFromSystemServer(); 5021 } 5022 } 5023 return 0; 5024 } 5025 5026 /** 5027 * Called by an application that is administering the device to set the minimum number of upper 5028 * case letters required in the password. After setting this, the user will not be able to enter 5029 * a new password that is not at least as restrictive as what has been set. Note that the 5030 * current password will remain until the user has set a new one, so the change does not take 5031 * place immediately. To prompt the user for a new password, use 5032 * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after 5033 * setting this value. This constraint is only imposed if the administrator has also requested 5034 * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting 5035 * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without 5036 * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw 5037 * {@link IllegalStateException}. The default value is 0. 5038 * <p> 5039 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5040 * password is always treated as empty. 5041 * <p> 5042 * The calling device admin must have requested 5043 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has 5044 * not, a security exception will be thrown. 5045 * <p> 5046 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the 5047 * {@link DevicePolicyManager} instance returned by 5048 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 5049 * profile. 5050 * 5051 * <p><string>Note:</strong> this method is ignored on 5052 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}. 5053 * 5054 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5055 * 5056 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 5057 * @param length The new desired minimum number of upper case letters required in the password. 5058 * A value of 0 means there is no restriction. 5059 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin} 5060 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} 5061 * @throws IllegalStateException if the calling app is targeting SDK level 5062 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password 5063 * quality requirement prior to calling this method. 5064 */ 5065 @Deprecated setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)5066 public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) { 5067 if (mService != null) { 5068 try { 5069 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance); 5070 } catch (RemoteException e) { 5071 throw e.rethrowFromSystemServer(); 5072 } 5073 } 5074 } 5075 5076 /** 5077 * Retrieve the current number of upper case letters required in the password 5078 * for a particular admin or all admins that set restrictions on this user and 5079 * its participating profiles. Restrictions on profiles that have a separate challenge 5080 * are not taken into account. 5081 * This is the same value as set by 5082 * {@link #setPasswordMinimumUpperCase(ComponentName, int)} 5083 * and only applies when the password quality is 5084 * {@link #PASSWORD_QUALITY_COMPLEX}. 5085 * 5086 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5087 * password is always treated as empty. 5088 * 5089 * <p>This method can be called on the {@link DevicePolicyManager} instance 5090 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5091 * restrictions on the parent profile. 5092 * 5093 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5094 * 5095 * @param admin The name of the admin component to check, or {@code null} to 5096 * aggregate all admins. 5097 * @return The minimum number of upper case letters required in the 5098 * password. 5099 */ 5100 @Deprecated getPasswordMinimumUpperCase(@ullable ComponentName admin)5101 public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) { 5102 return getPasswordMinimumUpperCase(admin, myUserId()); 5103 } 5104 5105 /** @hide per-user version */ 5106 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)5107 public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) { 5108 if (mService != null) { 5109 try { 5110 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance); 5111 } catch (RemoteException e) { 5112 throw e.rethrowFromSystemServer(); 5113 } 5114 } 5115 return 0; 5116 } 5117 5118 /** 5119 * Called by an application that is administering the device to set the minimum number of lower 5120 * case letters required in the password. After setting this, the user will not be able to enter 5121 * a new password that is not at least as restrictive as what has been set. Note that the 5122 * current password will remain until the user has set a new one, so the change does not take 5123 * place immediately. To prompt the user for a new password, use 5124 * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after 5125 * setting this value. This constraint is only imposed if the administrator has also requested 5126 * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting 5127 * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without 5128 * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw 5129 * {@link IllegalStateException}. The default value is 0. 5130 * <p> 5131 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5132 * password is always treated as empty. 5133 * <p> 5134 * The calling device admin must have requested 5135 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has 5136 * not, a security exception will be thrown. 5137 * <p> 5138 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the 5139 * {@link DevicePolicyManager} instance returned by 5140 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 5141 * profile. 5142 * 5143 * <p><string>Note:</strong> this method is ignored on 5144 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}. 5145 * 5146 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5147 * 5148 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 5149 * @param length The new desired minimum number of lower case letters required in the password. 5150 * A value of 0 means there is no restriction. 5151 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin} 5152 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} 5153 * @throws IllegalStateException if the calling app is targeting SDK level 5154 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password 5155 * quality requirement prior to calling this method. 5156 */ 5157 @Deprecated setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)5158 public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) { 5159 if (mService != null) { 5160 try { 5161 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance); 5162 } catch (RemoteException e) { 5163 throw e.rethrowFromSystemServer(); 5164 } 5165 } 5166 } 5167 5168 /** 5169 * Retrieve the current number of lower case letters required in the password 5170 * for a particular admin or all admins that set restrictions on this user 5171 * and its participating profiles. Restrictions on profiles that have 5172 * a separate challenge are not taken into account. 5173 * This is the same value as set by 5174 * {@link #setPasswordMinimumLowerCase(ComponentName, int)} 5175 * and only applies when the password quality is 5176 * {@link #PASSWORD_QUALITY_COMPLEX}. 5177 * 5178 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5179 * password is always treated as empty. 5180 * 5181 * <p>This method can be called on the {@link DevicePolicyManager} instance 5182 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5183 * restrictions on the parent profile. 5184 * 5185 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5186 * 5187 * @param admin The name of the admin component to check, or {@code null} to 5188 * aggregate all admins. 5189 * @return The minimum number of lower case letters required in the 5190 * password. 5191 */ 5192 @Deprecated getPasswordMinimumLowerCase(@ullable ComponentName admin)5193 public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) { 5194 return getPasswordMinimumLowerCase(admin, myUserId()); 5195 } 5196 5197 /** @hide per-user version */ 5198 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)5199 public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) { 5200 if (mService != null) { 5201 try { 5202 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance); 5203 } catch (RemoteException e) { 5204 throw e.rethrowFromSystemServer(); 5205 } 5206 } 5207 return 0; 5208 } 5209 5210 /** 5211 * Called by an application that is administering the device to set the minimum number of 5212 * letters required in the password. After setting this, the user will not be able to enter a 5213 * new password that is not at least as restrictive as what has been set. Note that the current 5214 * password will remain until the user has set a new one, so the change does not take place 5215 * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or 5216 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is 5217 * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with 5218 * {@link #setPasswordQuality}. If an app targeting SDK level 5219 * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings 5220 * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw 5221 * {@link IllegalStateException}. The default value is 1. 5222 * <p> 5223 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5224 * password is always treated as empty. 5225 * <p> 5226 * The calling device admin must have requested 5227 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has 5228 * not, a security exception will be thrown. 5229 * <p> 5230 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the 5231 * {@link DevicePolicyManager} instance returned by 5232 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 5233 * profile. 5234 * 5235 * <p><string>Note:</strong> this method is ignored on 5236 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}. 5237 * 5238 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5239 * 5240 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 5241 * @param length The new desired minimum number of letters required in the password. A value of 5242 * 0 means there is no restriction. 5243 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin} 5244 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} 5245 * @throws IllegalStateException if the calling app is targeting SDK level 5246 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password 5247 * quality requirement prior to calling this method. 5248 */ 5249 @Deprecated setPasswordMinimumLetters(@onNull ComponentName admin, int length)5250 public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) { 5251 if (mService != null) { 5252 try { 5253 mService.setPasswordMinimumLetters(admin, length, mParentInstance); 5254 } catch (RemoteException e) { 5255 throw e.rethrowFromSystemServer(); 5256 } 5257 } 5258 } 5259 5260 /** 5261 * Retrieve the current number of letters required in the password 5262 * for a particular admin or all admins that set restrictions on this user 5263 * and its participating profiles. Restrictions on profiles that have 5264 * a separate challenge are not taken into account. 5265 * This is the same value as set by 5266 * {@link #setPasswordMinimumLetters(ComponentName, int)} 5267 * and only applies when the password quality is 5268 * {@link #PASSWORD_QUALITY_COMPLEX}. 5269 * 5270 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5271 * password is always treated as empty. 5272 * 5273 * <p>This method can be called on the {@link DevicePolicyManager} instance 5274 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5275 * restrictions on the parent profile. 5276 * 5277 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5278 * 5279 * @param admin The name of the admin component to check, or {@code null} to 5280 * aggregate all admins. 5281 * @return The minimum number of letters required in the password. 5282 */ 5283 @Deprecated getPasswordMinimumLetters(@ullable ComponentName admin)5284 public int getPasswordMinimumLetters(@Nullable ComponentName admin) { 5285 return getPasswordMinimumLetters(admin, myUserId()); 5286 } 5287 5288 /** @hide per-user version */ 5289 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)5290 public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) { 5291 if (mService != null) { 5292 try { 5293 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance); 5294 } catch (RemoteException e) { 5295 throw e.rethrowFromSystemServer(); 5296 } 5297 } 5298 return 0; 5299 } 5300 5301 /** 5302 * Called by an application that is administering the device to set the minimum number of 5303 * numerical digits required in the password. After setting this, the user will not be able to 5304 * enter a new password that is not at least as restrictive as what has been set. Note that the 5305 * current password will remain until the user has set a new one, so the change does not take 5306 * place immediately. To prompt the user for a new password, use 5307 * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after 5308 * setting this value. This constraint is only imposed if the administrator has also requested 5309 * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting 5310 * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without 5311 * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw 5312 * {@link IllegalStateException}. The default value is 1. 5313 * <p> 5314 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5315 * password is always treated as empty. 5316 * <p> 5317 * The calling device admin must have requested 5318 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has 5319 * not, a security exception will be thrown. 5320 * <p> 5321 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the 5322 * {@link DevicePolicyManager} instance returned by 5323 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 5324 * profile. 5325 * 5326 * <p><string>Note:</strong> this method is ignored on 5327 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}. 5328 * 5329 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5330 * 5331 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 5332 * @param length The new desired minimum number of numerical digits required in the password. A 5333 * value of 0 means there is no restriction. 5334 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin} 5335 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} 5336 * @throws IllegalStateException if the calling app is targeting SDK level 5337 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password 5338 * quality requirement prior to calling this method. 5339 */ 5340 @Deprecated setPasswordMinimumNumeric(@onNull ComponentName admin, int length)5341 public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) { 5342 if (mService != null) { 5343 try { 5344 mService.setPasswordMinimumNumeric(admin, length, mParentInstance); 5345 } catch (RemoteException e) { 5346 throw e.rethrowFromSystemServer(); 5347 } 5348 } 5349 } 5350 5351 /** 5352 * Retrieve the current number of numerical digits required in the password 5353 * for a particular admin or all admins that set restrictions on this user 5354 * and its participating profiles. Restrictions on profiles that have 5355 * a separate challenge are not taken into account. 5356 * This is the same value as set by 5357 * {@link #setPasswordMinimumNumeric(ComponentName, int)} 5358 * and only applies when the password quality is 5359 * {@link #PASSWORD_QUALITY_COMPLEX}. 5360 * 5361 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5362 * password is always treated as empty. 5363 * 5364 * <p>This method can be called on the {@link DevicePolicyManager} instance 5365 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5366 * restrictions on the parent profile. 5367 * 5368 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5369 * 5370 * @param admin The name of the admin component to check, or {@code null} to 5371 * aggregate all admins. 5372 * @return The minimum number of numerical digits required in the password. 5373 */ 5374 @Deprecated getPasswordMinimumNumeric(@ullable ComponentName admin)5375 public int getPasswordMinimumNumeric(@Nullable ComponentName admin) { 5376 return getPasswordMinimumNumeric(admin, myUserId()); 5377 } 5378 5379 /** @hide per-user version */ 5380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)5381 public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) { 5382 if (mService != null) { 5383 try { 5384 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance); 5385 } catch (RemoteException e) { 5386 throw e.rethrowFromSystemServer(); 5387 } 5388 } 5389 return 0; 5390 } 5391 5392 /** 5393 * Called by an application that is administering the device to set the minimum number of 5394 * symbols required in the password. After setting this, the user will not be able to enter a 5395 * new password that is not at least as restrictive as what has been set. Note that the current 5396 * password will remain until the user has set a new one, so the change does not take place 5397 * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or 5398 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is 5399 * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with 5400 * {@link #setPasswordQuality}. If an app targeting SDK level 5401 * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings 5402 * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw 5403 * {@link IllegalStateException}. The default value is 1. 5404 * <p> 5405 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5406 * password is always treated as empty. 5407 * <p> 5408 * The calling device admin must have requested 5409 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has 5410 * not, a security exception will be thrown. 5411 * <p> 5412 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the 5413 * {@link DevicePolicyManager} instance returned by 5414 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 5415 * profile. 5416 * 5417 * <p><string>Note:</strong> this method is ignored on 5418 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}. 5419 * 5420 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5421 * 5422 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 5423 * @param length The new desired minimum number of symbols required in the password. A value of 5424 * 0 means there is no restriction. 5425 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin} 5426 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} 5427 * @throws IllegalStateException if the calling app is targeting SDK level 5428 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password 5429 * quality requirement prior to calling this method. 5430 */ 5431 @Deprecated setPasswordMinimumSymbols(@onNull ComponentName admin, int length)5432 public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) { 5433 if (mService != null) { 5434 try { 5435 mService.setPasswordMinimumSymbols(admin, length, mParentInstance); 5436 } catch (RemoteException e) { 5437 throw e.rethrowFromSystemServer(); 5438 } 5439 } 5440 } 5441 5442 /** 5443 * Retrieve the current number of symbols required in the password 5444 * for a particular admin or all admins that set restrictions on this user 5445 * and its participating profiles. Restrictions on profiles that have 5446 * a separate challenge are not taken into account. This is the same value as 5447 * set by {@link #setPasswordMinimumSymbols(ComponentName, int)} 5448 * and only applies when the password quality is 5449 * {@link #PASSWORD_QUALITY_COMPLEX}. 5450 * 5451 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5452 * password is always treated as empty. 5453 * 5454 * <p>This method can be called on the {@link DevicePolicyManager} instance 5455 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5456 * restrictions on the parent profile. 5457 * 5458 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5459 * 5460 * @param admin The name of the admin component to check, or {@code null} to 5461 * aggregate all admins. 5462 * @return The minimum number of symbols required in the password. 5463 */ 5464 @Deprecated getPasswordMinimumSymbols(@ullable ComponentName admin)5465 public int getPasswordMinimumSymbols(@Nullable ComponentName admin) { 5466 return getPasswordMinimumSymbols(admin, myUserId()); 5467 } 5468 5469 /** @hide per-user version */ 5470 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)5471 public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) { 5472 if (mService != null) { 5473 try { 5474 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance); 5475 } catch (RemoteException e) { 5476 throw e.rethrowFromSystemServer(); 5477 } 5478 } 5479 return 0; 5480 } 5481 5482 /** 5483 * Called by an application that is administering the device to set the minimum number of 5484 * non-letter characters (numerical digits or symbols) required in the password. After setting 5485 * this, the user will not be able to enter a new password that is not at least as restrictive 5486 * as what has been set. Note that the current password will remain until the user has set a new 5487 * one, so the change does not take place immediately. To prompt the user for a new password, 5488 * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after 5489 * setting this value. This constraint is only imposed if the administrator has also requested 5490 * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting 5491 * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without 5492 * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw 5493 * {@link IllegalStateException}. The default value is 0. 5494 * <p> 5495 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5496 * password is always treated as empty. 5497 * <p> 5498 * The calling device admin must have requested 5499 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has 5500 * not, a security exception will be thrown. 5501 * <p> 5502 * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the 5503 * {@link DevicePolicyManager} instance returned by 5504 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 5505 * profile. 5506 * 5507 * <p><string>Note:</strong> this method is ignored on 5508 * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}. 5509 * 5510 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5511 * 5512 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 5513 * @param length The new desired minimum number of letters required in the password. A value of 5514 * 0 means there is no restriction. 5515 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin} 5516 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} 5517 * @throws IllegalStateException if the calling app is targeting SDK level 5518 * {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password 5519 * quality requirement prior to calling this method. 5520 */ 5521 @Deprecated setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)5522 public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) { 5523 if (mService != null) { 5524 try { 5525 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance); 5526 } catch (RemoteException e) { 5527 throw e.rethrowFromSystemServer(); 5528 } 5529 } 5530 } 5531 5532 /** 5533 * Retrieve the current number of non-letter characters required in the password 5534 * for a particular admin or all admins that set restrictions on this user 5535 * and its participating profiles. Restrictions on profiles that have 5536 * a separate challenge are not taken into account. 5537 * This is the same value as set by 5538 * {@link #setPasswordMinimumNonLetter(ComponentName, int)} 5539 * and only applies when the password quality is 5540 * {@link #PASSWORD_QUALITY_COMPLEX}. 5541 * 5542 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5543 * password is always treated as empty. 5544 * 5545 * <p>This method can be called on the {@link DevicePolicyManager} instance 5546 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5547 * restrictions on the parent profile. 5548 * 5549 * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details. 5550 * 5551 * @param admin The name of the admin component to check, or {@code null} to 5552 * aggregate all admins. 5553 * @return The minimum number of letters required in the password. 5554 */ 5555 @Deprecated getPasswordMinimumNonLetter(@ullable ComponentName admin)5556 public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) { 5557 return getPasswordMinimumNonLetter(admin, myUserId()); 5558 } 5559 5560 /** @hide per-user version */ 5561 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)5562 public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) { 5563 if (mService != null) { 5564 try { 5565 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance); 5566 } catch (RemoteException e) { 5567 throw e.rethrowFromSystemServer(); 5568 } 5569 } 5570 return 0; 5571 } 5572 5573 /** 5574 * Returns minimum PasswordMetrics that satisfies all admin policies. 5575 * 5576 * @hide 5577 */ getPasswordMinimumMetrics(@serIdInt int userHandle)5578 public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle) { 5579 return getPasswordMinimumMetrics(userHandle, false); 5580 } 5581 5582 /** 5583 * Returns minimum PasswordMetrics that satisfies all admin policies. 5584 * If requested, only consider device-wide admin policies and ignore policies set on the 5585 * managed profile instance (as if the managed profile had separate work challenge). 5586 * 5587 * @hide 5588 */ getPasswordMinimumMetrics(@serIdInt int userHandle, boolean deviceWideOnly)5589 public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle, 5590 boolean deviceWideOnly) { 5591 if (mService != null) { 5592 try { 5593 return mService.getPasswordMinimumMetrics(userHandle, deviceWideOnly); 5594 } catch (RemoteException e) { 5595 throw e.rethrowFromSystemServer(); 5596 } 5597 } 5598 return null; 5599 } 5600 5601 /** 5602 * Called by an application that is administering the device to set the length of the password 5603 * history. After setting this, the user will not be able to enter a new password that is the 5604 * same as any password in the history. Note that the current password will remain until the 5605 * user has set a new one, so the change does not take place immediately. To prompt the user for 5606 * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or 5607 * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. 5608 * <p> 5609 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5610 * password history length is always 0. 5611 * <p> 5612 * The calling device admin must have requested 5613 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has 5614 * not, a security exception will be thrown. 5615 * <p> 5616 * This method can be called on the {@link DevicePolicyManager} instance returned by 5617 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 5618 * profile. 5619 * 5620 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 5621 * @param length The new desired length of password history. A value of 0 means there is no 5622 * restriction. 5623 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin} 5624 * does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} 5625 */ 5626 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) setPasswordHistoryLength(@onNull ComponentName admin, int length)5627 public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) { 5628 if (mService != null) { 5629 try { 5630 mService.setPasswordHistoryLength(admin, length, mParentInstance); 5631 } catch (RemoteException e) { 5632 throw e.rethrowFromSystemServer(); 5633 } 5634 } 5635 } 5636 5637 /** 5638 * Called by a device admin to set the password expiration timeout. Calling this method will 5639 * restart the countdown for password expiration for the given admin, as will changing the 5640 * device password (for all admins). 5641 * <p> 5642 * The provided timeout is the time delta in ms and will be added to the current time. For 5643 * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 = 5644 * 432000000 ms for timeout. 5645 * <p> 5646 * To disable password expiration, a value of 0 may be used for timeout. 5647 * <p> 5648 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5649 * password expiration is always disabled. 5650 * <p> 5651 * A calling device admin must have requested 5652 * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has 5653 * not, a security exception will be thrown. 5654 * <p> 5655 * Note that setting the password will automatically reset the expiration time for all active 5656 * admins. Active admins do not need to explicitly call this method in that case. 5657 * <p> 5658 * This method can be called on the {@link DevicePolicyManager} instance returned by 5659 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 5660 * profile. 5661 * 5662 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 5663 * caller is not a device admin 5664 * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means 5665 * there is no restriction (unlimited). 5666 * @throws SecurityException if {@code admin} is not an active administrator or {@code admin} 5667 * does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} 5668 */ 5669 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) 5670 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true) setPasswordExpirationTimeout(@ullable ComponentName admin, long timeout)5671 public void setPasswordExpirationTimeout(@Nullable ComponentName admin, long timeout) { 5672 if (mService != null) { 5673 try { 5674 mService.setPasswordExpirationTimeout( 5675 admin, mContext.getPackageName(), timeout, mParentInstance); 5676 } catch (RemoteException e) { 5677 throw e.rethrowFromSystemServer(); 5678 } 5679 } 5680 } 5681 5682 /** 5683 * Get the password expiration timeout for the given admin. The expiration timeout is the 5684 * recurring expiration timeout provided in the call to 5685 * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the 5686 * aggregate of all participating policy administrators if {@code admin} is null. Admins that 5687 * have set restrictions on profiles that have a separate challenge are not taken into account. 5688 * 5689 * <p>This method can be called on the {@link DevicePolicyManager} instance 5690 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5691 * restrictions on the parent profile. 5692 * 5693 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5694 * password expiration is always disabled and this method always returns 0. 5695 * 5696 * @param admin The name of the admin component to check, or {@code null} to aggregate all admins. 5697 * @return The timeout for the given admin or the minimum of all timeouts 5698 */ 5699 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getPasswordExpirationTimeout(@ullable ComponentName admin)5700 public long getPasswordExpirationTimeout(@Nullable ComponentName admin) { 5701 if (mService != null) { 5702 try { 5703 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance); 5704 } catch (RemoteException e) { 5705 throw e.rethrowFromSystemServer(); 5706 } 5707 } 5708 return 0; 5709 } 5710 5711 /** 5712 * Get the current password expiration time for a particular admin or all admins that set 5713 * restrictions on this user and its participating profiles. Restrictions on profiles that have 5714 * a separate challenge are not taken into account. If admin is {@code null}, then a composite 5715 * of all expiration times is returned - which will be the minimum of all of them. 5716 * 5717 * <p>This method can be called on the {@link DevicePolicyManager} instance 5718 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5719 * the password expiration for the parent profile. 5720 * 5721 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5722 * password expiration is always disabled and this method always returns 0. 5723 * 5724 * @param admin The name of the admin component to check, or {@code null} to aggregate all admins. 5725 * @return The password expiration time, in milliseconds since epoch. 5726 */ 5727 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getPasswordExpiration(@ullable ComponentName admin)5728 public long getPasswordExpiration(@Nullable ComponentName admin) { 5729 if (mService != null) { 5730 try { 5731 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance); 5732 } catch (RemoteException e) { 5733 throw e.rethrowFromSystemServer(); 5734 } 5735 } 5736 return 0; 5737 } 5738 5739 /** 5740 * Retrieve the current password history length for a particular admin or all admins that 5741 * set restrictions on this user and its participating profiles. Restrictions on profiles that 5742 * have a separate challenge are not taken into account. 5743 * 5744 * <p>This method can be called on the {@link DevicePolicyManager} instance 5745 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5746 * restrictions on the parent profile. 5747 * 5748 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5749 * password history length is always 0. 5750 * 5751 * @param admin The name of the admin component to check, or {@code null} to aggregate 5752 * all admins. 5753 * @return The length of the password history 5754 */ 5755 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getPasswordHistoryLength(@ullable ComponentName admin)5756 public int getPasswordHistoryLength(@Nullable ComponentName admin) { 5757 return getPasswordHistoryLength(admin, myUserId()); 5758 } 5759 5760 /** @hide per-user version */ 5761 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 5762 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)5763 public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) { 5764 if (mService != null) { 5765 try { 5766 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance); 5767 } catch (RemoteException e) { 5768 throw e.rethrowFromSystemServer(); 5769 } 5770 } 5771 return 0; 5772 } 5773 5774 /** 5775 * Return the maximum password length that the device supports for a 5776 * particular password quality. 5777 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5778 * password is always empty and this method always returns 0. 5779 * @param quality The quality being interrogated. 5780 * @return Returns the maximum length that the user can enter. 5781 */ getPasswordMaximumLength(int quality)5782 public int getPasswordMaximumLength(int quality) { 5783 PackageManager pm = mContext.getPackageManager(); 5784 if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) { 5785 return 0; 5786 } 5787 return MAX_PASSWORD_LENGTH; 5788 } 5789 5790 /** 5791 * Determines whether the calling user's current password meets policy requirements 5792 * (e.g. quality, minimum length). The user must be unlocked to perform this check. 5793 * 5794 * <p>Policy requirements which affect this check can be set by admins of the user, but also 5795 * by the admin of a managed profile associated with the calling user (when the managed profile 5796 * doesn't have a separate work challenge). When a managed profile has a separate work 5797 * challenge, its policy requirements only affect the managed profile. 5798 * 5799 * <p>Depending on the user, this method checks the policy requirement against one of the 5800 * following passwords: 5801 * <ul> 5802 * <li>For the primary user or secondary users: the personal keyguard password. 5803 * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal 5804 * keyguard password. 5805 * <ul/> 5806 * In other words, it's always checking the requirement against the password that is protecting 5807 * the calling user. 5808 * 5809 * <p>Note that this method considers all policy requirements targeting the password in 5810 * question. For example a profile owner might set a requirement on the parent profile i.e. 5811 * personal keyguard but not on the profile itself. When the device has a weak personal keyguard 5812 * password and no separate work challenge, calling this method will return {@code false} 5813 * despite the profile owner not setting a policy on the profile itself. This is because the 5814 * profile's current password is the personal keyguard password, and it does not meet all policy 5815 * requirements. 5816 * 5817 * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before 5818 * calling this method. Note, this policy type is deprecated for device admins in Android 9.0 5819 * (API level 28) or higher. 5820 * 5821 * <p>This method can be called on the {@link DevicePolicyManager} instance returned by 5822 * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on 5823 * the parent profile is sufficient. 5824 * 5825 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 5826 * password is always treated as empty - i.e. this method will always return false on such 5827 * devices, provided any password requirements were set. 5828 * 5829 * @return {@code true} if the password meets the policy requirements, {@code false} otherwise 5830 * @throws SecurityException if the calling application isn't an active admin that uses 5831 * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} 5832 * @throws IllegalStateException if the user isn't unlocked 5833 */ 5834 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true) isActivePasswordSufficient()5835 public boolean isActivePasswordSufficient() { 5836 if (mService != null) { 5837 try { 5838 return mService.isActivePasswordSufficient( 5839 mContext.getPackageName(), myUserId(), mParentInstance); 5840 } catch (RemoteException e) { 5841 throw e.rethrowFromSystemServer(); 5842 } 5843 } 5844 return false; 5845 } 5846 5847 /** 5848 * Called by profile owner of a managed profile to determine whether the current device password 5849 * meets policy requirements set explicitly device-wide. 5850 * <p> This API is similar to {@link #isActivePasswordSufficient()}, with two notable 5851 * differences: 5852 * <ul> 5853 * <li>this API always targets the device password. As a result it should always be called on 5854 * the {@link #getParentProfileInstance(ComponentName)} instance.</li> 5855 * <li>password policy requirement set on the managed profile is not taken into consideration 5856 * by this API, even if the device currently does not have a separate work challenge set.</li> 5857 * </ul> 5858 * 5859 * <p>This API is designed to facilite progressive password enrollment flows when the DPC 5860 * imposes both device and profile password policies. DPC applies profile password policy by 5861 * calling {@link #setPasswordQuality(ComponentName, int)} or 5862 * {@link #setRequiredPasswordComplexity} on the regular {@link DevicePolicyManager} instance, 5863 * while it applies device-wide policy by calling {@link #setRequiredPasswordComplexity} on the 5864 * {@link #getParentProfileInstance(ComponentName)} instance. The DPC can utilize this check to 5865 * guide the user to set a device password first taking into consideration the device-wide 5866 * policy only, and then prompt the user to either upgrade it to be fully compliant, or enroll a 5867 * separate work challenge to satisfy the profile password policy only. 5868 * 5869 * <p>The device user must be unlocked (@link {@link UserManager#isUserUnlocked(UserHandle)}) 5870 * to perform this check. 5871 * 5872 * @return {@code true} if the device password meets explicit requirement set on it, 5873 * {@code false} otherwise. 5874 * @throws SecurityException if the calling application is not a profile owner of a managed 5875 * profile, or if this API is not called on the parent DevicePolicyManager instance. 5876 * @throws IllegalStateException if the user isn't unlocked 5877 * @see #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY 5878 */ isActivePasswordSufficientForDeviceRequirement()5879 public boolean isActivePasswordSufficientForDeviceRequirement() { 5880 if (!mParentInstance) { 5881 throw new SecurityException("only callable on the parent instance"); 5882 } 5883 if (mService != null) { 5884 try { 5885 return mService.isActivePasswordSufficientForDeviceRequirement(); 5886 } catch (RemoteException e) { 5887 throw e.rethrowFromSystemServer(); 5888 } 5889 } 5890 return false; 5891 } 5892 5893 /** 5894 * Returns how complex the current user's screen lock is. 5895 * 5896 * <p>Note that when called from a profile which uses an unified challenge with its parent, the 5897 * screen lock complexity of the parent will be returned. 5898 * 5899 * <p>Apps need the {@link permission#REQUEST_PASSWORD_COMPLEXITY} permission to call this 5900 * method. On Android {@link android.os.Build.VERSION_CODES#S} and above, the calling 5901 * application does not need this permission if it is a device owner or a profile owner. 5902 * 5903 * <p>This method can be called on the {@link DevicePolicyManager} instance 5904 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 5905 * restrictions on the parent profile. 5906 * 5907 * @throws IllegalStateException if the user is not unlocked. 5908 * @throws SecurityException if the calling application does not have the permission 5909 * {@link permission#REQUEST_PASSWORD_COMPLEXITY}, and is not a 5910 * device owner or a profile owner. 5911 */ 5912 @PasswordComplexity 5913 @RequiresPermission(anyOf={MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, REQUEST_PASSWORD_COMPLEXITY}, conditional = true) getPasswordComplexity()5914 public int getPasswordComplexity() { 5915 if (mService == null) { 5916 return PASSWORD_COMPLEXITY_NONE; 5917 } 5918 5919 try { 5920 return mService.getPasswordComplexity(mParentInstance); 5921 } catch (RemoteException e) { 5922 throw e.rethrowFromSystemServer(); 5923 } 5924 } 5925 5926 /** 5927 * Sets a minimum password complexity requirement for the user's screen lock. 5928 * The complexity level is one of the pre-defined levels, and the user is unable to set a 5929 * password with a lower complexity level. 5930 * 5931 * <p>Note that when called on a profile which uses an unified challenge with its parent, the 5932 * complexity would apply to the unified challenge. 5933 * 5934 * <p>This method can be called on the {@link DevicePolicyManager} instance 5935 * returned by {@link #getParentProfileInstance(ComponentName)} in order to set 5936 * restrictions on the parent profile. 5937 * 5938 * <p><strong>Note:</strong> Specifying password requirements using this method clears any 5939 * password requirements set using the obsolete {@link #setPasswordQuality(ComponentName, int)} 5940 * and any of its associated methods. 5941 * Additionally, if there are password requirements set using the obsolete 5942 * {@link #setPasswordQuality(ComponentName, int)} on the parent {@code DevicePolicyManager} 5943 * instance, they must be cleared by calling {@link #setPasswordQuality(ComponentName, int)} 5944 * with {@link #PASSWORD_QUALITY_UNSPECIFIED} on that instance prior to setting complexity 5945 * requirement for the managed profile. 5946 * 5947 * Starting from {@link Build.VERSION_CODES#VANILLA_ICE_CREAM}, after the password 5948 * requirement has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 5949 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 5950 * successfully set or not. This callback will contain: 5951 * <ul> 5952 * <li> The policy identifier {@link DevicePolicyIdentifiers#PASSWORD_COMPLEXITY_POLICY} 5953 * <li> The {@link TargetUser} that this policy relates to 5954 * <li> The {@link PolicyUpdateResult}, which will be 5955 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 5956 * reason the policy failed to be set 5957 * e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 5958 * </ul> 5959 * If there has been a change to the policy, 5960 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 5961 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 5962 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 5963 * will contain the reason why the policy changed. 5964 * 5965 * @throws SecurityException if the calling application is not a device owner or a profile 5966 * owner. 5967 * @throws IllegalArgumentException if the complexity level is not one of the four above. 5968 * @throws IllegalStateException if the caller is trying to set password complexity while there 5969 * are password requirements specified using {@link #setPasswordQuality(ComponentName, int)} 5970 * on the parent {@code DevicePolicyManager} instance. 5971 */ 5972 @SupportsCoexistence 5973 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true) setRequiredPasswordComplexity(@asswordComplexity int passwordComplexity)5974 public void setRequiredPasswordComplexity(@PasswordComplexity int passwordComplexity) { 5975 if (mService == null) { 5976 return; 5977 } 5978 5979 try { 5980 mService.setRequiredPasswordComplexity( 5981 mContext.getPackageName(), passwordComplexity, mParentInstance); 5982 } catch (RemoteException e) { 5983 throw e.rethrowFromSystemServer(); 5984 } 5985 } 5986 5987 5988 /** 5989 * Gets the password complexity requirement set by {@link #setRequiredPasswordComplexity(int)}, 5990 * for the current user. 5991 * 5992 * <p>The difference between this method and {@link #getPasswordComplexity()} is that this 5993 * method simply returns the value set by {@link #setRequiredPasswordComplexity(int)} while 5994 * {@link #getPasswordComplexity()} returns the complexity of the actual password. 5995 * 5996 * <p>This method can be called on the {@link DevicePolicyManager} instance 5997 * returned by {@link #getParentProfileInstance(ComponentName)} in order to get 5998 * restrictions on the parent profile. 5999 * 6000 * @throws SecurityException if the calling application is not a device owner or a profile 6001 * owner. 6002 */ 6003 @PasswordComplexity 6004 @SupportsCoexistence 6005 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true) getRequiredPasswordComplexity()6006 public int getRequiredPasswordComplexity() { 6007 if (mService == null) { 6008 return PASSWORD_COMPLEXITY_NONE; 6009 } 6010 6011 try { 6012 return mService.getRequiredPasswordComplexity( 6013 mContext.getPackageName(), mParentInstance); 6014 } catch (RemoteException e) { 6015 throw e.rethrowFromSystemServer(); 6016 } 6017 } 6018 6019 /** 6020 * Returns the password complexity that applies to this user, aggregated from other users if 6021 * necessary (for example, if the DPC has set password complexity requirements on the parent 6022 * profile DPM instance of a managed profile user, they would apply to the primary user on the 6023 * device). 6024 * @hide 6025 */ 6026 @PasswordComplexity getAggregatedPasswordComplexityForUser(int userId)6027 public int getAggregatedPasswordComplexityForUser(int userId) { 6028 return getAggregatedPasswordComplexityForUser(userId, false); 6029 } 6030 6031 /** 6032 * Returns the password complexity that applies to this user, aggregated from other users if 6033 * necessary (for example, if the DPC has set password complexity requirements on the parent 6034 * profile DPM instance of a managed profile user, they would apply to the primary user on the 6035 * device). If {@code deviceWideOnly} is {@code true}, ignore policies set on the 6036 * managed profile DPM instance (as if the managed profile had separate work challenge). 6037 * @hide 6038 */ 6039 @PasswordComplexity getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly)6040 public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) { 6041 if (mService == null) { 6042 return PASSWORD_COMPLEXITY_NONE; 6043 } 6044 6045 try { 6046 return mService.getAggregatedPasswordComplexityForUser(userId, deviceWideOnly); 6047 } catch (RemoteException e) { 6048 throw e.rethrowFromSystemServer(); 6049 } 6050 } 6051 6052 6053 /** 6054 * When called by a profile owner of a managed profile returns true if the profile uses unified 6055 * challenge with its parent user. 6056 * 6057 * <strong>Note</strong>: This method is not concerned with password quality and will return 6058 * false if the profile has empty password as a separate challenge. 6059 * 6060 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 6061 * @throws SecurityException if {@code admin} is not a profile owner of a managed profile. 6062 * @see UserManager#DISALLOW_UNIFIED_PASSWORD 6063 */ isUsingUnifiedPassword(@onNull ComponentName admin)6064 public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) { 6065 throwIfParentInstance("isUsingUnifiedPassword"); 6066 if (mService != null) { 6067 try { 6068 return mService.isUsingUnifiedPassword(admin); 6069 } catch (RemoteException e) { 6070 throw e.rethrowFromSystemServer(); 6071 } 6072 } 6073 return true; 6074 } 6075 6076 /** 6077 * Returns whether the given user's credential will be sufficient for all password policy 6078 * requirement, once the user's profile has switched to unified challenge. 6079 * 6080 * <p>This is different from {@link #isActivePasswordSufficient()} since once the profile 6081 * switches to unified challenge, policies set explicitly on the profile will start to affect 6082 * the parent user. 6083 * @param userHandle the user whose password requirement will be checked 6084 * @param profileUser the profile user whose lockscreen challenge will be unified. 6085 * @hide 6086 */ isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser)6087 public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) { 6088 if (mService != null) { 6089 try { 6090 return mService.isPasswordSufficientAfterProfileUnification(userHandle, 6091 profileUser); 6092 } catch (RemoteException e) { 6093 throw e.rethrowFromSystemServer(); 6094 } 6095 } 6096 return false; 6097 } 6098 /** 6099 * Retrieve the number of times the user has failed at entering a password since that last 6100 * successful password entry. 6101 * <p> 6102 * This method can be called on the {@link DevicePolicyManager} instance returned by 6103 * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed 6104 * password attemts for the parent user. 6105 * <p> 6106 * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} 6107 * to be able to call this method; if it has not, a security exception will be thrown. 6108 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 6109 * password is always empty and this method always returns 0. 6110 * 6111 * @return The number of times user has entered an incorrect password since the last correct 6112 * password entry. 6113 * @throws SecurityException if the calling application does not own an active administrator 6114 * that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} 6115 */ 6116 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) 6117 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true) getCurrentFailedPasswordAttempts()6118 public int getCurrentFailedPasswordAttempts() { 6119 return getCurrentFailedPasswordAttempts(myUserId()); 6120 } 6121 6122 /** 6123 * Retrieve the number of times the given user has failed at entering a 6124 * password since that last successful password entry. 6125 * 6126 * <p>The calling device admin must have requested 6127 * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has 6128 * not and it is not the system uid, a security exception will be thrown. 6129 * 6130 * @hide 6131 */ 6132 @UnsupportedAppUsage getCurrentFailedPasswordAttempts(int userHandle)6133 public int getCurrentFailedPasswordAttempts(int userHandle) { 6134 if (mService != null) { 6135 try { 6136 return mService.getCurrentFailedPasswordAttempts( 6137 mContext.getPackageName(), userHandle, mParentInstance); 6138 } catch (RemoteException e) { 6139 throw e.rethrowFromSystemServer(); 6140 } 6141 } 6142 return -1; 6143 } 6144 6145 /** 6146 * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set. 6147 * 6148 * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set. 6149 * @hide 6150 */ getDoNotAskCredentialsOnBoot()6151 public boolean getDoNotAskCredentialsOnBoot() { 6152 if (mService != null) { 6153 try { 6154 return mService.getDoNotAskCredentialsOnBoot(); 6155 } catch (RemoteException e) { 6156 throw e.rethrowFromSystemServer(); 6157 } 6158 } 6159 return false; 6160 } 6161 6162 /** 6163 * Setting this to a value greater than zero enables a policy that will perform a 6164 * device or profile wipe after too many incorrect device-unlock passwords have been entered. 6165 * This policy combines watching for failed passwords and wiping the device, and 6166 * requires that calling Device Admins request both 6167 * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and 6168 * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}. 6169 * <p> 6170 * When this policy is set on the system or the main user, the device will be factory reset 6171 * after too many incorrect password attempts. When set on any other user, only the 6172 * corresponding user or profile will be wiped. 6173 * <p> 6174 * To implement any other policy (e.g. wiping data for a particular application only, erasing or 6175 * revoking credentials, or reporting the failure to a server), you should implement 6176 * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not 6177 * use this API, because if the maximum count is reached, the device or profile will be wiped 6178 * immediately, and your callback will not be invoked. 6179 * <p> 6180 * This method can be called on the {@link DevicePolicyManager} instance returned by 6181 * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent 6182 * profile. This allows a profile wipe after too many incorrect device-unlock password have 6183 * been entered on the parent profile even if each profile has a separate challenge. 6184 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 6185 * password is always empty and this method has no effect - i.e. the policy is not set. 6186 * 6187 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 6188 * caller is not a device admin. 6189 * @param num The number of failed password attempts at which point the device or profile will 6190 * be wiped. 6191 * @throws SecurityException if {@code admin} is not null, and {@code admin} is not an active 6192 * administrator or does not use both 6193 * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and 6194 * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}, or if {@code admin} is null and the 6195 * caller does not have permission to wipe the device. 6196 */ 6197 @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true) 6198 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) setMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int num)6199 public void setMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int num) { 6200 if (mService != null) { 6201 try { 6202 mService.setMaximumFailedPasswordsForWipe( 6203 admin, mContext.getPackageName(), num, mParentInstance); 6204 } catch (RemoteException e) { 6205 throw e.rethrowFromSystemServer(); 6206 } 6207 } 6208 } 6209 6210 /** 6211 * Retrieve the current maximum number of login attempts that are allowed before the device 6212 * or profile is wiped, for a particular admin or all admins that set restrictions on this user 6213 * and its participating profiles. Restrictions on profiles that have a separate challenge are 6214 * not taken into account. 6215 * 6216 * <p>This method can be called on the {@link DevicePolicyManager} instance 6217 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 6218 * the value for the parent profile. 6219 * 6220 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 6221 * password is always empty and this method returns a default value (0) indicating that the 6222 * policy is not set. 6223 * 6224 * @param admin The name of the admin component to check, or {@code null} to aggregate 6225 * all admins. 6226 */ 6227 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)6228 public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) { 6229 return getMaximumFailedPasswordsForWipe(admin, myUserId()); 6230 } 6231 6232 /** @hide per-user version */ 6233 @UnsupportedAppUsage 6234 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)6235 public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) { 6236 if (mService != null) { 6237 try { 6238 return mService.getMaximumFailedPasswordsForWipe( 6239 admin, userHandle, mParentInstance); 6240 } catch (RemoteException e) { 6241 throw e.rethrowFromSystemServer(); 6242 } 6243 } 6244 return 0; 6245 } 6246 6247 /** 6248 * Returns the user that will be wiped first when too many failed attempts are made to unlock 6249 * user {@code userHandle}. That user is either the same as {@code userHandle} or belongs to the 6250 * same profile group. When there is no such policy, returns {@code UserHandle.USER_NULL}. 6251 * E.g. managed profile user may be wiped as a result of failed primary profile password 6252 * attempts when using unified challenge. Primary user may be wiped as a result of failed 6253 * password attempts on the managed profile on an organization-owned device. 6254 * @hide Used only by Keyguard 6255 */ 6256 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getProfileWithMinimumFailedPasswordsForWipe(int userHandle)6257 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) { 6258 if (mService != null) { 6259 try { 6260 return mService.getProfileWithMinimumFailedPasswordsForWipe( 6261 userHandle, mParentInstance); 6262 } catch (RemoteException e) { 6263 throw e.rethrowFromSystemServer(); 6264 } 6265 } 6266 return UserHandle.USER_NULL; 6267 } 6268 6269 /** 6270 * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins 6271 * to change the password again until the user has entered it. 6272 */ 6273 public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001; 6274 6275 /** 6276 * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user 6277 * credentials on device boot. 6278 * If the flag is set, the device can be booted without asking for user password. 6279 * The absence of this flag does not change the current boot requirements. This flag 6280 * can be set by the device owner only. If the app is not the device owner, the flag 6281 * is ignored. Once the flag is set, it cannot be reverted back without resetting the 6282 * device to factory defaults. 6283 */ 6284 public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002; 6285 6286 /** 6287 * Force a new password for device unlock (the password needed to access the entire device) or 6288 * the work profile challenge on the current user. This takes effect immediately. 6289 * 6290 * <p> Before {@link android.os.Build.VERSION_CODES#N}, this API is available to device admin, 6291 * profile owner and device owner. Starting from {@link android.os.Build.VERSION_CODES#N}, 6292 * legacy device admin (who is not also profile owner or device owner) can only call this 6293 * API to set a new password if there is currently no password set. Profile owner and device 6294 * owner can continue to force change an existing password as long as the target user is 6295 * unlocked, although device owner will not be able to call this API at all if there is also a 6296 * managed profile on the device. 6297 * 6298 * <p> Between {@link android.os.Build.VERSION_CODES#O}, 6299 * {@link android.os.Build.VERSION_CODES#P} and {@link android.os.Build.VERSION_CODES#Q}, 6300 * profile owner and devices owner targeting SDK level {@link android.os.Build.VERSION_CODES#O} 6301 * or above who attempt to call this API will receive {@link SecurityException}; they are 6302 * encouraged to migrate to the new {@link #resetPasswordWithToken} API instead. 6303 * Profile owner and device owner targeting older SDK levels are not affected: they continue 6304 * to experience the existing behaviour described in the previous paragraph. 6305 * 6306 * <p><em>Starting from {@link android.os.Build.VERSION_CODES#R}, this API is no longer 6307 * supported in most cases.</em> Device owner and profile owner calling 6308 * this API will receive {@link SecurityException} if they target SDK level 6309 * {@link android.os.Build.VERSION_CODES#O} or above, or they will receive a silent failure 6310 * (API returning {@code false}) if they target lower SDK level. 6311 * For legacy device admins, this API throws {@link SecurityException} if they target SDK level 6312 * {@link android.os.Build.VERSION_CODES#N} or above, and returns {@code false} otherwise. Only 6313 * privileged apps holding RESET_PASSWORD permission which are part of 6314 * the system factory image can still call this API to set a new password if there is currently 6315 * no password set. In this case, if the device already has a password, this API will throw 6316 * {@link SecurityException}. 6317 * 6318 * <p> 6319 * The given password must be sufficient for the current password quality and length constraints 6320 * as returned by {@link #getPasswordQuality(ComponentName)} and 6321 * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then 6322 * it will be rejected and false returned. Note that the password may be a stronger quality 6323 * (containing alphanumeric characters when the requested quality is only numeric), in which 6324 * case the currently active quality will be increased to match. 6325 * 6326 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this 6327 * methods does nothing. 6328 * <p> 6329 * The calling device admin must have requested 6330 * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has 6331 * not, a security exception will be thrown. 6332 * 6333 * @param password The new password for the user. Null or empty clears the password. 6334 * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and 6335 * {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}. 6336 * @return Returns true if the password was applied, or false if it is not acceptable for the 6337 * current constraints. 6338 * @throws SecurityException if the calling application does not own an active administrator 6339 * that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} 6340 * @throws IllegalStateException if the calling user is locked or has a managed profile. 6341 * @deprecated Please use {@link #resetPasswordWithToken} instead. 6342 */ 6343 @Deprecated 6344 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) resetPassword(String password, int flags)6345 public boolean resetPassword(String password, int flags) { 6346 throwIfParentInstance("resetPassword"); 6347 if (mService != null) { 6348 try { 6349 return mService.resetPassword(password, flags); 6350 } catch (RemoteException e) { 6351 throw e.rethrowFromSystemServer(); 6352 } 6353 } 6354 return false; 6355 } 6356 6357 /** 6358 * Called by a profile or device owner to provision a token which can later be used to reset the 6359 * device lockscreen password (if called by device owner), or managed profile challenge (if 6360 * called by profile owner), via {@link #resetPasswordWithToken}. 6361 * <p> 6362 * If the user currently has a lockscreen password, the provisioned token will not be 6363 * immediately usable; it only becomes active after the user performs a confirm credential 6364 * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}. 6365 * If the user has no lockscreen password, the token is activated immediately. In all cases, 6366 * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}. 6367 * For security reasons, un-activated tokens are only stored in memory and will be lost once 6368 * the device reboots. In this case a new token needs to be provisioned again. 6369 * <p> 6370 * Once provisioned and activated, the token will remain effective even if the user changes 6371 * or clears the lockscreen password. 6372 * <p> 6373 * <em>This token is highly sensitive and should be treated at the same level as user 6374 * credentials. In particular, NEVER store this token on device in plaintext. Do not store 6375 * the plaintext token in device-encrypted storage if it will be needed to reset password on 6376 * file-based encryption devices before user unlocks. Consider carefully how any password token 6377 * will be stored on your server and who will need access to them. Tokens may be the subject of 6378 * legal access requests. 6379 * </em> 6380 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the 6381 * reset token is not set and this method returns false. 6382 * 6383 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 6384 * caller is not a device admin. 6385 * @param token a secure token a least 32-byte long, which must be generated by a 6386 * cryptographically strong random number generator. 6387 * @return true if the operation is successful, false otherwise. 6388 * @throws SecurityException if admin is not a device or profile owner. 6389 * @throws IllegalArgumentException if the supplied token is invalid. 6390 */ 6391 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) 6392 @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true) setResetPasswordToken(@ullable ComponentName admin, byte[] token)6393 public boolean setResetPasswordToken(@Nullable ComponentName admin, byte[] token) { 6394 throwIfParentInstance("setResetPasswordToken"); 6395 if (mService != null) { 6396 try { 6397 return mService.setResetPasswordToken(admin, mContext.getPackageName(), token); 6398 } catch (RemoteException e) { 6399 throw e.rethrowFromSystemServer(); 6400 } 6401 } 6402 return false; 6403 } 6404 6405 /** 6406 * Called by a profile, device owner or holder of the permission 6407 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD} 6408 * to revoke the current password reset token. 6409 * 6410 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this 6411 * method has no effect - the reset token should not have been set in the first place - and 6412 * false is returned. 6413 * 6414 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 6415 * caller is not a device admin. 6416 * @return true if the operation is successful, false otherwise. 6417 * @throws SecurityException if admin is not a device or profile owner and if the caller does 6418 * not the permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD}. 6419 */ 6420 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) 6421 @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true) clearResetPasswordToken(@ullable ComponentName admin)6422 public boolean clearResetPasswordToken(@Nullable ComponentName admin) { 6423 throwIfParentInstance("clearResetPasswordToken"); 6424 if (mService != null) { 6425 try { 6426 return mService.clearResetPasswordToken(admin, mContext.getPackageName()); 6427 } catch (RemoteException e) { 6428 throw e.rethrowFromSystemServer(); 6429 } 6430 } 6431 return false; 6432 } 6433 6434 /** 6435 * Called by a profile, device owner or a holder of the permission 6436 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD} 6437 * to check if the current reset password token is active. 6438 * 6439 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, 6440 * false is always returned. 6441 * 6442 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 6443 * caller is not a device admin. 6444 * @return true if the token is active, false otherwise. 6445 * @throws SecurityException if admin is not a device or profile owner and not a holder of the 6446 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD} 6447 * @throws IllegalStateException if no token has been set. 6448 */ 6449 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) 6450 @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true) isResetPasswordTokenActive(@ullable ComponentName admin)6451 public boolean isResetPasswordTokenActive(@Nullable ComponentName admin) { 6452 throwIfParentInstance("isResetPasswordTokenActive"); 6453 if (mService != null) { 6454 try { 6455 return mService.isResetPasswordTokenActive(admin, mContext.getPackageName()); 6456 } catch (RemoteException e) { 6457 throw e.rethrowFromSystemServer(); 6458 } 6459 } 6460 return false; 6461 } 6462 6463 /** 6464 * Called by device or profile owner to force set a new device unlock password or a managed 6465 * profile challenge on current user. This takes effect immediately. 6466 * <p> 6467 * Unlike {@link #resetPassword}, this API can change the password even before the user or 6468 * device is unlocked or decrypted. The supplied token must have been previously provisioned via 6469 * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}. 6470 * <p> 6471 * The given password must be sufficient for the current password quality and length constraints 6472 * as returned by {@link #getPasswordQuality(ComponentName)} and 6473 * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then 6474 * it will be rejected and false returned. Note that the password may be a stronger quality, for 6475 * example, a password containing alphanumeric characters when the requested quality is only 6476 * numeric. 6477 * <p> 6478 * Calling with a {@code null} or empty password will clear any existing PIN, pattern or 6479 * password if the current password constraints allow it. 6480 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, 6481 * calling this methods has no effect - the password is always empty - and false is returned. 6482 * 6483 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 6484 * caller is not a device admin. 6485 * @param password The new password for the user. {@code null} or empty clears the password. 6486 * @param token the password reset token previously provisioned by 6487 * {@link #setResetPasswordToken}. 6488 * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and 6489 * {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}. 6490 * @return Returns true if the password was applied, or false if it is not acceptable for the 6491 * current constraints. 6492 * @throws SecurityException if admin is not a device or profile owner. 6493 * @throws IllegalStateException if the provided token is not valid. 6494 */ 6495 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) 6496 @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true) resetPasswordWithToken(@ullable ComponentName admin, String password, byte[] token, int flags)6497 public boolean resetPasswordWithToken(@Nullable ComponentName admin, String password, 6498 byte[] token, int flags) { 6499 throwIfParentInstance("resetPassword"); 6500 if (mService != null) { 6501 try { 6502 return mService.resetPasswordWithToken(admin, mContext.getPackageName(), password, 6503 token, flags); 6504 } catch (RemoteException e) { 6505 throw e.rethrowFromSystemServer(); 6506 } 6507 } 6508 return false; 6509 } 6510 6511 /** 6512 * Called by an application that is administering the device to set the maximum time for user 6513 * activity until the device will lock. This limits the length that the user can set. It takes 6514 * effect immediately. 6515 * <p> 6516 * A calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} 6517 * to be able to call this method; if it has not, a security exception will be thrown. 6518 * <p> 6519 * This method can be called on the {@link DevicePolicyManager} instance returned by 6520 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 6521 * profile. 6522 * 6523 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 6524 * caller is not a device admin 6525 * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there 6526 * is no restriction. 6527 * @throws SecurityException if {@code admin} is not an active administrator or it does not use 6528 * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} 6529 */ 6530 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK, conditional = true) setMaximumTimeToLock(@ullable ComponentName admin, long timeMs)6531 public void setMaximumTimeToLock(@Nullable ComponentName admin, long timeMs) { 6532 if (mService != null) { 6533 try { 6534 mService.setMaximumTimeToLock(admin, mContext.getPackageName(), timeMs, mParentInstance); 6535 } catch (RemoteException e) { 6536 throw e.rethrowFromSystemServer(); 6537 } 6538 } 6539 } 6540 6541 /** 6542 * Retrieve the current maximum time to unlock for a particular admin or all admins that set 6543 * restrictions on this user and its participating profiles. Restrictions on profiles that have 6544 * a separate challenge are not taken into account. 6545 * 6546 * <p>This method can be called on the {@link DevicePolicyManager} instance 6547 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 6548 * restrictions on the parent profile. 6549 * 6550 * @param admin The name of the admin component to check, or {@code null} to aggregate 6551 * all admins. 6552 * @return time in milliseconds for the given admin or the minimum value (strictest) of 6553 * all admins if admin is null. Returns 0 if there are no restrictions. 6554 */ getMaximumTimeToLock(@ullable ComponentName admin)6555 public long getMaximumTimeToLock(@Nullable ComponentName admin) { 6556 return getMaximumTimeToLock(admin, myUserId()); 6557 } 6558 6559 /** @hide per-user version */ 6560 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)6561 public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) { 6562 if (mService != null) { 6563 try { 6564 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance); 6565 } catch (RemoteException e) { 6566 throw e.rethrowFromSystemServer(); 6567 } 6568 } 6569 return 0; 6570 } 6571 6572 /** 6573 * Called by a device/profile owner to set the timeout after which unlocking with secondary, non 6574 * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a 6575 * strong authentication method like password, pin or pattern. 6576 * 6577 * <p>This timeout is used internally to reset the timer to require strong auth again after 6578 * specified timeout each time it has been successfully used. 6579 * 6580 * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}. 6581 * 6582 * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. 6583 * 6584 * <p>A calling device admin can verify the value it has set by calling 6585 * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance. 6586 * 6587 * <p>This method can be called on the {@link DevicePolicyManager} instance returned by 6588 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 6589 * profile. 6590 * 6591 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, 6592 * calling this methods has no effect - i.e. the timeout is not set. 6593 * 6594 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 6595 * caller is not a device admin 6596 * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock 6597 * with strong authentication method. A value of 0 means the admin is not participating 6598 * in controlling the timeout. 6599 * The minimum and maximum timeouts are platform-defined and are typically 1 hour and 6600 * 72 hours, respectively. Though discouraged, the admin may choose to require strong 6601 * auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or 6602 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. 6603 * 6604 * @throws SecurityException if {@code admin} is not a device or profile owner. 6605 */ 6606 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) 6607 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true) setRequiredStrongAuthTimeout(@ullable ComponentName admin, long timeoutMs)6608 public void setRequiredStrongAuthTimeout(@Nullable ComponentName admin, 6609 long timeoutMs) { 6610 if (mService != null) { 6611 try { 6612 mService.setRequiredStrongAuthTimeout( 6613 admin, mContext.getPackageName(), timeoutMs, mParentInstance); 6614 } catch (RemoteException e) { 6615 throw e.rethrowFromSystemServer(); 6616 } 6617 } 6618 } 6619 6620 /** 6621 * Determine for how long the user will be able to use secondary, non strong auth for 6622 * authentication, since last strong method authentication (password, pin or pattern) was used. 6623 * After the returned timeout the user is required to use strong authentication method. 6624 * 6625 * <p>This method can be called on the {@link DevicePolicyManager} instance 6626 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 6627 * restrictions on the parent profile. 6628 * 6629 * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, 6630 * 0 is returned to indicate that no timeout is configured. 6631 * 6632 * @param admin The name of the admin component to check, or {@code null} to aggregate 6633 * across all participating admins. 6634 * @return The timeout in milliseconds or 0 if not configured for the provided admin. 6635 */ 6636 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getRequiredStrongAuthTimeout(@ullable ComponentName admin)6637 public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) { 6638 return getRequiredStrongAuthTimeout(admin, myUserId()); 6639 } 6640 6641 /** @hide per-user version */ 6642 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 6643 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)6644 public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) { 6645 if (mService != null) { 6646 try { 6647 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance); 6648 } catch (RemoteException e) { 6649 throw e.rethrowFromSystemServer(); 6650 } 6651 } 6652 return DEFAULT_STRONG_AUTH_TIMEOUT_MS; 6653 } 6654 6655 /** 6656 * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the 6657 * keyring. The user's credential will need to be entered again in order to derive the 6658 * credential encryption key that will be stored back in the keyring for future use. 6659 * <p> 6660 * This flag can only be used by a profile owner when locking a managed profile when 6661 * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}. 6662 * <p> 6663 * In order to secure user data, the user will be stopped and restarted so apps should wait 6664 * until they are next run to perform further actions. 6665 */ 6666 public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1; 6667 6668 /** @hide */ 6669 @Retention(RetentionPolicy.SOURCE) 6670 @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = { 6671 FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY 6672 }) 6673 public @interface LockNowFlag {} 6674 6675 /** 6676 * Make the device lock immediately, as if the lock screen timeout has expired at the point of 6677 * this call. 6678 * <p> 6679 * This method secures the device in response to an urgent situation, such as a lost or stolen 6680 * device. After this method is called, the device must be unlocked using strong authentication 6681 * (PIN, pattern, or password). This API is intended for use only by device admins. 6682 * <p> 6683 * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have 6684 * the LOCK_DEVICE permission or the device must have the 6685 * device admin feature; if neither is true, then the method will return without completing 6686 * any action. Before version {@link android.os.Build.VERSION_CODES#R}, 6687 * the device needed the device admin feature, regardless of the caller's permissions. 6688 * <p> 6689 * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} 6690 * to be able to call this method; if it has not, a security exception will be thrown. 6691 * <p> 6692 * If there's no lock type set, this method forces the device to go to sleep but doesn't lock 6693 * the device. Device admins who find the device in this state can lock an otherwise-insecure 6694 * device by first calling {@link #resetPassword} to set the password and then lock the device. 6695 * <p> 6696 * This method can be called on the {@link DevicePolicyManager} instance returned by 6697 * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile. 6698 * <p> 6699 * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this 6700 * method doesn't turn off the screen as it would be a driving safety distraction. 6701 * <p> 6702 * Equivalent to calling {@link #lockNow(int)} with no flags. 6703 * 6704 * @throws SecurityException if the calling application does not own an active administrator 6705 * that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} 6706 */ 6707 @SuppressLint("RequiresPermission") 6708 @RequiresPermission(value = LOCK_DEVICE, conditional = true) lockNow()6709 public void lockNow() { 6710 lockNow(0); 6711 } 6712 6713 /** 6714 * Make the device lock immediately, as if the lock screen timeout has expired at the point of 6715 * this call. 6716 * <p> 6717 * This method secures the device in response to an urgent situation, such as a lost or stolen 6718 * device. After this method is called, the device must be unlocked using strong authentication 6719 * (PIN, pattern, or password). This API is intended for use only by device admins. 6720 * <p> 6721 * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have 6722 * the LOCK_DEVICE permission or the device must have the 6723 * device admin feature; if neither is true, then the method will return without completing any 6724 * action. Before version {@link android.os.Build.VERSION_CODES#R}, the device needed the device 6725 * admin feature, regardless of the caller's permissions. 6726 * <p> 6727 * A calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} 6728 * to be able to call this method; if it has not, a security exception will be thrown. 6729 * <p> 6730 * If there's no lock type set, this method forces the device to go to sleep but doesn't lock 6731 * the device. Device admins who find the device in this state can lock an otherwise-insecure 6732 * device by first calling {@link #resetPassword} to set the password and then lock the device. 6733 * <p> 6734 * This method can be called on the {@link DevicePolicyManager} instance returned by 6735 * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile as 6736 * well as the managed profile. 6737 * <p> 6738 * NOTE: In order to lock the parent profile and evict the encryption key of the managed 6739 * profile, {@link #lockNow()} must be called twice: First, {@link #lockNow()} should be called 6740 * on the {@link DevicePolicyManager} instance returned by 6741 * {@link #getParentProfileInstance(ComponentName)}, then {@link #lockNow(int)} should be 6742 * called on the {@link DevicePolicyManager} instance associated with the managed profile, 6743 * with the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag. 6744 * Calling the method twice in this order ensures that all users are locked and does not 6745 * stop the device admin on the managed profile from issuing a second call to lock its own 6746 * profile. 6747 * <p> 6748 * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this 6749 * method doesn't turn off the screen as it would be a driving safety distraction. 6750 * 6751 * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}. 6752 * @throws SecurityException if the calling application does not own an active administrator 6753 * that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} and the does not hold 6754 * the LOCK_DEVICE permission, or 6755 * the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an 6756 * application that is not a profile owner of a managed profile. 6757 * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is 6758 * passed when locking the parent profile. 6759 * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} 6760 * flag is passed when {@link #getStorageEncryptionStatus} does not return 6761 * {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}. 6762 */ 6763 @RequiresPermission(value = LOCK_DEVICE, conditional = true) lockNow(@ockNowFlag int flags)6764 public void lockNow(@LockNowFlag int flags) { 6765 if (mService != null) { 6766 try { 6767 mService.lockNow(flags, mContext.getPackageName(), mParentInstance); 6768 } catch (RemoteException e) { 6769 throw e.rethrowFromSystemServer(); 6770 } 6771 } 6772 } 6773 6774 /** 6775 * Flag for {@link #wipeData(int)}: also erase the device's adopted external storage (such as 6776 * adopted SD cards). 6777 * @see <a href="{@docRoot}about/versions/marshmallow/android-6.0.html#adoptable-storage"> 6778 * Adoptable Storage Devices</a> 6779 */ 6780 public static final int WIPE_EXTERNAL_STORAGE = 0x0001; 6781 6782 /** 6783 * Flag for {@link #wipeData(int)}: also erase the factory reset protection 6784 * data. 6785 * 6786 * <p>This flag may only be set by device owner admins; if it is set by 6787 * other admins a {@link SecurityException} will be thrown. 6788 */ 6789 public static final int WIPE_RESET_PROTECTION_DATA = 0x0002; 6790 6791 /** 6792 * Flag for {@link #wipeData(int)}: also erase the device's eUICC data. 6793 */ 6794 public static final int WIPE_EUICC = 0x0004; 6795 6796 /** 6797 * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user. 6798 */ 6799 public static final int WIPE_SILENTLY = 0x0008; 6800 6801 /** 6802 * See {@link #wipeData(int, CharSequence)} 6803 * 6804 * @param flags Bit mask of additional options: currently supported flags are 6805 * {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA}, 6806 * {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}. 6807 * @throws SecurityException if the calling application does not own an active 6808 * administrator 6809 * that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} and is 6810 * not granted the 6811 * {@link android.Manifest.permission#MASTER_CLEAR} or 6812 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_WIPE_DATA} 6813 * permissions. 6814 * @throws IllegalStateException if called on last full-user or system-user 6815 * @see #wipeDevice(int) 6816 * @see #wipeData(int, CharSequence) 6817 */ 6818 @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true) wipeData(int flags)6819 public void wipeData(int flags) { 6820 wipeDataInternal(flags, 6821 /* wipeReasonForUser= */ "", 6822 /* factoryReset= */ false); 6823 } 6824 6825 /** 6826 * Ask that all user data be wiped. 6827 * 6828 * <p> 6829 * If called as a secondary user or managed profile, the user itself and its associated user 6830 * data will be wiped. In particular, If the caller is a profile owner of an 6831 * organization-owned managed profile, calling this method will relinquish the device for 6832 * personal use, removing the managed profile and all policies set by the profile owner. 6833 * </p> 6834 * 6835 * <p> Calling this method from the primary user will only work if the calling app is 6836 * targeting SDK level {@link Build.VERSION_CODES#TIRAMISU} or below, in which case it will 6837 * cause the device to reboot, erasing all device data - including all the secondary users 6838 * and their data - while booting up. If an app targeting SDK level 6839 * {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE} and above is calling this method from the 6840 * primary user or last full user, {@link IllegalStateException} will be thrown. </p> 6841 * 6842 * If an app wants to wipe the entire device irrespective of which user they are from, they 6843 * should use {@link #wipeDevice} instead. 6844 * 6845 * @param flags Bit mask of additional options: currently supported flags are 6846 * {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and 6847 * {@link #WIPE_EUICC}. 6848 * @param reason a string that contains the reason for wiping data, which can be 6849 * presented to the user. 6850 * @throws SecurityException if the calling application does not own an active administrator 6851 * that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} and is not granted the 6852 * {@link android.Manifest.permission#MASTER_CLEAR} or 6853 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_WIPE_DATA} permissions. 6854 * @throws IllegalArgumentException if the input reason string is null or empty, or if 6855 * {@link #WIPE_SILENTLY} is set. 6856 * @throws IllegalStateException if called on last full-user or system-user 6857 * @see #wipeDevice(int) 6858 * @see #wipeData(int) 6859 */ 6860 @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true) wipeData(int flags, @NonNull CharSequence reason)6861 public void wipeData(int flags, @NonNull CharSequence reason) { 6862 Objects.requireNonNull(reason, "reason string is null"); 6863 Preconditions.checkStringNotEmpty(reason, "reason string is empty"); 6864 Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set"); 6865 wipeDataInternal(flags, reason.toString(), /* factoryReset= */ false); 6866 } 6867 6868 /** 6869 * Ask that the device be wiped and factory reset. 6870 * 6871 * <p> 6872 * The calling Device Owner or Organization Owned Profile Owner must have requested 6873 * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to be able to call this method; if it has 6874 * not, a security exception will be thrown. 6875 * 6876 * @param flags Bit mask of additional options: currently supported flags are 6877 * {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA}, 6878 * {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}. 6879 * @throws SecurityException if the calling application does not own an active administrator 6880 * that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} and is not 6881 * granted the {@link android.Manifest.permission#MASTER_CLEAR} 6882 * or both the 6883 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_WIPE_DATA} and 6884 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_ACROSS_USERS} 6885 * permissions. 6886 * @see #wipeData(int) 6887 * @see #wipeData(int, CharSequence) 6888 */ 6889 // TODO(b/255323293) Add host-side tests 6890 @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true) wipeDevice(int flags)6891 public void wipeDevice(int flags) { 6892 wipeDataInternal(flags, 6893 /* wipeReasonForUser= */ "", 6894 /* factoryReset= */ true); 6895 } 6896 6897 /** 6898 * Internal function for {@link #wipeData(int)}, {@link #wipeData(int, CharSequence)} 6899 * and {@link #wipeDevice(int)} to call. 6900 * 6901 * @hide 6902 * @see #wipeData(int) 6903 * @see #wipeData(int, CharSequence) 6904 * @see #wipeDevice(int) 6905 */ wipeDataInternal(int flags, @NonNull String wipeReasonForUser, boolean factoryReset)6906 private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser, 6907 boolean factoryReset) { 6908 if (mService != null) { 6909 try { 6910 mService.wipeDataWithReason(mContext.getPackageName(), flags, wipeReasonForUser, 6911 mParentInstance, factoryReset); 6912 } catch (RemoteException e) { 6913 throw e.rethrowFromSystemServer(); 6914 } 6915 } 6916 } 6917 6918 /** 6919 * Callable by device owner or profile owner of an organization-owned device, to set a 6920 * factory reset protection (FRP) policy. When a new policy is set, the system 6921 * notifies the FRP management agent of a policy change by broadcasting 6922 * {@code ACTION_RESET_PROTECTION_POLICY_CHANGED}. 6923 * 6924 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 6925 * caller is not a device admin 6926 * @param policy the new FRP policy, or {@code null} to clear the current policy. 6927 * @throws SecurityException if {@code admin} is not a device owner or a profile owner of 6928 * an organization-owned device. 6929 * @throws UnsupportedOperationException if factory reset protection is not 6930 * supported on the device. 6931 */ 6932 @RequiresPermission(value = MANAGE_DEVICE_POLICY_FACTORY_RESET, conditional = true) setFactoryResetProtectionPolicy(@ullable ComponentName admin, @Nullable FactoryResetProtectionPolicy policy)6933 public void setFactoryResetProtectionPolicy(@Nullable ComponentName admin, 6934 @Nullable FactoryResetProtectionPolicy policy) { 6935 throwIfParentInstance("setFactoryResetProtectionPolicy"); 6936 if (mService != null) { 6937 try { 6938 mService.setFactoryResetProtectionPolicy(admin, mContext.getPackageName(), policy); 6939 } catch (RemoteException e) { 6940 throw e.rethrowFromSystemServer(); 6941 } 6942 } 6943 } 6944 6945 /** 6946 * Callable by device owner or profile owner of an organization-owned device, to retrieve 6947 * the current factory reset protection (FRP) policy set previously by 6948 * {@link #setFactoryResetProtectionPolicy}. 6949 * <p> 6950 * This method can also be called by the FRP management agent on device or with the permission 6951 * {@link android.Manifest.permission#MASTER_CLEAR}, in which case, it can pass {@code null} 6952 * as the ComponentName. 6953 * 6954 * @param admin Which {@link DeviceAdminReceiver} this request is associated with or 6955 * {@code null} if the caller is not a device admin 6956 * @return The current FRP policy object or {@code null} if no policy is set. 6957 * @throws SecurityException if {@code admin} is not a device owner, a profile owner of 6958 * an organization-owned device or the FRP management agent. 6959 * @throws UnsupportedOperationException if factory reset protection is not 6960 * supported on the device. 6961 */ 6962 @RequiresPermission(value = MANAGE_DEVICE_POLICY_FACTORY_RESET, conditional = true) getFactoryResetProtectionPolicy( @ullable ComponentName admin)6963 public @Nullable FactoryResetProtectionPolicy getFactoryResetProtectionPolicy( 6964 @Nullable ComponentName admin) { 6965 throwIfParentInstance("getFactoryResetProtectionPolicy"); 6966 if (mService != null) { 6967 try { 6968 return mService.getFactoryResetProtectionPolicy(admin); 6969 } catch (RemoteException e) { 6970 throw e.rethrowFromSystemServer(); 6971 } 6972 } 6973 return null; 6974 } 6975 6976 /** 6977 * Send a lost mode location update to the admin. This API is limited to organization-owned 6978 * devices, which includes devices with a device owner or devices with a profile owner on an 6979 * organization-owned managed profile. 6980 * 6981 * <p>The caller must hold the 6982 * {@link android.Manifest.permission#TRIGGER_LOST_MODE} permission. 6983 * 6984 * <p>This API accesses the device's location and will only be used when a device is lost. 6985 * 6986 * <p>Register a broadcast receiver to receive lost mode location updates. This receiver should 6987 * subscribe to the {@link #ACTION_LOST_MODE_LOCATION_UPDATE} action and receive the location 6988 * from an intent extra {@link #EXTRA_LOST_MODE_LOCATION}. 6989 * 6990 * <p> Not for use by third-party applications. 6991 * 6992 * @param executor The executor through which the callback should be invoked. 6993 * @param callback A callback object that will inform the caller whether a lost mode location 6994 * update was successfully sent 6995 * @hide 6996 */ 6997 @SystemApi 6998 @RequiresPermission(android.Manifest.permission.TRIGGER_LOST_MODE) sendLostModeLocationUpdate(@onNull @allbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)6999 public void sendLostModeLocationUpdate(@NonNull @CallbackExecutor Executor executor, 7000 @NonNull Consumer<Boolean> callback) { 7001 throwIfParentInstance("sendLostModeLocationUpdate"); 7002 if (mService == null) { 7003 executeCallback(AndroidFuture.completedFuture(false), executor, callback); 7004 return; 7005 } 7006 try { 7007 final AndroidFuture<Boolean> future = new AndroidFuture<>(); 7008 mService.sendLostModeLocationUpdate(future); 7009 executeCallback(future, executor, callback); 7010 } catch (RemoteException e) { 7011 throw e.rethrowFromSystemServer(); 7012 } 7013 } 7014 executeCallback(AndroidFuture<Boolean> future, @CallbackExecutor @NonNull Executor executor, Consumer<Boolean> callback)7015 private void executeCallback(AndroidFuture<Boolean> future, 7016 @CallbackExecutor @NonNull Executor executor, 7017 Consumer<Boolean> callback) { 7018 future.whenComplete((result, error) -> executor.execute(() -> { 7019 final long token = Binder.clearCallingIdentity(); 7020 try { 7021 if (error != null) { 7022 callback.accept(false); 7023 } else { 7024 callback.accept(result); 7025 } 7026 } finally { 7027 Binder.restoreCallingIdentity(token); 7028 } 7029 })); 7030 } 7031 7032 /** 7033 * Called by an application that is administering the device to set the 7034 * global proxy and exclusion list. 7035 * <p> 7036 * The calling device admin must have requested 7037 * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call 7038 * this method; if it has not, a security exception will be thrown. 7039 * Only the first device admin can set the proxy. If a second admin attempts 7040 * to set the proxy, the {@link ComponentName} of the admin originally setting the 7041 * proxy will be returned. If successful in setting the proxy, {@code null} will 7042 * be returned. 7043 * The method can be called repeatedly by the device admin alrady setting the 7044 * proxy to update the proxy and exclusion list. 7045 * 7046 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 7047 * @param proxySpec the global proxy desired. Must be an HTTP Proxy. 7048 * Pass Proxy.NO_PROXY to reset the proxy. 7049 * @param exclusionList a list of domains to be excluded from the global proxy. 7050 * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName} 7051 * of the device admin that sets the proxy. 7052 * @hide 7053 */ 7054 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )7055 public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec, 7056 List<String> exclusionList ) { 7057 throwIfParentInstance("setGlobalProxy"); 7058 if (proxySpec == null) { 7059 throw new NullPointerException(); 7060 } 7061 if (mService != null) { 7062 try { 7063 String hostSpec; 7064 String exclSpec; 7065 if (proxySpec.equals(Proxy.NO_PROXY)) { 7066 hostSpec = null; 7067 exclSpec = null; 7068 } else { 7069 if (!proxySpec.type().equals(Proxy.Type.HTTP)) { 7070 throw new IllegalArgumentException(); 7071 } 7072 final Pair<String, String> proxyParams = 7073 getProxyParameters(proxySpec, exclusionList); 7074 hostSpec = proxyParams.first; 7075 exclSpec = proxyParams.second; 7076 } 7077 return mService.setGlobalProxy(admin, hostSpec, exclSpec); 7078 } catch (RemoteException e) { 7079 throw e.rethrowFromSystemServer(); 7080 } 7081 } 7082 return null; 7083 } 7084 7085 /** 7086 * Build HTTP proxy parameters for {@link IDevicePolicyManager#setGlobalProxy}. 7087 * @throws IllegalArgumentException Invalid proxySpec 7088 * @hide 7089 */ 7090 @VisibleForTesting getProxyParameters(Proxy proxySpec, List<String> exclusionList)7091 public Pair<String, String> getProxyParameters(Proxy proxySpec, List<String> exclusionList) { 7092 InetSocketAddress sa = (InetSocketAddress) proxySpec.address(); 7093 String hostName = sa.getHostName(); 7094 int port = sa.getPort(); 7095 final List<String> trimmedExclList; 7096 if (exclusionList == null) { 7097 trimmedExclList = Collections.emptyList(); 7098 } else { 7099 trimmedExclList = new ArrayList<>(exclusionList.size()); 7100 for (String exclDomain : exclusionList) { 7101 trimmedExclList.add(exclDomain.trim()); 7102 } 7103 } 7104 final ProxyInfo info = ProxyInfo.buildDirectProxy(hostName, port, trimmedExclList); 7105 // The hostSpec is built assuming that there is a specified port and hostname, 7106 // but ProxyInfo.isValid() accepts 0 / empty as unspecified: also reject them. 7107 if (port == 0 || TextUtils.isEmpty(hostName) || !info.isValid()) { 7108 throw new IllegalArgumentException(); 7109 } 7110 7111 return new Pair<>(hostName + ":" + port, TextUtils.join(",", trimmedExclList)); 7112 } 7113 7114 /** 7115 * Set a network-independent global HTTP proxy. This is not normally what you want for typical 7116 * HTTP proxies - they are generally network dependent. However if you're doing something 7117 * unusual like general internal filtering this may be useful. On a private network where the 7118 * proxy is not accessible, you may break HTTP using this. 7119 * <p> 7120 * This method requires the caller to be the device owner. 7121 * <p> 7122 * This proxy is only a recommendation and it is possible that some apps will ignore it. 7123 * <p> 7124 * Note: The device owner won't be able to set a global HTTP proxy if there are unaffiliated 7125 * secondary users or profiles on the device. It's recommended that affiliation ids are set for 7126 * new users as soon as possible after provisioning via {@link #setAffiliationIds}. 7127 * 7128 * @see ProxyInfo 7129 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 7130 * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A 7131 * {@code null} value will clear the global HTTP proxy. 7132 * @throws SecurityException if {@code admin} is not the device owner. 7133 */ setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)7134 public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo 7135 proxyInfo) { 7136 throwIfParentInstance("setRecommendedGlobalProxy"); 7137 if (mService != null) { 7138 try { 7139 mService.setRecommendedGlobalProxy(admin, proxyInfo); 7140 } catch (RemoteException e) { 7141 throw e.rethrowFromSystemServer(); 7142 } 7143 } 7144 } 7145 7146 /** 7147 * Returns the component name setting the global proxy. 7148 * @return ComponentName object of the device admin that set the global proxy, or {@code null} 7149 * if no admin has set the proxy. 7150 * @hide 7151 */ getGlobalProxyAdmin()7152 public @Nullable ComponentName getGlobalProxyAdmin() { 7153 if (mService != null) { 7154 try { 7155 return mService.getGlobalProxyAdmin(myUserId()); 7156 } catch (RemoteException e) { 7157 throw e.rethrowFromSystemServer(); 7158 } 7159 } 7160 return null; 7161 } 7162 7163 /** 7164 * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}: 7165 * indicating that encryption is not supported. 7166 */ 7167 public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0; 7168 7169 /** 7170 * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}: 7171 * indicating that encryption is supported, but is not currently active. 7172 * <p> 7173 * {@link #getStorageEncryptionStatus} can only return this value on devices that use Full Disk 7174 * Encryption. Support for Full Disk Encryption was entirely removed in API level 33, having 7175 * been replaced by File Based Encryption. Devices that use File Based Encryption always 7176 * automatically activate their encryption on first boot. 7177 * <p> 7178 * {@link #setStorageEncryption} can still return this value for an unrelated reason, but {@link 7179 * #setStorageEncryption} is deprecated since it doesn't do anything useful. 7180 */ 7181 public static final int ENCRYPTION_STATUS_INACTIVE = 1; 7182 7183 /** 7184 * Result code for {@link #getStorageEncryptionStatus}: indicating that encryption is not 7185 * currently active, but is currently being activated. 7186 * <p> 7187 * @deprecated This result code has never actually been used, so there is no reason for apps to 7188 * check for it. 7189 */ 7190 @Deprecated 7191 public static final int ENCRYPTION_STATUS_ACTIVATING = 2; 7192 7193 /** 7194 * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}: 7195 * indicating that encryption is active. 7196 * <p> 7197 * {@link #getStorageEncryptionStatus} can only return this value for apps targeting API level 7198 * 23 or lower, or on devices that use Full Disk Encryption. Support for Full Disk Encryption 7199 * was entirely removed in API level 33, having been replaced by File Based Encryption. The 7200 * result code {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER} is used on devices that use File Based 7201 * Encryption, except when the app targets API level 23 or lower. 7202 * <p> 7203 * {@link #setStorageEncryption} can still return this value for an unrelated reason, but {@link 7204 * #setStorageEncryption} is deprecated since it doesn't do anything useful. 7205 */ 7206 public static final int ENCRYPTION_STATUS_ACTIVE = 3; 7207 7208 /** 7209 * Result code for {@link #getStorageEncryptionStatus}: indicating that encryption is active, 7210 * but the encryption key is not cryptographically protected by the user's credentials. 7211 * <p> 7212 * This value can only be returned on devices that use Full Disk Encryption. Support for Full 7213 * Disk Encryption was entirely removed in API level 33, having been replaced by File Based 7214 * Encryption. With File Based Encryption, each user's credential-encrypted storage is always 7215 * cryptographically protected by the user's credentials. 7216 */ 7217 public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4; 7218 7219 /** 7220 * Result code for {@link #getStorageEncryptionStatus}: 7221 * indicating that encryption is active and the encryption key is tied to the user or profile. 7222 * <p> 7223 * This value is only returned to apps targeting API level 24 and above. For apps targeting 7224 * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the 7225 * encryption key is specific to the user or profile. 7226 */ 7227 public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5; 7228 7229 /** 7230 * Activity action: begin the process of encrypting data on the device. This activity should 7231 * be launched after using {@link #setStorageEncryption} to request encryption be activated. 7232 * After resuming from this activity, use {@link #getStorageEncryption} 7233 * to check encryption status. However, on some devices this activity may never return, as 7234 * it may trigger a reboot and in some cases a complete data wipe of the device. 7235 */ 7236 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 7237 public static final String ACTION_START_ENCRYPTION 7238 = "android.app.action.START_ENCRYPTION"; 7239 7240 /** 7241 * Activity action: launch the DPC to check policy compliance. This intent is launched when 7242 * the user taps on the notification about personal apps suspension. When handling this intent 7243 * the DPC must check if personal apps should still be suspended and either unsuspend them or 7244 * instruct the user on how to resolve the noncompliance causing the suspension. 7245 * 7246 * @see #setPersonalAppsSuspended 7247 */ 7248 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 7249 public static final String ACTION_CHECK_POLICY_COMPLIANCE = 7250 "android.app.action.CHECK_POLICY_COMPLIANCE"; 7251 7252 /** 7253 * Broadcast action: notify managed provisioning that PO/DO provisioning has completed. 7254 * 7255 * @hide 7256 */ 7257 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 7258 public static final String ACTION_PROVISIONING_COMPLETED = 7259 "android.app.action.PROVISIONING_COMPLETED"; 7260 7261 /** 7262 * Extra for {@link #ACTION_PROVISIONING_COMPLETED} to indicate the provisioning action that has 7263 * been completed, this can either be {@link #ACTION_PROVISION_MANAGED_PROFILE}, 7264 * {@link #ACTION_PROVISION_MANAGED_DEVICE}, or {@link #ACTION_PROVISION_MANAGED_USER}. 7265 * 7266 * @hide 7267 */ 7268 public static final String EXTRA_PROVISIONING_ACTION = 7269 "android.app.extra.PROVISIONING_ACTION"; 7270 7271 /** 7272 * Broadcast action: notify system that a new (Android) user was added when the device is 7273 * managed by a device owner, so receivers can show the proper disclaimer to the (human) user. 7274 * 7275 * @hide 7276 */ 7277 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 7278 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 7279 public static final String ACTION_SHOW_NEW_USER_DISCLAIMER = 7280 "android.app.action.SHOW_NEW_USER_DISCLAIMER"; 7281 7282 /** 7283 * Widgets are enabled in keyguard 7284 */ 7285 public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0; 7286 7287 /** 7288 * Disable all keyguard widgets. Has no effect between {@link 7289 * android.os.Build.VERSION_CODES#LOLLIPOP} and {@link 7290 * android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} (both inclusive), since keyguard widget is 7291 * only supported on Android versions lower than 5.0 and versions higher than 14. 7292 */ 7293 public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0; 7294 7295 /** 7296 * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password) 7297 */ 7298 public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1; 7299 7300 /** 7301 * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password) 7302 */ 7303 public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2; 7304 7305 /** 7306 * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password) 7307 */ 7308 public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3; 7309 7310 /** 7311 * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password). 7312 * By setting this flag alone, all trust agents are disabled. If the admin then wants to 7313 * allowlist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be 7314 * used in conjuction to set trust-agent-specific configurations. 7315 */ 7316 public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4; 7317 7318 /** 7319 * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password). 7320 */ 7321 public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5; 7322 7323 /** 7324 * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password). 7325 * @deprecated This flag was added in version {@link android.os.Build.VERSION_CODES#N}, but it 7326 * never had any effect. 7327 */ 7328 @Deprecated 7329 public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6; 7330 7331 /** 7332 * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password). 7333 */ 7334 public static final int KEYGUARD_DISABLE_FACE = 1 << 7; 7335 7336 /** 7337 * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password). 7338 */ 7339 public static final int KEYGUARD_DISABLE_IRIS = 1 << 8; 7340 7341 /** 7342 * Disable all keyguard shortcuts. 7343 */ 7344 public static final int KEYGUARD_DISABLE_SHORTCUTS_ALL = 1 << 9; 7345 7346 /** 7347 * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures 7348 * CTS test when adding to the list above. 7349 */ 7350 7351 /** 7352 * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password). 7353 */ 7354 public static final int KEYGUARD_DISABLE_BIOMETRICS = 7355 DevicePolicyManager.KEYGUARD_DISABLE_FACE 7356 | DevicePolicyManager.KEYGUARD_DISABLE_IRIS 7357 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT; 7358 7359 /** 7360 * Disable all current and future keyguard customizations. 7361 */ 7362 public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff; 7363 7364 /** 7365 * Keyguard features that when set on a non-organization-owned managed profile that doesn't 7366 * have its own challenge will affect the profile's parent user. These can also be set on the 7367 * managed profile's parent {@link DevicePolicyManager} instance to explicitly control the 7368 * parent user. 7369 * 7370 * <p> 7371 * Organization-owned managed profile supports disabling additional keyguard features on the 7372 * parent user as defined in {@link #ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY}. 7373 * 7374 * @hide 7375 */ 7376 public static final int NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER = 7377 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS 7378 | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS; 7379 7380 /** 7381 * Keyguard features that when set by the profile owner of an organization-owned managed 7382 * profile will affect the profile's parent user if set on the managed profile's parent 7383 * {@link DevicePolicyManager} instance. 7384 * 7385 * @hide 7386 */ 7387 public static final int ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY = 7388 DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA 7389 | DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS 7390 | DevicePolicyManager.KEYGUARD_DISABLE_SHORTCUTS_ALL 7391 | DevicePolicyManager.KEYGUARD_DISABLE_WIDGETS_ALL; 7392 7393 /** 7394 * Keyguard features that when set on a normal or organization-owned managed profile, have 7395 * the potential to affect the profile's parent user. 7396 * 7397 * @hide 7398 */ 7399 public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER = 7400 DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER 7401 | DevicePolicyManager.ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY; 7402 7403 /** 7404 * @deprecated This method does not actually modify the storage encryption of the device. 7405 * It has never affected the encryption status of a device. 7406 * 7407 * Called by an application that is administering the device to request that the storage system 7408 * be encrypted. Does nothing if the caller is on a secondary user or a managed profile. 7409 * <p> 7410 * When multiple device administrators attempt to control device encryption, the most secure, 7411 * supported setting will always be used. If any device administrator requests device 7412 * encryption, it will be enabled; Conversely, if a device administrator attempts to disable 7413 * device encryption while another device administrator has enabled it, the call to disable will 7414 * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}). 7415 * <p> 7416 * This policy controls encryption of the secure (application data) storage area. Data written 7417 * to other storage areas may or may not be encrypted, and this policy does not require or 7418 * control the encryption of any other storage areas. There is one exception: If 7419 * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the 7420 * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be 7421 * written to disk within the encrypted storage area. 7422 * <p> 7423 * Important Note: On some devices, it is possible to encrypt storage without requiring the user 7424 * to create a device PIN or Password. In this case, the storage is encrypted, but the 7425 * encryption key may not be fully secured. For maximum security, the administrator should also 7426 * require (and check for) a pattern, PIN, or password. 7427 * 7428 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 7429 * @param encrypt true to request encryption, false to release any previous request 7430 * @return the new total request status (for all active admins), or {@link 7431 * DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user. 7432 * Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link 7433 * #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value 7434 * of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device 7435 * state. 7436 * 7437 * @throws SecurityException if {@code admin} is not an active administrator or does not use 7438 * {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE} 7439 */ 7440 @Deprecated setStorageEncryption(@onNull ComponentName admin, boolean encrypt)7441 public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) { 7442 throwIfParentInstance("setStorageEncryption"); 7443 if (mService != null) { 7444 try { 7445 return mService.setStorageEncryption(admin, encrypt); 7446 } catch (RemoteException e) { 7447 throw e.rethrowFromSystemServer(); 7448 } 7449 } 7450 return ENCRYPTION_STATUS_UNSUPPORTED; 7451 } 7452 7453 /** 7454 * @deprecated This method only returns the value set by {@link #setStorageEncryption}. 7455 * It does not actually reflect the storage encryption status. 7456 * Use {@link #getStorageEncryptionStatus} for that. 7457 * 7458 * Called by an application that is administering the device to 7459 * determine the requested setting for secure storage. 7460 * 7461 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null, 7462 * this will return the requested encryption setting as an aggregate of all active 7463 * administrators. 7464 * @return true if the admin(s) are requesting encryption, false if not. 7465 */ 7466 @Deprecated getStorageEncryption(@ullable ComponentName admin)7467 public boolean getStorageEncryption(@Nullable ComponentName admin) { 7468 throwIfParentInstance("getStorageEncryption"); 7469 if (mService != null) { 7470 try { 7471 return mService.getStorageEncryption(admin, myUserId()); 7472 } catch (RemoteException e) { 7473 throw e.rethrowFromSystemServer(); 7474 } 7475 } 7476 return false; 7477 } 7478 7479 /** 7480 * Called by an application that is administering the device to 7481 * determine the current encryption status of the device. 7482 * <p> 7483 * Depending on the returned status code, the caller may proceed in different 7484 * ways. If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the 7485 * storage system does not support encryption. If the 7486 * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link 7487 * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the 7488 * storage. If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the 7489 * storage system has enabled encryption but no password is set so further action 7490 * may be required. If the result is {@link #ENCRYPTION_STATUS_ACTIVATING}, 7491 * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}, 7492 * no further action is required. 7493 * 7494 * @return current status of encryption. The value will be one of 7495 * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, 7496 * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, 7497 * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}. 7498 * 7499 * @throws SecurityException if called on a parent instance. 7500 */ getStorageEncryptionStatus()7501 public int getStorageEncryptionStatus() { 7502 throwIfParentInstance("getStorageEncryptionStatus"); 7503 return getStorageEncryptionStatus(myUserId()); 7504 } 7505 7506 /** @hide per-user version */ 7507 @UnsupportedAppUsage getStorageEncryptionStatus(int userHandle)7508 public int getStorageEncryptionStatus(int userHandle) { 7509 if (mService != null) { 7510 try { 7511 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle); 7512 } catch (RemoteException e) { 7513 throw e.rethrowFromSystemServer(); 7514 } 7515 } 7516 return ENCRYPTION_STATUS_UNSUPPORTED; 7517 } 7518 7519 /** 7520 * Mark a CA certificate as approved by the device user. This means that they have been notified 7521 * of the installation, were made aware of the risks, viewed the certificate and still wanted to 7522 * keep the certificate on the device. 7523 * 7524 * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to 7525 * this certificate. 7526 * 7527 * @hide 7528 */ approveCaCert(String alias, int userHandle, boolean approval)7529 public boolean approveCaCert(String alias, int userHandle, boolean approval) { 7530 if (mService != null) { 7531 try { 7532 return mService.approveCaCert(alias, userHandle, approval); 7533 } catch (RemoteException e) { 7534 throw e.rethrowFromSystemServer(); 7535 } 7536 } 7537 return false; 7538 } 7539 7540 /** 7541 * Check whether a CA certificate has been approved by the device user. 7542 * 7543 * @hide 7544 */ isCaCertApproved(String alias, int userHandle)7545 public boolean isCaCertApproved(String alias, int userHandle) { 7546 if (mService != null) { 7547 try { 7548 return mService.isCaCertApproved(alias, userHandle); 7549 } catch (RemoteException e) { 7550 throw e.rethrowFromSystemServer(); 7551 } 7552 } 7553 return false; 7554 } 7555 7556 /** 7557 * Installs the given certificate as a user CA. 7558 * <p> 7559 * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and 7560 * higher. App developers can change the default behavior for an app by adding a 7561 * <a href="{@docRoot}training/articles/security-config.html">Security Configuration 7562 * File</a> to the app manifest file. 7563 * 7564 * The caller must be a profile or device owner on that user, or a delegate package given the 7565 * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a 7566 * security exception will be thrown. 7567 * 7568 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 7569 * {@code null} if calling from a delegated certificate installer. 7570 * @param certBuffer encoded form of the certificate to install. 7571 * 7572 * @return false if the certBuffer cannot be parsed or installation is 7573 * interrupted, true otherwise. 7574 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 7575 * owner. 7576 * @see #setDelegatedScopes 7577 * @see #DELEGATION_CERT_INSTALL 7578 */ installCaCert(@ullable ComponentName admin, byte[] certBuffer)7579 public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) { 7580 throwIfParentInstance("installCaCert"); 7581 if (mService != null) { 7582 try { 7583 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer); 7584 } catch (RemoteException e) { 7585 throw e.rethrowFromSystemServer(); 7586 } 7587 } 7588 return false; 7589 } 7590 7591 /** 7592 * Uninstalls the given certificate from trusted user CAs, if present. 7593 * 7594 * The caller must be a profile or device owner on that user, or a delegate package given the 7595 * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a 7596 * security exception will be thrown. 7597 * 7598 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 7599 * {@code null} if calling from a delegated certificate installer. 7600 * @param certBuffer encoded form of the certificate to remove. 7601 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 7602 * owner. 7603 * @see #setDelegatedScopes 7604 * @see #DELEGATION_CERT_INSTALL 7605 */ uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)7606 public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) { 7607 throwIfParentInstance("uninstallCaCert"); 7608 if (mService != null) { 7609 try { 7610 final String alias = getCaCertAlias(certBuffer); 7611 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias}); 7612 } catch (CertificateException e) { 7613 Log.w(TAG, "Unable to parse certificate", e); 7614 } catch (RemoteException e) { 7615 throw e.rethrowFromSystemServer(); 7616 } 7617 } 7618 } 7619 7620 /** 7621 * Returns all CA certificates that are currently trusted, excluding system CA certificates. 7622 * If a user has installed any certificates by other means than device policy these will be 7623 * included too. 7624 * 7625 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 7626 * {@code null} if calling from a delegated certificate installer. 7627 * @return a List of byte[] arrays, each encoding one user CA certificate. 7628 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 7629 * owner. 7630 */ getInstalledCaCerts(@ullable ComponentName admin)7631 public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) { 7632 final List<byte[]> certs = new ArrayList<byte[]>(); 7633 throwIfParentInstance("getInstalledCaCerts"); 7634 if (mService != null) { 7635 try { 7636 mService.enforceCanManageCaCerts(admin, mContext.getPackageName()); 7637 final TrustedCertificateStore certStore = new TrustedCertificateStore(); 7638 for (String alias : certStore.userAliases()) { 7639 try { 7640 certs.add(certStore.getCertificate(alias).getEncoded()); 7641 } catch (CertificateException ce) { 7642 Log.w(TAG, "Could not encode certificate: " + alias, ce); 7643 } 7644 } 7645 } catch (RemoteException re) { 7646 throw re.rethrowFromSystemServer(); 7647 } 7648 } 7649 return certs; 7650 } 7651 7652 /** 7653 * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by 7654 * means other than device policy will also be removed, except for system CA certificates. 7655 * 7656 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 7657 * {@code null} if calling from a delegated certificate installer. 7658 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 7659 * owner. 7660 */ uninstallAllUserCaCerts(@ullable ComponentName admin)7661 public void uninstallAllUserCaCerts(@Nullable ComponentName admin) { 7662 throwIfParentInstance("uninstallAllUserCaCerts"); 7663 if (mService != null) { 7664 try { 7665 mService.uninstallCaCerts(admin, mContext.getPackageName(), 7666 new TrustedCertificateStore().userAliases() .toArray(new String[0])); 7667 } catch (RemoteException re) { 7668 throw re.rethrowFromSystemServer(); 7669 } 7670 } 7671 } 7672 7673 /** 7674 * Returns whether this certificate is installed as a trusted CA. 7675 * 7676 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 7677 * {@code null} if calling from a delegated certificate installer. 7678 * @param certBuffer encoded form of the certificate to look up. 7679 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 7680 * owner. 7681 */ hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)7682 public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) { 7683 throwIfParentInstance("hasCaCertInstalled"); 7684 if (mService != null) { 7685 try { 7686 mService.enforceCanManageCaCerts(admin, mContext.getPackageName()); 7687 return getCaCertAlias(certBuffer) != null; 7688 } catch (RemoteException re) { 7689 throw re.rethrowFromSystemServer(); 7690 } catch (CertificateException ce) { 7691 Log.w(TAG, "Could not parse certificate", ce); 7692 } 7693 } 7694 return false; 7695 } 7696 7697 /** 7698 * This API can be called by the following to install a certificate and corresponding 7699 * private key: 7700 * <ul> 7701 * <li>Device owner</li> 7702 * <li>Profile owner</li> 7703 * <li>Delegated certificate installer</li> 7704 * <li>Credential management app</li> 7705 * <li>An app that holds the 7706 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li> 7707 * </ul> 7708 * All apps within the profile will be able to access the certificate and use the private key, 7709 * given direct user approval. 7710 * 7711 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app 7712 * can call this API. However, this API sets the key pair as user selectable by default, 7713 * which is not permitted when called by the credential management app. Instead, 7714 * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be 7715 * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag. 7716 * 7717 * <p>Access to the installed credentials will not be granted to the caller of this API without 7718 * direct user approval. This is for security - should a certificate installer become 7719 * compromised, certificates it had already installed will be protected. 7720 * 7721 * <p>If the installer must have access to the credentials, call 7722 * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead. 7723 * 7724 * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps 7725 * have been given to access the key and certificates associated with this alias will be 7726 * revoked. 7727 * 7728 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 7729 * {@code null} if the caller is not a device admin. 7730 * @param privKey The private key to install. 7731 * @param cert The certificate to install. 7732 * @param alias The private key alias under which to install the certificate. If a certificate 7733 * with that alias already exists, it will be overwritten. 7734 * @return {@code true} if the keys were installed, {@code false} otherwise. 7735 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 7736 * owner, or {@code admin} is null and the calling application does not have the 7737 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission. 7738 * @see #setDelegatedScopes 7739 * @see #DELEGATION_CERT_INSTALL 7740 */ 7741 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true) installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)7742 public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey, 7743 @NonNull Certificate cert, @NonNull String alias) { 7744 return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false); 7745 } 7746 7747 /** 7748 * This API can be called by the following to install a certificate chain and corresponding 7749 * private key for the leaf certificate: 7750 * <ul> 7751 * <li>Device owner</li> 7752 * <li>Profile owner</li> 7753 * <li>Delegated certificate installer</li> 7754 * <li>Credential management app</li> 7755 * <li>An app that holds the 7756 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li> 7757 * </ul> 7758 * All apps within the profile will be able to access the certificate chain and use the private 7759 * key, given direct user approval. 7760 * 7761 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app 7762 * can call this API. However, this API sets the key pair as user selectable by default, 7763 * which is not permitted when called by the credential management app. Instead, 7764 * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be 7765 * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag. 7766 * Note, there can only be a credential management app on an unmanaged device. 7767 * 7768 * <p>The caller of this API may grant itself access to the certificate and private key 7769 * immediately, without user approval. It is a best practice not to request this unless strictly 7770 * necessary since it opens up additional security vulnerabilities. 7771 * 7772 * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps 7773 * have been given to access the key and certificates associated with this alias will be 7774 * revoked. 7775 * 7776 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 7777 * {@code null} if the caller is not a device admin. 7778 * @param privKey The private key to install. 7779 * @param certs The certificate chain to install. The chain should start with the leaf 7780 * certificate and include the chain of trust in order. This will be returned by 7781 * {@link android.security.KeyChain#getCertificateChain}. 7782 * @param alias The private key alias under which to install the certificate. If a certificate 7783 * with that alias already exists, it will be overwritten. 7784 * @param requestAccess {@code true} to request that the calling app be granted access to the 7785 * credentials immediately. Otherwise, access to the credentials will be gated by user 7786 * approval. 7787 * @return {@code true} if the keys were installed, {@code false} otherwise. 7788 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 7789 * owner, or {@code admin} is null and the calling application does not have the 7790 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission. 7791 * @see android.security.KeyChain#getCertificateChain 7792 * @see #setDelegatedScopes 7793 * @see #DELEGATION_CERT_INSTALL 7794 */ 7795 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true) installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)7796 public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey, 7797 @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) { 7798 int flags = INSTALLKEY_SET_USER_SELECTABLE; 7799 if (requestAccess) { 7800 flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS; 7801 } 7802 return installKeyPair(admin, privKey, certs, alias, flags); 7803 } 7804 7805 /** 7806 * This API can be called by the following to install a certificate chain and corresponding 7807 * private key for the leaf certificate: 7808 * <ul> 7809 * <li>Device owner</li> 7810 * <li>Profile owner</li> 7811 * <li>Delegated certificate installer</li> 7812 * <li>Credential management app</li> 7813 * <li>An app that holds the 7814 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li> 7815 * </ul> 7816 * All apps within the profile will be able to access the certificate chain and use the 7817 * private key, given direct user approval (if the user is allowed to select the private key). 7818 * 7819 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app 7820 * can call this API. If called by the credential management app: 7821 * <ul> 7822 * <li>The componentName must be {@code null}r</li> 7823 * <li>The alias must exist in the credential management app's 7824 * {@link android.security.AppUriAuthenticationPolicy}</li> 7825 * <li>The key pair must not be user selectable</li> 7826 * </ul> 7827 * Note, there can only be a credential management app on an unmanaged device. 7828 * 7829 * <p>The caller of this API may grant itself access to the certificate and private key 7830 * immediately, without user approval. It is a best practice not to request this unless strictly 7831 * necessary since it opens up additional security vulnerabilities. 7832 * 7833 * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow 7834 * the user to select the key from a dialog. 7835 * 7836 * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps 7837 * have been given to access the key and certificates associated with this alias will be 7838 * revoked. 7839 * 7840 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 7841 * {@code null} if the caller is not a device admin. 7842 * @param privKey The private key to install. 7843 * @param certs The certificate chain to install. The chain should start with the leaf 7844 * certificate and include the chain of trust in order. This will be returned by 7845 * {@link android.security.KeyChain#getCertificateChain}. 7846 * @param alias The private key alias under which to install the certificate. If a certificate 7847 * with that alias already exists, it will be overwritten. 7848 * @param flags Flags to request that the calling app be granted access to the credentials 7849 * and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and 7850 * {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}. 7851 * @return {@code true} if the keys were installed, {@code false} otherwise. 7852 * @throws SecurityException if {@code admin} is not {@code null} and not a device or 7853 * profile owner, or {@code admin} is null but the calling application is not a 7854 * delegated certificate installer, credential management app and does not have the 7855 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission. 7856 * @see android.security.KeyChain#getCertificateChain 7857 * @see #setDelegatedScopes 7858 * @see #DELEGATION_CERT_INSTALL 7859 */ 7860 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true) installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)7861 public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey, 7862 @NonNull Certificate[] certs, @NonNull String alias, int flags) { 7863 throwIfParentInstance("installKeyPair"); 7864 boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS) 7865 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS; 7866 boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE) 7867 == INSTALLKEY_SET_USER_SELECTABLE; 7868 try { 7869 final byte[] pemCert = Credentials.convertToPem(certs[0]); 7870 byte[] pemChain = null; 7871 if (certs.length > 1) { 7872 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length)); 7873 } 7874 final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm()) 7875 .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded(); 7876 return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert, 7877 pemChain, alias, requestAccess, isUserSelectable); 7878 } catch (RemoteException e) { 7879 throw e.rethrowFromSystemServer(); 7880 } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { 7881 Log.w(TAG, "Failed to obtain private key material", e); 7882 } catch (CertificateException | IOException e) { 7883 Log.w(TAG, "Could not pem-encode certificate", e); 7884 } 7885 return false; 7886 } 7887 7888 /** 7889 * This API can be called by the following to remove a certificate and private key pair 7890 * installed under a given alias: 7891 * <ul> 7892 * <li>Device owner</li> 7893 * <li>Profile owner</li> 7894 * <li>Delegated certificate installer</li> 7895 * <li>Credential management app</li> 7896 * </ul> 7897 * 7898 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app 7899 * can call this API. If called by the credential management app, the componentName must be 7900 * {@code null}. Note, there can only be a credential management app on an unmanaged device. 7901 * 7902 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 7903 * {@code null} if the caller is not a device admin. 7904 * @param alias The private key alias under which the certificate is installed. 7905 * @return {@code true} if the private key alias no longer exists, {@code false} otherwise. 7906 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 7907 * owner, or {@code admin} is null but the calling application is not a delegated 7908 * certificate installer or credential management app. 7909 * @see #setDelegatedScopes 7910 * @see #DELEGATION_CERT_INSTALL 7911 */ 7912 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true) removeKeyPair(@ullable ComponentName admin, @NonNull String alias)7913 public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) { 7914 throwIfParentInstance("removeKeyPair"); 7915 try { 7916 return mService.removeKeyPair(admin, mContext.getPackageName(), alias); 7917 } catch (RemoteException e) { 7918 throw e.rethrowFromSystemServer(); 7919 } 7920 } 7921 7922 // STOPSHIP(b/174298501): clarify the expected return value following generateKeyPair call. 7923 /** 7924 * This API can be called by the following to query whether a certificate and private key are 7925 * installed under a given alias: 7926 * <ul> 7927 * <li>Device owner</li> 7928 * <li>Profile owner</li> 7929 * <li>Delegated certificate installer</li> 7930 * <li>Credential management app</li> 7931 * <li>An app that holds the 7932 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li> 7933 * </ul> 7934 * 7935 * If called by the credential management app, the alias must exist in the credential 7936 * management app's {@link android.security.AppUriAuthenticationPolicy}. 7937 * 7938 * @param alias The alias under which the key pair is installed. 7939 * @return {@code true} if a key pair with this alias exists, {@code false} otherwise. 7940 * @throws SecurityException if the caller is not a device or profile owner, a delegated 7941 * certificate installer, the credential management app and does not have the 7942 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission. 7943 * @see #setDelegatedScopes 7944 * @see #DELEGATION_CERT_INSTALL 7945 */ 7946 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true) hasKeyPair(@onNull String alias)7947 public boolean hasKeyPair(@NonNull String alias) { 7948 throwIfParentInstance("hasKeyPair"); 7949 try { 7950 return mService.hasKeyPair(mContext.getPackageName(), alias); 7951 } catch (RemoteException e) { 7952 throw e.rethrowFromSystemServer(); 7953 } 7954 } 7955 7956 /** 7957 * This API can be called by the following to generate a new private/public key pair: 7958 * <ul> 7959 * <li>Device owner</li> 7960 * <li>Profile owner</li> 7961 * <li>Delegated certificate installer</li> 7962 * <li>Credential management app</li> 7963 * <li>An app that holds the 7964 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li> 7965 * </ul> 7966 * If the device supports key generation via secure hardware, this method is useful for 7967 * creating a key in KeyChain that never left the secure hardware. Access to the key is 7968 * controlled the same way as in {@link #installKeyPair}. 7969 * 7970 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app 7971 * can call this API. If called by the credential management app, the componentName must be 7972 * {@code null}. Note, there can only be a credential management app on an unmanaged device. 7973 * 7974 * <p>Because this method might take several seconds to complete, it should only be called from 7975 * a worker thread. This method returns {@code null} when called from the main thread. 7976 * 7977 * <p>This method is not thread-safe, calling it from multiple threads at the same time will 7978 * result in undefined behavior. If the calling thread is interrupted while the invocation is 7979 * in-flight, it will eventually terminate and return {@code null}. 7980 * 7981 * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps 7982 * have been given to access the key and certificates associated with this alias will be 7983 * revoked. 7984 * 7985 * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via 7986 * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the 7987 * {@code idAttestationFlags} parameter, it is possible to request the device's unique 7988 * identity to be included in the attestation record. 7989 * 7990 * <p>Specific identifiers can be included in the attestation record, and an individual 7991 * attestation certificate can be used to sign the attestation record. To find out if the device 7992 * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and 7993 * {@link #isUniqueDeviceAttestationSupported()}. 7994 * 7995 * <p>Device owner, profile owner, their delegated certificate installer and the credential 7996 * management app can use {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device 7997 * information including manufacturer, model, brand, device and product in the attestation 7998 * record. 7999 * Only device owner, profile owner on an organization-owned device or affiliated user, and 8000 * their delegated certificate installers can use {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} 8001 * and {@link #ID_TYPE_MEID} to request unique device identifiers to be attested (the serial 8002 * number, IMEI and MEID correspondingly), if supported by the device 8003 * (see {@link #isDeviceIdAttestationSupported()}). 8004 * Additionally, device owner, profile owner on an organization-owned device and their delegated 8005 * certificate installers can also request the attestation record to be signed using an 8006 * individual attestation certificate by specifying the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} 8007 * flag (if supported by the device, see {@link #isUniqueDeviceAttestationSupported()}). 8008 * <p> 8009 * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID} 8010 * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set. 8011 * <p> 8012 * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if 8013 * key generation is done in StrongBox. 8014 * 8015 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 8016 * {@code null} if the caller is not a device admin. 8017 * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}. 8018 * @param keySpec Specification of the key to generate, see 8019 * {@link java.security.KeyPairGenerator}. 8020 * @param idAttestationFlags A bitmask of the identifiers that should be included in the 8021 * attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL}, 8022 * {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and 8023 * {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed 8024 * using an individual attestation certificate. 8025 * <p> 8026 * {@code 0} should be passed in if no device identification is required in the 8027 * attestation record and the batch attestation certificate should be used. 8028 * <p> 8029 * If any flag is specified, then an attestation challenge must be included in the 8030 * {@code keySpec}. 8031 * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise. 8032 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 8033 * owner, or {@code admin} is null but the calling application is not a delegated 8034 * certificate installer or credential management app. If Device ID attestation is 8035 * requested (using {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} or 8036 * {@link #ID_TYPE_MEID}), the caller must be the Device Owner or the Certificate 8037 * Installer delegate. 8038 * @throws IllegalArgumentException in the following cases: 8039 * <p> 8040 * <ul> 8041 * <li>The alias in {@code keySpec} is empty.</li> 8042 * <li>The algorithm specification in {@code keySpec} is not 8043 * {@code RSAKeyGenParameterSpec} or {@code ECGenParameterSpec}.</li> 8044 * <li>Device ID attestation was requested but the {@code keySpec} does not contain an 8045 * attestation challenge.</li> 8046 * </ul> 8047 * @throws UnsupportedOperationException if Device ID attestation or individual attestation 8048 * was requested but the underlying hardware does not support it. 8049 * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was 8050 * specified in {@code keySpec} but the device does not have one. 8051 * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[]) 8052 */ 8053 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true) generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)8054 public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin, 8055 @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, 8056 @AttestationIdType int idAttestationFlags) { 8057 throwIfParentInstance("generateKeyPair"); 8058 try { 8059 final ParcelableKeyGenParameterSpec parcelableSpec = 8060 new ParcelableKeyGenParameterSpec(keySpec); 8061 KeymasterCertificateChain attestationChain = new KeymasterCertificateChain(); 8062 8063 // Translate ID attestation flags to values used by AttestationUtils 8064 final boolean success = mService.generateKeyPair( 8065 admin, mContext.getPackageName(), algorithm, parcelableSpec, 8066 idAttestationFlags, attestationChain); 8067 if (!success) { 8068 Log.e(TAG, "Error generating key via DevicePolicyManagerService."); 8069 return null; 8070 } 8071 8072 final String alias = keySpec.getKeystoreAlias(); 8073 final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias); 8074 Certificate[] outputChain = null; 8075 try { 8076 if (AttestationUtils.isChainValid(attestationChain)) { 8077 outputChain = AttestationUtils.parseCertificateChain(attestationChain); 8078 } 8079 } catch (KeyAttestationException e) { 8080 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e); 8081 mService.removeKeyPair(admin, mContext.getPackageName(), alias); 8082 return null; 8083 } 8084 return new AttestedKeyPair(keyPair, outputChain); 8085 } catch (RemoteException e) { 8086 throw e.rethrowFromSystemServer(); 8087 } catch (KeyChainException e) { 8088 Log.w(TAG, "Failed to generate key", e); 8089 } catch (InterruptedException e) { 8090 Log.w(TAG, "Interrupted while generating key", e); 8091 Thread.currentThread().interrupt(); 8092 } catch (ServiceSpecificException e) { 8093 Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode)); 8094 switch (e.errorCode) { 8095 case KEY_GEN_STRONGBOX_UNAVAILABLE: 8096 throw new StrongBoxUnavailableException("No StrongBox for key generation."); 8097 default: 8098 throw new RuntimeException( 8099 String.format("Unknown error while generating key: %d", e.errorCode)); 8100 } 8101 } 8102 return null; 8103 } 8104 8105 /** 8106 * Called by a device or profile owner, or delegated certificate chooser (an app that has been 8107 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to grant an application access 8108 * to an already-installed (or generated) KeyChain key. 8109 * This is useful (in combination with {@link #installKeyPair} or {@link #generateKeyPair}) to 8110 * let an application call {@link android.security.KeyChain#getPrivateKey} without having to 8111 * call {@link android.security.KeyChain#choosePrivateKeyAlias} first. 8112 * 8113 * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED} 8114 * broadcast when access to a key is granted. 8115 * 8116 * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an 8117 * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key. 8118 * 8119 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 8120 * {@code null} if calling from a delegated certificate chooser. 8121 * @param alias The alias of the key to grant access to. 8122 * @param packageName The name of the (already installed) package to grant access to. 8123 * @return {@code true} if the grant was set successfully, {@code false} otherwise. 8124 * 8125 * @throws SecurityException if the caller is not a device owner, a profile owner or 8126 * delegated certificate chooser. 8127 * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if 8128 * {@code packageName} is not a name of an installed package. 8129 * @see #revokeKeyPairFromApp 8130 */ grantKeyPairToApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)8131 public boolean grantKeyPairToApp(@Nullable ComponentName admin, @NonNull String alias, 8132 @NonNull String packageName) { 8133 throwIfParentInstance("grantKeyPairToApp"); 8134 try { 8135 return mService.setKeyGrantForApp( 8136 admin, mContext.getPackageName(), alias, packageName, true); 8137 } catch (RemoteException e) { 8138 e.rethrowFromSystemServer(); 8139 } 8140 return false; 8141 } 8142 8143 /** 8144 * Called by a device or profile owner, or delegated certificate chooser (an app that has been 8145 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query which apps have access 8146 * to a given KeyChain key. 8147 * 8148 * Key are granted on a per-UID basis, so if several apps share the same UID, granting access to 8149 * one of them automatically grants it to others. This method returns a map containing one entry 8150 * per grantee UID. Entries have UIDs as keys and sets of corresponding package names as values. 8151 * In particular, grantee packages that don't share UID with other packages are represented by 8152 * entries having singleton sets as values. 8153 * 8154 * @param alias The alias of the key to grant access to. 8155 * @return apps that have access to a given key, arranged in a map from UID to sets of 8156 * package names. 8157 * 8158 * @throws SecurityException if the caller is not a device owner, a profile owner or 8159 * delegated certificate chooser. 8160 * @throws IllegalArgumentException if {@code alias} doesn't correspond to an existing key. 8161 * 8162 * @see #grantKeyPairToApp(ComponentName, String, String) 8163 */ getKeyPairGrants(@onNull String alias)8164 public @NonNull Map<Integer, Set<String>> getKeyPairGrants(@NonNull String alias) { 8165 throwIfParentInstance("getKeyPairGrants"); 8166 try { 8167 // The result is wrapped into intermediate parcelable representation. 8168 return mService.getKeyPairGrants(mContext.getPackageName(), alias).getPackagesByUid(); 8169 } catch (RemoteException e) { 8170 e.rethrowFromSystemServer(); 8171 } 8172 return null; 8173 } 8174 8175 /** 8176 * Called by a device or profile owner, or delegated certificate chooser (an app that has been 8177 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to revoke an application's 8178 * grant to a KeyChain key pair. 8179 * Calls by the application to {@link android.security.KeyChain#getPrivateKey} 8180 * will fail after the grant is revoked. 8181 * 8182 * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED} 8183 * broadcast when access to a key is revoked. 8184 * 8185 * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an 8186 * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key. 8187 * 8188 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 8189 * {@code null} if calling from a delegated certificate chooser. 8190 * @param alias The alias of the key to revoke access from. 8191 * @param packageName The name of the (already installed) package to revoke access from. 8192 * @return {@code true} if the grant was revoked successfully, {@code false} otherwise. 8193 * 8194 * @throws SecurityException if the caller is not a device owner, a profile owner or 8195 * delegated certificate chooser. 8196 * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if 8197 * {@code packageName} is not a name of an installed package. 8198 * @see #grantKeyPairToApp 8199 */ revokeKeyPairFromApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)8200 public boolean revokeKeyPairFromApp(@Nullable ComponentName admin, @NonNull String alias, 8201 @NonNull String packageName) { 8202 throwIfParentInstance("revokeKeyPairFromApp"); 8203 try { 8204 return mService.setKeyGrantForApp( 8205 admin, mContext.getPackageName(), alias, packageName, false); 8206 } catch (RemoteException e) { 8207 e.rethrowFromSystemServer(); 8208 } 8209 return false; 8210 } 8211 8212 /** 8213 * Called by a device or profile owner, or delegated certificate chooser (an app that has been 8214 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to allow using a KeyChain key 8215 * pair for authentication to Wifi networks. The key can then be used in configurations passed 8216 * to {@link android.net.wifi.WifiManager#addNetwork}. 8217 * 8218 * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an 8219 * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key. 8220 * 8221 * @param alias The alias of the key pair. 8222 * @return {@code true} if the operation was set successfully, {@code false} otherwise. 8223 * 8224 * @throws SecurityException if the caller is not a device owner, a profile owner or 8225 * delegated certificate chooser. 8226 * @see #revokeKeyPairFromWifiAuth 8227 */ grantKeyPairToWifiAuth(@onNull String alias)8228 public boolean grantKeyPairToWifiAuth(@NonNull String alias) { 8229 throwIfParentInstance("grantKeyPairToWifiAuth"); 8230 try { 8231 return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, true); 8232 } catch (RemoteException e) { 8233 e.rethrowFromSystemServer(); 8234 } 8235 return false; 8236 } 8237 8238 /** 8239 * Called by a device or profile owner, or delegated certificate chooser (an app that has been 8240 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to deny using a KeyChain key 8241 * pair for authentication to Wifi networks. Configured networks using this key won't be able to 8242 * authenticate. 8243 * 8244 * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an 8245 * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key. 8246 * 8247 * @param alias The alias of the key pair. 8248 * @return {@code true} if the operation was set successfully, {@code false} otherwise. 8249 * 8250 * @throws SecurityException if the caller is not a device owner, a profile owner or 8251 * delegated certificate chooser. 8252 * @see #grantKeyPairToWifiAuth 8253 */ revokeKeyPairFromWifiAuth(@onNull String alias)8254 public boolean revokeKeyPairFromWifiAuth(@NonNull String alias) { 8255 throwIfParentInstance("revokeKeyPairFromWifiAuth"); 8256 try { 8257 return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, false); 8258 } catch (RemoteException e) { 8259 e.rethrowFromSystemServer(); 8260 } 8261 return false; 8262 } 8263 8264 /** 8265 * Called by a device or profile owner, or delegated certificate chooser (an app that has been 8266 * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query whether a KeyChain key 8267 * pair can be used for authentication to Wifi networks. 8268 * 8269 * @param alias The alias of the key pair. 8270 * @return {@code true} if the key pair can be used, {@code false} otherwise. 8271 * 8272 * @throws SecurityException if the caller is not a device owner, a profile owner or 8273 * delegated certificate chooser. 8274 * @throws IllegalArgumentException if {@code alias} does not correspond to an existing key 8275 * @see #grantKeyPairToWifiAuth 8276 */ isKeyPairGrantedToWifiAuth(@onNull String alias)8277 public boolean isKeyPairGrantedToWifiAuth(@NonNull String alias) { 8278 throwIfParentInstance("isKeyPairGrantedToWifiAuth"); 8279 try { 8280 return mService.isKeyPairGrantedToWifiAuth(mContext.getPackageName(), alias); 8281 } catch (RemoteException e) { 8282 e.rethrowFromSystemServer(); 8283 } 8284 return false; 8285 } 8286 8287 /** 8288 * Returns {@code true} if the device supports attestation of device identifiers in addition 8289 * to key attestation. See 8290 * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)} 8291 * @return {@code true} if Device ID attestation is supported. 8292 */ isDeviceIdAttestationSupported()8293 public boolean isDeviceIdAttestationSupported() { 8294 PackageManager pm = mContext.getPackageManager(); 8295 return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION); 8296 } 8297 8298 /** 8299 * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned 8300 * with an individual attestation certificate and can sign attestation records using it (as 8301 * attestation using an individual attestation certificate is a feature only Keymaster 8302 * implementations with StrongBox security level can implement). 8303 * For use prior to calling 8304 * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}. 8305 * @return {@code true} if individual attestation is supported. 8306 */ isUniqueDeviceAttestationSupported()8307 public boolean isUniqueDeviceAttestationSupported() { 8308 PackageManager pm = mContext.getPackageManager(); 8309 return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION); 8310 } 8311 8312 /** 8313 * This API can be called by the following to associate certificates with a key pair that was 8314 * generated using {@link #generateKeyPair}, and set whether the key is available for the user 8315 * to choose in the certificate selection prompt: 8316 * <ul> 8317 * <li>Device owner</li> 8318 * <li>Profile owner</li> 8319 * <li>Delegated certificate installer</li> 8320 * <li>Credential management app</li> 8321 * </ul> 8322 * 8323 * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app 8324 * can call this API. If called by the credential management app, the componentName must be 8325 * {@code null}. Note, there can only be a credential management app on an unmanaged device. 8326 * 8327 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 8328 * {@code null} if the caller is not a device admin. 8329 * @param alias The private key alias under which to install the certificate. The {@code alias} 8330 * should denote an existing private key. If a certificate with that alias already 8331 * exists, it will be overwritten. 8332 * @param certs The certificate chain to install. The chain should start with the leaf 8333 * certificate and include the chain of trust in order. This will be returned by 8334 * {@link android.security.KeyChain#getCertificateChain}. 8335 * @param isUserSelectable {@code true} to indicate that a user can select this key via the 8336 * certificate selection prompt, {@code false} to indicate that this key can only be 8337 * granted access by implementing 8338 * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}. 8339 * @return {@code true} if the provided {@code alias} exists and the certificates has been 8340 * successfully associated with it, {@code false} otherwise. 8341 * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile 8342 * owner, or {@code admin} is null but the calling application is not a delegated 8343 * certificate installer or credential management app. 8344 */ 8345 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true) setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)8346 public boolean setKeyPairCertificate(@Nullable ComponentName admin, 8347 @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) { 8348 throwIfParentInstance("setKeyPairCertificate"); 8349 try { 8350 final byte[] pemCert = Credentials.convertToPem(certs.get(0)); 8351 byte[] pemChain = null; 8352 if (certs.size() > 1) { 8353 pemChain = Credentials.convertToPem( 8354 certs.subList(1, certs.size()).toArray(new Certificate[0])); 8355 } 8356 return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert, 8357 pemChain, isUserSelectable); 8358 } catch (RemoteException e) { 8359 throw e.rethrowFromSystemServer(); 8360 } catch (CertificateException | IOException e) { 8361 Log.w(TAG, "Could not pem-encode certificate", e); 8362 } 8363 return false; 8364 } 8365 8366 /** 8367 * @return the alias of a given CA certificate in the certificate store, or {@code null} if it 8368 * doesn't exist. 8369 */ getCaCertAlias(byte[] certBuffer)8370 private static String getCaCertAlias(byte[] certBuffer) throws CertificateException { 8371 final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 8372 final X509Certificate cert = (X509Certificate) certFactory.generateCertificate( 8373 new ByteArrayInputStream(certBuffer)); 8374 return new TrustedCertificateStore().getCertificateAlias(cert); 8375 } 8376 8377 /** 8378 * Called by a profile owner or device owner to grant access to privileged certificate 8379 * manipulation APIs to a third-party certificate installer app. Granted APIs include 8380 * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert}, 8381 * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}. 8382 * <p> 8383 * Delegated certificate installer is a per-user state. The delegated access is persistent until 8384 * it is later cleared by calling this method with a null value or uninstallling the certificate 8385 * installer. 8386 * <p> 8387 * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller 8388 * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the 8389 * supplied certificate installer package must be installed when calling this API, otherwise an 8390 * {@link IllegalArgumentException} will be thrown. 8391 * 8392 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 8393 * @param installerPackage The package name of the certificate installer which will be given 8394 * access. If {@code null} is given the current package will be cleared. 8395 * @throws SecurityException if {@code admin} is not a device or a profile owner. 8396 * 8397 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes} 8398 * with the {@link #DELEGATION_CERT_INSTALL} scope instead. 8399 */ 8400 @Deprecated setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)8401 public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String 8402 installerPackage) throws SecurityException { 8403 throwIfParentInstance("setCertInstallerPackage"); 8404 if (mService != null) { 8405 try { 8406 mService.setCertInstallerPackage(admin, installerPackage); 8407 } catch (RemoteException e) { 8408 throw e.rethrowFromSystemServer(); 8409 } 8410 } 8411 } 8412 8413 /** 8414 * Called by a profile owner or device owner to retrieve the certificate installer for the user, 8415 * or {@code null} if none is set. If there are multiple delegates this function will return one 8416 * of them. 8417 * 8418 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 8419 * @return The package name of the current delegated certificate installer, or {@code null} if 8420 * none is set. 8421 * @throws SecurityException if {@code admin} is not a device or a profile owner. 8422 * 8423 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages} 8424 * with the {@link #DELEGATION_CERT_INSTALL} scope instead. 8425 */ 8426 @Deprecated getCertInstallerPackage(@onNull ComponentName admin)8427 public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin) 8428 throws SecurityException { 8429 throwIfParentInstance("getCertInstallerPackage"); 8430 if (mService != null) { 8431 try { 8432 return mService.getCertInstallerPackage(admin); 8433 } catch (RemoteException e) { 8434 throw e.rethrowFromSystemServer(); 8435 } 8436 } 8437 return null; 8438 } 8439 8440 /** 8441 * Called by a profile owner or device owner to grant access to privileged APIs to another app. 8442 * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*} 8443 * constants. 8444 * <p> 8445 * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be 8446 * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra 8447 * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the 8448 * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag. 8449 * <p> 8450 * Delegated scopes are a per-user state. The delegated access is persistent until it is later 8451 * cleared by calling this method with an empty {@code scopes} list or uninstalling the 8452 * {@code delegatePackage}. 8453 * 8454 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 8455 * @param delegatePackage The package name of the app which will be given access. 8456 * @param scopes The groups of privileged APIs whose access should be granted to 8457 * {@code delegatedPackage}. 8458 * @throws SecurityException if {@code admin} is not a device or a profile owner. 8459 */ setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)8460 public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage, 8461 @NonNull List<String> scopes) { 8462 throwIfParentInstance("setDelegatedScopes"); 8463 if (mService != null) { 8464 try { 8465 mService.setDelegatedScopes(admin, delegatePackage, scopes); 8466 } catch (RemoteException e) { 8467 throw e.rethrowFromSystemServer(); 8468 } 8469 } 8470 } 8471 8472 /** 8473 * Called by a profile owner or device owner to retrieve a list of the scopes given to a 8474 * delegate package. Other apps can use this method to retrieve their own delegated scopes by 8475 * passing {@code null} for {@code admin} and their own package name as 8476 * {@code delegatedPackage}. 8477 * 8478 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 8479 * {@code null} if the caller is {@code delegatedPackage}. 8480 * @param delegatedPackage The package name of the app whose scopes should be retrieved. 8481 * @return A list containing the scopes given to {@code delegatedPackage}. 8482 * @throws SecurityException if {@code admin} is not a device or a profile owner. 8483 */ 8484 @NonNull getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)8485 public List<String> getDelegatedScopes(@Nullable ComponentName admin, 8486 @NonNull String delegatedPackage) { 8487 throwIfParentInstance("getDelegatedScopes"); 8488 if (mService != null) { 8489 try { 8490 return mService.getDelegatedScopes(admin, delegatedPackage); 8491 } catch (RemoteException e) { 8492 throw e.rethrowFromSystemServer(); 8493 } 8494 } 8495 return null; 8496 } 8497 8498 /** 8499 * Called by a profile owner or device owner to retrieve a list of delegate packages that were 8500 * granted a delegation scope. 8501 * 8502 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 8503 * @param delegationScope The scope whose delegates should be retrieved. 8504 * @return A list of package names of the current delegated packages for 8505 {@code delegationScope}. 8506 * @throws SecurityException if {@code admin} is not a device or a profile owner. 8507 */ 8508 @Nullable getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)8509 public List<String> getDelegatePackages(@NonNull ComponentName admin, 8510 @NonNull String delegationScope) { 8511 throwIfParentInstance("getDelegatePackages"); 8512 if (mService != null) { 8513 try { 8514 return mService.getDelegatePackages(admin, delegationScope); 8515 } catch (RemoteException e) { 8516 throw e.rethrowFromSystemServer(); 8517 } 8518 } 8519 return null; 8520 } 8521 8522 /** 8523 * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods. 8524 * @hide 8525 */ 8526 public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1; 8527 8528 /** 8529 * Called by a device or profile owner to configure an always-on VPN connection through a 8530 * specific application for the current user. This connection is automatically granted and 8531 * persisted after a reboot. 8532 * <p> To support the always-on feature, an app must 8533 * <ul> 8534 * <li>declare a {@link android.net.VpnService} in its manifest, guarded by 8535 * {@link android.Manifest.permission#BIND_VPN_SERVICE};</li> 8536 * <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li> 8537 * <li><i>not</i> explicitly opt out of the feature through 8538 * {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li> 8539 * </ul> 8540 * The call will fail if called with the package name of an unsupported VPN app. 8541 * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure 8542 * of the VPN provider could break networking for all apps. This method clears any lockdown 8543 * allowlist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}. 8544 * <p> Starting from {@link android.os.Build.VERSION_CODES#S API 31} calling this method with 8545 * {@code vpnPackage} set to {@code null} only removes the existing configuration if it was 8546 * previously created by this admin. To remove VPN configuration created by the user use 8547 * {@link UserManager#DISALLOW_CONFIG_VPN}. 8548 * 8549 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to 8550 * remove an existing always-on VPN configuration. 8551 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or 8552 * {@code false} otherwise. This has no effect when clearing. 8553 * @throws SecurityException if {@code admin} is not a device or a profile owner. 8554 * @throws NameNotFoundException if {@code vpnPackage} is not installed. 8555 * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being 8556 * set as always-on, or if always-on VPN is not available. 8557 * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set) 8558 */ setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)8559 public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage, 8560 boolean lockdownEnabled) throws NameNotFoundException { 8561 setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet()); 8562 } 8563 8564 /** 8565 * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the 8566 * admin to specify a set of apps that should be able to access the network directly when VPN 8567 * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN. 8568 * System apps can always bypass VPN. 8569 * <p> Note that the system doesn't update the allowlist when packages are installed or 8570 * uninstalled, the admin app must call this method to keep the list up to date. 8571 * <p> When {@code lockdownEnabled} is false {@code lockdownAllowlist} is ignored . When 8572 * {@code lockdownEnabled} is {@code true} and {@code lockdownAllowlist} is {@code null} or 8573 * empty, only system apps can bypass VPN. 8574 * <p> Setting always-on VPN package to {@code null} or using 8575 * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown allowlist. 8576 * 8577 * @param vpnPackage package name for an installed VPN app on the device, or {@code null} 8578 * to remove an existing always-on VPN configuration 8579 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or 8580 * {@code false} otherwise. This has no effect when clearing. 8581 * @param lockdownAllowlist Packages that will be able to access the network directly when VPN 8582 * is in lockdown mode but not connected. Has no effect when clearing. 8583 * @throws SecurityException if {@code admin} is not a device or a profile 8584 * owner. 8585 * @throws NameNotFoundException if {@code vpnPackage} or one of 8586 * {@code lockdownAllowlist} is not installed. 8587 * @throws UnsupportedOperationException if {@code vpnPackage} exists but does 8588 * not support being set as always-on, or if always-on VPN is not 8589 * available. 8590 */ setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)8591 public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage, 8592 boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist) 8593 throws NameNotFoundException { 8594 throwIfParentInstance("setAlwaysOnVpnPackage"); 8595 if (mService != null) { 8596 try { 8597 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, 8598 lockdownAllowlist == null ? null : new ArrayList<>(lockdownAllowlist)); 8599 } catch (ServiceSpecificException e) { 8600 switch (e.errorCode) { 8601 case ERROR_VPN_PACKAGE_NOT_FOUND: 8602 throw new NameNotFoundException(e.getMessage()); 8603 default: 8604 throw new RuntimeException( 8605 "Unknown error setting always-on VPN: " + e.errorCode, e); 8606 } 8607 } catch (RemoteException e) { 8608 throw e.rethrowFromSystemServer(); 8609 } 8610 } 8611 } 8612 8613 /** 8614 * Called by device or profile owner to query whether current always-on VPN is configured in 8615 * lockdown mode. Returns {@code false} when no always-on configuration is set. 8616 * 8617 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 8618 * 8619 * @throws SecurityException if {@code admin} is not a device or a profile owner. 8620 * 8621 * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean) 8622 */ isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)8623 public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) { 8624 throwIfParentInstance("isAlwaysOnVpnLockdownEnabled"); 8625 if (mService != null) { 8626 try { 8627 // Starting from Android R, the caller can pass the permission check in 8628 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK. 8629 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission 8630 // which is used by the NetworkStack mainline module. 8631 return mService.isAlwaysOnVpnLockdownEnabled(admin); 8632 } catch (RemoteException e) { 8633 throw e.rethrowFromSystemServer(); 8634 } 8635 } 8636 return false; 8637 } 8638 8639 /** 8640 * Returns whether the admin has enabled always-on VPN lockdown for the current user. 8641 * 8642 * Only callable by the system. 8643 * @hide 8644 */ 8645 @UserHandleAware isAlwaysOnVpnLockdownEnabled()8646 public boolean isAlwaysOnVpnLockdownEnabled() { 8647 throwIfParentInstance("isAlwaysOnVpnLockdownEnabled"); 8648 if (mService != null) { 8649 try { 8650 return mService.isAlwaysOnVpnLockdownEnabledForUser(myUserId()); 8651 } catch (RemoteException e) { 8652 throw e.rethrowFromSystemServer(); 8653 } 8654 } 8655 return false; 8656 } 8657 8658 /** 8659 * Called by device or profile owner to query the set of packages that are allowed to access 8660 * the network directly when always-on VPN is in lockdown mode but not connected. Returns 8661 * {@code null} when always-on VPN is not active or not in lockdown mode. 8662 * 8663 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 8664 * 8665 * @throws SecurityException if {@code admin} is not a device or a profile owner. 8666 * 8667 * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set) 8668 */ getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)8669 public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) { 8670 throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist"); 8671 if (mService != null) { 8672 try { 8673 final List<String> allowlist = 8674 mService.getAlwaysOnVpnLockdownAllowlist(admin); 8675 return allowlist == null ? null : new HashSet<>(allowlist); 8676 } catch (RemoteException e) { 8677 throw e.rethrowFromSystemServer(); 8678 } 8679 } 8680 return null; 8681 } 8682 8683 /** 8684 * Called by a device or profile owner to read the name of the package administering an 8685 * always-on VPN connection for the current user. If there is no such package, or the always-on 8686 * VPN is provided by the system instead of by an application, {@code null} will be returned. 8687 * 8688 * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none 8689 * is set. 8690 * @throws SecurityException if {@code admin} is not a device or a profile owner. 8691 */ getAlwaysOnVpnPackage(@onNull ComponentName admin)8692 public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) { 8693 throwIfParentInstance("getAlwaysOnVpnPackage"); 8694 if (mService != null) { 8695 try { 8696 return mService.getAlwaysOnVpnPackage(admin); 8697 } catch (RemoteException e) { 8698 throw e.rethrowFromSystemServer(); 8699 } 8700 } 8701 return null; 8702 } 8703 8704 /** 8705 * Returns the VPN package name if the admin has enabled always-on VPN on the current user, 8706 * or {@code null} if none is set. 8707 * 8708 * Only callable by the system. 8709 * @hide 8710 */ 8711 @UserHandleAware getAlwaysOnVpnPackage()8712 public @Nullable String getAlwaysOnVpnPackage() { 8713 throwIfParentInstance("getAlwaysOnVpnPackage"); 8714 if (mService != null) { 8715 try { 8716 return mService.getAlwaysOnVpnPackageForUser(myUserId()); 8717 } catch (RemoteException e) { 8718 throw e.rethrowFromSystemServer(); 8719 } 8720 } 8721 return null; 8722 } 8723 8724 /** 8725 * Called by an application that is administering the device to disable all cameras on the 8726 * device, for this user. After setting this, no applications running as this user will be able 8727 * to access any cameras on the device. 8728 * <p> 8729 * This method can be called on the {@link DevicePolicyManager} instance, 8730 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be 8731 * the profile owner of an organization-owned managed profile. 8732 * <p> 8733 * If the caller is device owner, then the restriction will be applied to all users. If 8734 * called on the parent instance, then the restriction will be applied on the personal profile. 8735 * <p> 8736 * The calling device admin must have requested 8737 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has 8738 * not, a security exception will be thrown. 8739 * <p> 8740 * <b>Note</b>, this policy type is deprecated for legacy device admins since 8741 * {@link android.os.Build.VERSION_CODES#Q}. On Android 8742 * {@link android.os.Build.VERSION_CODES#Q} devices, legacy device admins targeting SDK 8743 * version {@link android.os.Build.VERSION_CODES#P} or below can still call this API to 8744 * disable camera, while legacy device admins targeting SDK version 8745 * {@link android.os.Build.VERSION_CODES#Q} will receive a SecurityException. Starting 8746 * from Android {@link android.os.Build.VERSION_CODES#R}, requests to disable camera from 8747 * legacy device admins targeting SDK version {@link android.os.Build.VERSION_CODES#P} or 8748 * below will be silently ignored. 8749 * <p> 8750 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the camera disabled 8751 * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 8752 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 8753 * successfully set or not. This callback will contain: 8754 * <ul> 8755 * <li> The policy identifier: userRestriction_no_camera 8756 * <li> The {@link TargetUser} that this policy relates to 8757 * <li> The {@link PolicyUpdateResult}, which will be 8758 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 8759 * reason the policy failed to be set 8760 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 8761 * </ul> 8762 * If there has been a change to the policy, 8763 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 8764 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 8765 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 8766 * will contain the reason why the policy changed. 8767 * 8768 * @param admin Which {@link DeviceAdminReceiver} this request is associated with or null if 8769 the caller is not a device admin 8770 * @param disabled Whether or not the camera should be disabled. 8771 * @throws SecurityException if {@code admin} is not an active administrator or does not use 8772 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}. 8773 */ 8774 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CAMERA, conditional = true) 8775 @SupportsCoexistence setCameraDisabled(@ullable ComponentName admin, boolean disabled)8776 public void setCameraDisabled(@Nullable ComponentName admin, boolean disabled) { 8777 if (mService != null) { 8778 try { 8779 mService.setCameraDisabled(admin, mContext.getPackageName(), disabled, 8780 mParentInstance); 8781 } catch (RemoteException e) { 8782 throw e.rethrowFromSystemServer(); 8783 } 8784 } 8785 } 8786 8787 /** 8788 * Determine whether or not the device's cameras have been disabled for this user, 8789 * either by the calling admin, if specified, or all admins. 8790 * <p> 8791 * This method can be called on the {@link DevicePolicyManager} instance, 8792 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be 8793 * the profile owner of an organization-owned managed profile. 8794 * 8795 * @param admin The name of the admin component to check, or {@code null} to check whether any 8796 * admins have disabled the camera 8797 */ 8798 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CAMERA, conditional = true) getCameraDisabled(@ullable ComponentName admin)8799 public boolean getCameraDisabled(@Nullable ComponentName admin) { 8800 return getCameraDisabled(admin, myUserId()); 8801 } 8802 8803 /** @hide per-user version */ 8804 @UnsupportedAppUsage getCameraDisabled(@ullable ComponentName admin, int userHandle)8805 public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) { 8806 if (mService != null) { 8807 try { 8808 return mService.getCameraDisabled(admin, mContext.getPackageName(), userHandle, 8809 mParentInstance); 8810 } catch (RemoteException e) { 8811 throw e.rethrowFromSystemServer(); 8812 } 8813 } 8814 return false; 8815 } 8816 8817 /** 8818 * Called by a device owner to request a bugreport. 8819 * <p> 8820 * If the device contains secondary users or profiles, they must be affiliated with the device. 8821 * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}. 8822 * 8823 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 8824 * @return {@code true} if the bugreport collection started successfully, or {@code false} if it 8825 * wasn't triggered because a previous bugreport operation is still active (either the 8826 * bugreport is still running or waiting for the user to share or decline) 8827 * @throws SecurityException if {@code admin} is not a device owner, or there is at least one 8828 * profile or secondary user that is not affiliated with the device. 8829 * @see #isAffiliatedUser 8830 */ requestBugreport(@onNull ComponentName admin)8831 public boolean requestBugreport(@NonNull ComponentName admin) { 8832 throwIfParentInstance("requestBugreport"); 8833 if (mService != null) { 8834 try { 8835 return mService.requestBugreport(admin); 8836 } catch (RemoteException e) { 8837 throw e.rethrowFromSystemServer(); 8838 } 8839 } 8840 return false; 8841 } 8842 8843 /** 8844 * Called by a device/profile owner to set whether the screen capture is disabled. Disabling 8845 * screen capture also prevents the content from being shown on display devices that do not have 8846 * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about 8847 * secure surfaces and secure displays. 8848 * <p> 8849 * This method can be called on the {@link DevicePolicyManager} instance, returned by 8850 * {@link #getParentProfileInstance(ComponentName)}, where the calling device admin must be 8851 * the profile owner of an organization-owned managed profile. If it is not, a security 8852 * exception will be thrown. 8853 * <p> 8854 * If the caller is device owner or called on the parent instance by a profile owner of an 8855 * organization-owned managed profile, then the restriction will be applied to all users. 8856 * <p> 8857 * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks 8858 * assist requests for all activities of the relevant user. 8859 * 8860 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 8861 * caller is not a device admin. 8862 * @param disabled Whether screen capture is disabled or not. 8863 * @throws SecurityException if the caller is not permitted to control screen capture policy. 8864 */ 8865 @RequiresPermission(value = MANAGE_DEVICE_POLICY_SCREEN_CAPTURE, conditional = true) setScreenCaptureDisabled(@ullable ComponentName admin, boolean disabled)8866 public void setScreenCaptureDisabled(@Nullable ComponentName admin, boolean disabled) { 8867 if (mService != null) { 8868 try { 8869 mService.setScreenCaptureDisabled( 8870 admin, mContext.getPackageName(), disabled, mParentInstance); 8871 } catch (RemoteException e) { 8872 throw e.rethrowFromSystemServer(); 8873 } 8874 } 8875 } 8876 8877 /** 8878 * Determine whether or not screen capture has been disabled by the calling 8879 * admin, if specified, or all admins. 8880 * <p> 8881 * This method can be called on the {@link DevicePolicyManager} instance, 8882 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be 8883 * the profile owner of an organization-owned managed profile (the calling admin must be 8884 * specified). 8885 * 8886 * @param admin The name of the admin component to check, or {@code null} to check whether any 8887 * admins have disabled screen capture. 8888 */ getScreenCaptureDisabled(@ullable ComponentName admin)8889 public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) { 8890 return getScreenCaptureDisabled(admin, myUserId()); 8891 } 8892 8893 /** @hide per-user version */ getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)8894 public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) { 8895 if (mService != null) { 8896 try { 8897 return mService.getScreenCaptureDisabled(admin, userHandle, mParentInstance); 8898 } catch (RemoteException e) { 8899 throw e.rethrowFromSystemServer(); 8900 } 8901 } 8902 return false; 8903 } 8904 8905 /** 8906 * Called by a device/profile owner to set nearby notification streaming policy. Notification 8907 * streaming is sending notification data from pre-installed apps to nearby devices. 8908 * 8909 * @param policy One of the {@code NearbyStreamingPolicy} constants. 8910 * @throws SecurityException if caller is not a device or profile owner 8911 */ setNearbyNotificationStreamingPolicy(@earbyStreamingPolicy int policy)8912 public void setNearbyNotificationStreamingPolicy(@NearbyStreamingPolicy int policy) { 8913 throwIfParentInstance("setNearbyNotificationStreamingPolicy"); 8914 if (mService == null) { 8915 return; 8916 } 8917 try { 8918 mService.setNearbyNotificationStreamingPolicy(policy); 8919 } catch (RemoteException e) { 8920 throw e.rethrowFromSystemServer(); 8921 } 8922 } 8923 8924 /** 8925 * Returns the current runtime nearby notification streaming policy set by the device or profile 8926 * owner. 8927 * <p> 8928 * The caller must be the target user's device owner/profile owner or hold the 8929 * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY} 8930 * permission. 8931 */ 8932 @RequiresPermission( 8933 value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY, 8934 conditional = true) getNearbyNotificationStreamingPolicy()8935 public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy() { 8936 return getNearbyNotificationStreamingPolicy(myUserId()); 8937 } 8938 8939 /** @hide per-user version */ getNearbyNotificationStreamingPolicy(int userId)8940 public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy(int userId) { 8941 throwIfParentInstance("getNearbyNotificationStreamingPolicy"); 8942 if (mService == null) { 8943 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 8944 } 8945 try { 8946 return mService.getNearbyNotificationStreamingPolicy(userId); 8947 } catch (RemoteException re) { 8948 throw re.rethrowFromSystemServer(); 8949 } 8950 } 8951 8952 /** 8953 * Called by a device/profile owner to set nearby app streaming policy. App streaming is when 8954 * the device starts an app on a virtual display and sends a video stream of the app to nearby 8955 * devices. 8956 * 8957 * @param policy One of the {@code NearbyStreamingPolicy} constants. 8958 * @throws SecurityException if caller is not a device or profile owner. 8959 */ setNearbyAppStreamingPolicy(@earbyStreamingPolicy int policy)8960 public void setNearbyAppStreamingPolicy(@NearbyStreamingPolicy int policy) { 8961 throwIfParentInstance("setNearbyAppStreamingPolicy"); 8962 if (mService == null) { 8963 return; 8964 } 8965 try { 8966 mService.setNearbyAppStreamingPolicy(policy); 8967 } catch (RemoteException e) { 8968 throw e.rethrowFromSystemServer(); 8969 } 8970 } 8971 8972 /** 8973 * Returns the current runtime nearby app streaming policy set by the device or profile owner. 8974 * <p> 8975 * The caller must be the target user's device owner/profile owner or hold the 8976 * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY} 8977 * permission. 8978 */ 8979 @RequiresPermission( 8980 value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY, 8981 conditional = true) getNearbyAppStreamingPolicy()8982 public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy() { 8983 return getNearbyAppStreamingPolicy(myUserId()); 8984 } 8985 8986 /** @hide per-user version */ getNearbyAppStreamingPolicy(int userId)8987 public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy(int userId) { 8988 throwIfParentInstance("getNearbyAppStreamingPolicy"); 8989 if (mService == null) { 8990 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 8991 } 8992 try { 8993 return mService.getNearbyAppStreamingPolicy(userId); 8994 } catch (RemoteException re) { 8995 throw re.rethrowFromSystemServer(); 8996 } 8997 } 8998 8999 /** 9000 * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or 9001 * higher, to set whether auto time is required. If auto time is required, no user will be able 9002 * set the date and time and network date and time will be used. 9003 * <p> 9004 * Note: If auto time is required the user can still manually set the time zone. Staring from 9005 * Android 11, if auto time is required, the user cannot manually set the time zone. 9006 * <p> 9007 * The calling device admin must be a device owner, or alternatively a profile owner from 9008 * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown. 9009 * <p> 9010 * Staring from Android 11, this API switches to use 9011 * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to enforce the auto time settings. Calling 9012 * this API to enforce auto time will result in 9013 * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being set, while calling this API to lift 9014 * the requirement will result in {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being cleared. 9015 * From Android 11, this API can also no longer be called on a managed profile. 9016 * 9017 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 9018 * @param required Whether auto time is set required or not. 9019 * @throws SecurityException if {@code admin} is not a device owner, not a profile owner or 9020 * if this API is called on a managed profile. 9021 * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled} 9022 * to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME} 9023 * to prevent the user from changing this setting. 9024 */ 9025 @Deprecated setAutoTimeRequired(@onNull ComponentName admin, boolean required)9026 public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) { 9027 throwIfParentInstance("setAutoTimeRequired"); 9028 if (mService != null) { 9029 try { 9030 mService.setAutoTimeRequired(admin, required); 9031 } catch (RemoteException e) { 9032 throw e.rethrowFromSystemServer(); 9033 } 9034 } 9035 } 9036 9037 /** 9038 * @return true if auto time is required. 9039 * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled} 9040 */ 9041 @Deprecated getAutoTimeRequired()9042 public boolean getAutoTimeRequired() { 9043 throwIfParentInstance("getAutoTimeRequired"); 9044 if (mService != null) { 9045 try { 9046 return mService.getAutoTimeRequired(); 9047 } catch (RemoteException e) { 9048 throw e.rethrowFromSystemServer(); 9049 } 9050 } 9051 return false; 9052 } 9053 9054 /** 9055 * Called by a device owner, a profile owner for the primary user or a profile 9056 * owner of an organization-owned managed profile to turn auto time on and off. 9057 * <p> 9058 * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to prevent the 9059 * user from changing this setting, that way no user will be able set the date and time zone. 9060 * 9061 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 9062 * caller is not a device admin. 9063 * @param enabled Whether time should be obtained automatically from the network or not. 9064 * @throws SecurityException if caller is not a device owner, a profile owner for the 9065 * primary user, or a profile owner of an organization-owned managed profile. 9066 */ 9067 @RequiresPermission(value = SET_TIME, conditional = true) setAutoTimeEnabled(@ullable ComponentName admin, boolean enabled)9068 public void setAutoTimeEnabled(@Nullable ComponentName admin, boolean enabled) { 9069 throwIfParentInstance("setAutoTimeEnabled"); 9070 if (mService != null) { 9071 try { 9072 if (Flags.setAutoTimeEnabledCoexistence()) { 9073 mService.setAutoTimePolicy(mContext.getPackageName(), 9074 enabled ? DevicePolicyManager.AUTO_TIME_ENABLED 9075 : DevicePolicyManager.AUTO_TIME_DISABLED); 9076 } else { 9077 mService.setAutoTimeEnabled(admin, mContext.getPackageName(), enabled); 9078 } 9079 } catch (RemoteException e) { 9080 throw e.rethrowFromSystemServer(); 9081 } 9082 } 9083 } 9084 9085 /** 9086 * Returns true if auto time is enabled on the device. 9087 * 9088 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 9089 * caller is not a device admin. 9090 * @return true if auto time is enabled on the device. 9091 * @throws SecurityException if caller is not a device owner, a profile owner for the 9092 * primary user, or a profile owner of an organization-owned managed profile. 9093 */ 9094 @RequiresPermission(anyOf = {SET_TIME, QUERY_ADMIN_POLICY}, conditional = true) getAutoTimeEnabled(@ullable ComponentName admin)9095 public boolean getAutoTimeEnabled(@Nullable ComponentName admin) { 9096 throwIfParentInstance("getAutoTimeEnabled"); 9097 if (mService != null) { 9098 try { 9099 return mService.getAutoTimeEnabled(admin, mContext.getPackageName()); 9100 } catch (RemoteException e) { 9101 throw e.rethrowFromSystemServer(); 9102 } 9103 } 9104 return false; 9105 } 9106 9107 /** 9108 * Specifies that the auto time state is not controlled by device policy. 9109 * 9110 * @see #setAutoTimePolicy(ComponentName, int) 9111 */ 9112 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ENABLED_COEXISTENCE) 9113 public static final int AUTO_TIME_NOT_CONTROLLED_BY_POLICY = 0; 9114 9115 /** 9116 * Specifies the "disabled" auto time state. 9117 * 9118 * @see #setAutoTimePolicy(ComponentName, int) 9119 */ 9120 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ENABLED_COEXISTENCE) 9121 public static final int AUTO_TIME_DISABLED = 1; 9122 9123 /** 9124 * Specifies the "enabled" auto time state. 9125 * 9126 * @see #setAutoTimePolicy(ComponentName, int) 9127 */ 9128 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ENABLED_COEXISTENCE) 9129 public static final int AUTO_TIME_ENABLED = 2; 9130 9131 /** 9132 * Flags supplied to {@link #setAutoTimePolicy}(ComponentName, int)}. 9133 * 9134 * @hide 9135 */ 9136 @Retention(RetentionPolicy.SOURCE) 9137 @IntDef(prefix = { "AUTO_TIME_" }, value = { 9138 AUTO_TIME_NOT_CONTROLLED_BY_POLICY, 9139 AUTO_TIME_DISABLED, 9140 AUTO_TIME_ENABLED 9141 }) 9142 public @interface AutoTimePolicy {} 9143 9144 /** 9145 * Called by a device owner, a profile owner for the primary user or a profile owner of an 9146 * organization-owned managed profile to turn auto time on and off i.e. Whether time should be 9147 * obtained automatically from the network or not. 9148 * <p> 9149 * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to prevent the 9150 * user from changing this setting, that way no user will be able set the date and time zone. 9151 * 9152 * @param policy The desired state among {@link #AUTO_TIME_ENABLED} to enable, 9153 * {@link #AUTO_TIME_DISABLED} to disable and 9154 * {@link #AUTO_TIME_NOT_CONTROLLED_BY_POLICY} to unset the policy. 9155 * @throws SecurityException if caller is not a device owner, a profile owner for the 9156 * primary user, or a profile owner of an organization-owned managed profile, or if the caller 9157 * does not hold the required permission. 9158 */ 9159 @SupportsCoexistence 9160 @RequiresPermission(value = SET_TIME, conditional = true) 9161 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ENABLED_COEXISTENCE) setAutoTimePolicy(@utoTimePolicy int policy)9162 public void setAutoTimePolicy(@AutoTimePolicy int policy) { 9163 throwIfParentInstance("setAutoTimePolicy"); 9164 if (mService != null) { 9165 try { 9166 mService.setAutoTimePolicy(mContext.getPackageName(), policy); 9167 } catch (RemoteException e) { 9168 throw e.rethrowFromSystemServer(); 9169 } 9170 } 9171 } 9172 9173 /** 9174 * Returns current auto time policy's state. 9175 * 9176 * @return One of {@link #AUTO_TIME_ENABLED} if enabled, {@link #AUTO_TIME_DISABLED} if disabled 9177 * and {@link #AUTO_TIME_NOT_CONTROLLED_BY_POLICY} if it's not controlled by 9178 * policy. 9179 * @throws SecurityException if caller is not a device owner, a profile owner for the 9180 * primary user, or a profile owner of an organization-owned managed profile, or if the caller 9181 * does not hold the required permission. 9182 */ 9183 @SupportsCoexistence 9184 @RequiresPermission(anyOf = {SET_TIME, QUERY_ADMIN_POLICY}, conditional = true) 9185 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ENABLED_COEXISTENCE) getAutoTimePolicy()9186 public @AutoTimePolicy int getAutoTimePolicy() { 9187 throwIfParentInstance("getAutoTimePolicy"); 9188 if (mService != null) { 9189 try { 9190 return mService.getAutoTimePolicy(mContext.getPackageName()); 9191 } catch (RemoteException e) { 9192 throw e.rethrowFromSystemServer(); 9193 } 9194 } 9195 return DevicePolicyManager.AUTO_TIME_NOT_CONTROLLED_BY_POLICY; 9196 } 9197 9198 /** 9199 * Called by a device owner, a profile owner for the primary user or a profile 9200 * owner of an organization-owned managed profile to turn auto time zone on and off. 9201 * <p> 9202 * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to prevent the 9203 * user from changing this setting, that way no user will be able set the date and time zone. 9204 * 9205 * @param admin Which {@link DeviceAdminReceiver} this request is associated with or Null if the 9206 * caller is not a device admin. 9207 * @param enabled Whether time zone should be obtained automatically from the network or not. 9208 * @throws SecurityException if caller is not a device owner, a profile owner for the 9209 * primary user, or a profile owner of an organization-owned managed profile. 9210 */ 9211 @RequiresPermission(value = SET_TIME_ZONE, conditional = true) setAutoTimeZoneEnabled(@ullable ComponentName admin, boolean enabled)9212 public void setAutoTimeZoneEnabled(@Nullable ComponentName admin, boolean enabled) { 9213 throwIfParentInstance("setAutoTimeZone"); 9214 if (mService != null) { 9215 try { 9216 if (Flags.setAutoTimeZoneEnabledCoexistence()) { 9217 mService.setAutoTimeZonePolicy(mContext.getPackageName(), 9218 enabled ? AUTO_TIME_ZONE_ENABLED : AUTO_TIME_ZONE_DISABLED ); 9219 } else { 9220 mService.setAutoTimeZoneEnabled(admin, mContext.getPackageName(), enabled); 9221 } 9222 } catch (RemoteException e) { 9223 throw e.rethrowFromSystemServer(); 9224 } 9225 } 9226 } 9227 9228 /** 9229 * Returns true if auto time zone is enabled on the device. 9230 * 9231 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 9232 * caller is not a device admin. 9233 * @return true if auto time zone is enabled on the device. 9234 * @throws SecurityException if caller is not a device owner, a profile owner for the 9235 * primary user, or a profile owner of an organization-owned managed profile. 9236 */ 9237 @RequiresPermission(anyOf = {SET_TIME_ZONE, QUERY_ADMIN_POLICY}, conditional = true) getAutoTimeZoneEnabled(@ullable ComponentName admin)9238 public boolean getAutoTimeZoneEnabled(@Nullable ComponentName admin) { 9239 throwIfParentInstance("getAutoTimeZone"); 9240 if (mService != null) { 9241 try { 9242 return mService.getAutoTimeZoneEnabled(admin, mContext.getPackageName()); 9243 } catch (RemoteException e) { 9244 throw e.rethrowFromSystemServer(); 9245 } 9246 } 9247 return false; 9248 } 9249 9250 /** 9251 * Specifies that the auto time zone state is not controlled by device policy. 9252 * 9253 * @see #setAutoTimeZonePolicy(int) 9254 */ 9255 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ZONE_ENABLED_COEXISTENCE) 9256 public static final int AUTO_TIME_ZONE_NOT_CONTROLLED_BY_POLICY = 0; 9257 9258 /** 9259 * Specifies the "disabled" auto time zone state. 9260 * 9261 * @see #setAutoTimeZonePolicy(int) 9262 */ 9263 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ZONE_ENABLED_COEXISTENCE) 9264 public static final int AUTO_TIME_ZONE_DISABLED = 1; 9265 9266 /** 9267 * Specifies the "enabled" auto time zone state. 9268 * 9269 * @see #setAutoTimeZonePolicy(int) 9270 */ 9271 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ZONE_ENABLED_COEXISTENCE) 9272 public static final int AUTO_TIME_ZONE_ENABLED = 2; 9273 9274 /** 9275 * Flags supplied to {@link #setAutoTimeZonePolicy}(int)}. 9276 * 9277 * @hide 9278 */ 9279 @Retention(RetentionPolicy.SOURCE) 9280 @IntDef(prefix = { "AUTO_TIME_ZONE_" }, value = { 9281 AUTO_TIME_ZONE_NOT_CONTROLLED_BY_POLICY, 9282 AUTO_TIME_ZONE_DISABLED, 9283 AUTO_TIME_ZONE_ENABLED 9284 }) 9285 public @interface AutoTimeZonePolicy {} 9286 9287 /** 9288 * Called by a device owner, a profile owner for the primary user or a profile owner of an 9289 * organization-owned managed profile to turn auto time zone on and off. 9290 * <p> 9291 * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to prevent the 9292 * user from changing this setting, that way no user will be able set the date and time zone. 9293 * 9294 * @param policy The desired state among {@link #AUTO_TIME_ZONE_ENABLED} to enable it, 9295 * {@link #AUTO_TIME_ZONE_DISABLED} to disable it or 9296 * {@link #AUTO_TIME_ZONE_NOT_CONTROLLED_BY_POLICY} to unset the policy. 9297 * @throws SecurityException if caller is not a device owner, a profile owner for the primary 9298 * user, or a profile owner of an organization-owned managed profile, or if the caller does not 9299 * hold the required permission. 9300 */ 9301 @SupportsCoexistence 9302 @RequiresPermission(value = SET_TIME_ZONE, conditional = true) 9303 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ZONE_ENABLED_COEXISTENCE) setAutoTimeZonePolicy(@utoTimeZonePolicy int policy)9304 public void setAutoTimeZonePolicy(@AutoTimeZonePolicy int policy) { 9305 throwIfParentInstance("setAutoTimeZonePolicy"); 9306 if (mService != null) { 9307 try { 9308 mService.setAutoTimeZonePolicy(mContext.getPackageName(), policy); 9309 } catch (RemoteException e) { 9310 throw e.rethrowFromSystemServer(); 9311 } 9312 } 9313 } 9314 9315 /** 9316 * Returns auto time zone policy's current state. 9317 * 9318 * @return One of {@link #AUTO_TIME_ZONE_ENABLED} if enabled, {@link #AUTO_TIME_ZONE_DISABLED} 9319 * if disabled and {@link #AUTO_TIME_ZONE_NOT_CONTROLLED_BY_POLICY} if the state is not 9320 * controlled by policy. 9321 * @throws SecurityException if caller is not a device owner, a profile owner for the 9322 * primary user, or a profile owner of an organization-owned managed profile, or if the caller 9323 * does not hold the required permission. 9324 */ 9325 @SupportsCoexistence 9326 @RequiresPermission(anyOf = {SET_TIME_ZONE, QUERY_ADMIN_POLICY}, conditional = true) 9327 @FlaggedApi(Flags.FLAG_SET_AUTO_TIME_ZONE_ENABLED_COEXISTENCE) getAutoTimeZonePolicy()9328 public @AutoTimeZonePolicy int getAutoTimeZonePolicy() { 9329 throwIfParentInstance("getAutoTimeZonePolicy"); 9330 if (mService != null) { 9331 try { 9332 return mService.getAutoTimeZonePolicy(mContext.getPackageName()); 9333 } catch (RemoteException e) { 9334 throw e.rethrowFromSystemServer(); 9335 } 9336 } 9337 return DevicePolicyManager.AUTO_TIME_ZONE_NOT_CONTROLLED_BY_POLICY; 9338 } 9339 9340 /** 9341 * TODO (b/137101239): remove this method in follow-up CL 9342 * since it's only used for split system user. 9343 * Called by a device owner to set whether all users created on the device should be ephemeral. 9344 * @hide 9345 */ setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)9346 public void setForceEphemeralUsers( 9347 @NonNull ComponentName admin, boolean forceEphemeralUsers) { 9348 throwIfParentInstance("setForceEphemeralUsers"); 9349 if (mService != null) { 9350 try { 9351 mService.setForceEphemeralUsers(admin, forceEphemeralUsers); 9352 } catch (RemoteException e) { 9353 throw e.rethrowFromSystemServer(); 9354 } 9355 } 9356 } 9357 9358 /** 9359 * TODO (b/137101239): remove this method in follow-up CL 9360 * since it's only used for split system user. 9361 * @return true if all users are created ephemeral. 9362 * @throws SecurityException if {@code admin} is not a device owner. 9363 * @hide 9364 */ getForceEphemeralUsers(@onNull ComponentName admin)9365 public boolean getForceEphemeralUsers(@NonNull ComponentName admin) { 9366 throwIfParentInstance("getForceEphemeralUsers"); 9367 if (mService != null) { 9368 try { 9369 return mService.getForceEphemeralUsers(admin); 9370 } catch (RemoteException e) { 9371 throw e.rethrowFromSystemServer(); 9372 } 9373 } 9374 return false; 9375 } 9376 9377 /** 9378 * Called by an application that is administering the device to disable keyguard customizations, 9379 * such as widgets. After setting this, keyguard features will be disabled according to the 9380 * provided feature list. 9381 * <p> 9382 * A calling device admin must have requested 9383 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method; 9384 * if it has not, a security exception will be thrown. 9385 * <p> 9386 * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M} 9387 * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the 9388 * profile owner of a managed profile can set: 9389 * <ul> 9390 * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there 9391 * is no separate challenge set on the managed profile. 9392 * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or 9393 * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if 9394 * there is one, or the parent user otherwise. 9395 * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated 9396 * by applications in the managed profile. 9397 * </ul> 9398 * <p> 9399 * From version {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, the profile owner of a 9400 * managed profile can also set {@link #KEYGUARD_DISABLE_WIDGETS_ALL} which disables keyguard 9401 * widgets for the managed profile. 9402 * <p> 9403 * From version {@link android.os.Build.VERSION_CODES#R} the profile owner of an 9404 * organization-owned managed profile can set: 9405 * <ul> 9406 * <li>{@link #KEYGUARD_DISABLE_SECURE_CAMERA} which affects the parent user when called on the 9407 * parent profile. 9408 * <li>{@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} which affects the parent user when called 9409 * on the parent profile. 9410 * </ul> 9411 * Starting from version {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM} the profile 9412 * owner of an organization-owned managed profile can set: 9413 * <ul> 9414 * <li>{@link #KEYGUARD_DISABLE_WIDGETS_ALL} which affects the parent user when called on the 9415 * parent profile. 9416 * </ul> 9417 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT}, 9418 * {@link #KEYGUARD_DISABLE_FACE}, {@link #KEYGUARD_DISABLE_IRIS}, 9419 * {@link #KEYGUARD_DISABLE_SECURE_CAMERA} and {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} 9420 * can also be set on the {@link DevicePolicyManager} instance returned by 9421 * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent 9422 * profile. {@link #KEYGUARD_DISABLE_SECURE_CAMERA} can only be set on the parent profile 9423 * instance if the calling device admin is the profile owner of an organization-owned 9424 * managed profile. 9425 * <p> 9426 * Requests to disable other features on a managed profile will be ignored. 9427 * <p> 9428 * The admin can check which features have been disabled by calling 9429 * {@link #getKeyguardDisabledFeatures(ComponentName)} 9430 * 9431 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 9432 * caller is not a device admin 9433 * @param which The disabled features flag which can be either 9434 * {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default), 9435 * {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of 9436 * {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA}, 9437 * {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}, 9438 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, 9439 * {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS}, 9440 * {@link #KEYGUARD_DISABLE_FINGERPRINT}, 9441 * {@link #KEYGUARD_DISABLE_FACE}, 9442 * {@link #KEYGUARD_DISABLE_IRIS}, 9443 * {@link #KEYGUARD_DISABLE_SHORTCUTS_ALL}. 9444 * @throws SecurityException if {@code admin} is not an active administrator or does not use 9445 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} 9446 */ 9447 @RequiresPermission(value = MANAGE_DEVICE_POLICY_KEYGUARD, conditional = true) setKeyguardDisabledFeatures(@ullable ComponentName admin, int which)9448 public void setKeyguardDisabledFeatures(@Nullable ComponentName admin, int which) { 9449 if (mService != null) { 9450 try { 9451 mService.setKeyguardDisabledFeatures( 9452 admin, mContext.getPackageName(), which, mParentInstance); 9453 } catch (RemoteException e) { 9454 throw e.rethrowFromSystemServer(); 9455 } 9456 } 9457 } 9458 9459 /** 9460 * Determine whether or not features have been disabled in keyguard either by the calling 9461 * admin, if specified, or all admins that set restrictions on this user and its participating 9462 * profiles. Restrictions on profiles that have a separate challenge are not taken into account. 9463 * 9464 * <p>This method can be called on the {@link DevicePolicyManager} instance 9465 * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve 9466 * restrictions on the parent profile. 9467 * 9468 * @param admin The name of the admin component to check, or {@code null} to check whether any 9469 * admins have disabled features in keyguard. 9470 * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)} 9471 * for a list. 9472 */ getKeyguardDisabledFeatures(@ullable ComponentName admin)9473 public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) { 9474 return getKeyguardDisabledFeatures(admin, myUserId()); 9475 } 9476 9477 private IpcDataCache<Pair<ComponentName, Integer>, Integer> mGetKeyGuardDisabledFeaturesCache = 9478 new IpcDataCache<>(sDpmCaches.child("getKeyguardDisabledFeatures"), 9479 (query) -> getService().getKeyguardDisabledFeatures( 9480 query.first, query.second, isParentInstance())); 9481 9482 /** @hide per-user version */ 9483 @UnsupportedAppUsage getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)9484 public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) { 9485 if (mService != null) { 9486 return mGetKeyGuardDisabledFeaturesCache.query(new Pair<>(admin, userHandle)); 9487 } else { 9488 return KEYGUARD_DISABLE_FEATURES_NONE; 9489 } 9490 } 9491 9492 /** 9493 * @hide 9494 */ 9495 @UnsupportedAppUsage setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)9496 public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) { 9497 setActiveAdmin(policyReceiver, refreshing, myUserId()); 9498 } 9499 9500 /** 9501 * @hide 9502 */ 9503 @TestApi 9504 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 9505 @RequiresPermission(allOf = { 9506 MANAGE_DEVICE_ADMINS, 9507 INTERACT_ACROSS_USERS_FULL 9508 }) setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)9509 public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing, 9510 int userHandle) { 9511 setActiveAdminInternal(policyReceiver, refreshing, userHandle, null); 9512 } 9513 9514 /** 9515 * @hide 9516 */ 9517 @TestApi 9518 @RequiresPermission(allOf = { 9519 MANAGE_DEVICE_ADMINS, 9520 INTERACT_ACROSS_USERS_FULL 9521 }) 9522 @FlaggedApi(Flags.FLAG_PROVISIONING_CONTEXT_PARAMETER) setActiveAdmin( @onNull ComponentName policyReceiver, boolean refreshing, int userHandle, @Nullable String provisioningContext )9523 public void setActiveAdmin( 9524 @NonNull ComponentName policyReceiver, 9525 boolean refreshing, 9526 int userHandle, 9527 @Nullable String provisioningContext 9528 ) { 9529 setActiveAdminInternal(policyReceiver, refreshing, userHandle, provisioningContext); 9530 } 9531 setActiveAdminInternal( @onNull ComponentName policyReceiver, boolean refreshing, int userHandle, @Nullable String provisioningContext )9532 private void setActiveAdminInternal( 9533 @NonNull ComponentName policyReceiver, 9534 boolean refreshing, 9535 int userHandle, 9536 @Nullable String provisioningContext 9537 ) { 9538 if (mService != null) { 9539 try { 9540 mService.setActiveAdmin( 9541 policyReceiver, 9542 refreshing, 9543 userHandle, 9544 provisioningContext 9545 ); 9546 } catch (RemoteException e) { 9547 throw e.rethrowFromSystemServer(); 9548 } 9549 } 9550 } 9551 9552 /** 9553 * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve 9554 * the remove warning for the given device admin. 9555 * @hide 9556 */ getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)9557 public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) { 9558 if (mService != null) { 9559 try { 9560 mService.getRemoveWarning(admin, result, myUserId()); 9561 } catch (RemoteException e) { 9562 throw e.rethrowFromSystemServer(); 9563 } 9564 } 9565 } 9566 9567 /** 9568 * @hide 9569 */ 9570 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId)9571 public void reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId) { 9572 if (mService != null) { 9573 try { 9574 mService.reportPasswordChanged(metrics, userId); 9575 } catch (RemoteException e) { 9576 throw e.rethrowFromSystemServer(); 9577 } 9578 } 9579 } 9580 9581 /** 9582 * @hide 9583 */ 9584 @UnsupportedAppUsage 9585 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) reportFailedPasswordAttempt(int userHandle)9586 public void reportFailedPasswordAttempt(int userHandle) { 9587 if (mService != null) { 9588 try { 9589 mService.reportFailedPasswordAttempt(userHandle, mParentInstance); 9590 } catch (RemoteException e) { 9591 throw e.rethrowFromSystemServer(); 9592 } 9593 } 9594 } 9595 9596 /** 9597 * @hide 9598 */ 9599 @UnsupportedAppUsage 9600 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) reportSuccessfulPasswordAttempt(int userHandle)9601 public void reportSuccessfulPasswordAttempt(int userHandle) { 9602 if (mService != null) { 9603 try { 9604 mService.reportSuccessfulPasswordAttempt(userHandle); 9605 } catch (RemoteException e) { 9606 throw e.rethrowFromSystemServer(); 9607 } 9608 } 9609 } 9610 9611 /** 9612 * @hide 9613 */ 9614 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) reportFailedBiometricAttempt(int userHandle)9615 public void reportFailedBiometricAttempt(int userHandle) { 9616 if (mService != null) { 9617 try { 9618 mService.reportFailedBiometricAttempt(userHandle); 9619 } catch (RemoteException e) { 9620 throw e.rethrowFromSystemServer(); 9621 } 9622 } 9623 } 9624 9625 /** 9626 * @hide 9627 */ 9628 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) reportSuccessfulBiometricAttempt(int userHandle)9629 public void reportSuccessfulBiometricAttempt(int userHandle) { 9630 if (mService != null) { 9631 try { 9632 mService.reportSuccessfulBiometricAttempt(userHandle); 9633 } catch (RemoteException e) { 9634 throw e.rethrowFromSystemServer(); 9635 } 9636 } 9637 } 9638 9639 /** 9640 * Should be called when keyguard has been dismissed. 9641 * @hide 9642 */ reportKeyguardDismissed(int userHandle)9643 public void reportKeyguardDismissed(int userHandle) { 9644 if (mService != null) { 9645 try { 9646 mService.reportKeyguardDismissed(userHandle); 9647 } catch (RemoteException e) { 9648 throw e.rethrowFromSystemServer(); 9649 } 9650 } 9651 } 9652 9653 /** 9654 * Should be called when keyguard view has been shown to the user. 9655 * @hide 9656 */ reportKeyguardSecured(int userHandle)9657 public void reportKeyguardSecured(int userHandle) { 9658 if (mService != null) { 9659 try { 9660 mService.reportKeyguardSecured(userHandle); 9661 } catch (RemoteException e) { 9662 throw e.rethrowFromSystemServer(); 9663 } 9664 } 9665 } 9666 9667 /** 9668 * Sets the given package as the device owner. 9669 * 9670 * <p>Preconditions: 9671 * <ul> 9672 * <li>The package must already be installed. 9673 * <li>There must not already be a device owner. 9674 * <li>Only apps with the {@code MANAGE_PROFILE_AND_DEVICE_OWNERS} permission or the 9675 * {@link Process#SHELL_UID Shell UID} can call this method. 9676 * </ul> 9677 * 9678 * <p>Calling this after the setup phase of the device owner user has completed is allowed only 9679 * if the caller is the {@link Process#SHELL_UID Shell UID}, and there are no additional users 9680 * (except when the device runs on headless system user mode, in which case it could have exact 9681 * one extra user, which is the current user. 9682 * 9683 * <p>On a headless devices, if it is in affiliated mode the device owner will be set in the 9684 * {@link UserHandle#SYSTEM system} user. If the device is in single user mode, the device owner 9685 * will be set in the first secondary user. 9686 * 9687 * @param who the component name to be registered as device owner. 9688 * @param userId ID of the user on which the device owner runs. 9689 * 9690 * @return whether the package was successfully registered as the device owner. 9691 * 9692 * @throws IllegalArgumentException if the package name is {@code null} or invalid. 9693 * @throws IllegalStateException If the preconditions mentioned are not met. 9694 * 9695 * @hide 9696 */ 9697 @TestApi 9698 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) setDeviceOwner(@onNull ComponentName who, @UserIdInt int userId)9699 public boolean setDeviceOwner(@NonNull ComponentName who, @UserIdInt int userId) { 9700 if (mService != null) { 9701 try { 9702 return mService.setDeviceOwner(who, userId, 9703 /* setProfileOwnerOnCurrentUserIfNecessary= */ true); 9704 } catch (RemoteException re) { 9705 throw re.rethrowFromSystemServer(); 9706 } 9707 } 9708 return false; 9709 } 9710 9711 /** 9712 * Same as {@link #setDeviceOwner(ComponentName, int)}, but without setting the profile 9713 * owner on current user when running on headless system user mode - should be used only by 9714 * testing infra. 9715 * 9716 * @hide 9717 */ 9718 @TestApi 9719 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) setDeviceOwnerOnly( @onNull ComponentName who, @UserIdInt int userId)9720 public boolean setDeviceOwnerOnly( 9721 @NonNull ComponentName who, @UserIdInt int userId) { 9722 if (mService != null) { 9723 try { 9724 return mService.setDeviceOwner(who, userId, 9725 /* setProfileOwnerOnCurrentUserIfNecessary= */ false); 9726 } catch (RemoteException re) { 9727 throw re.rethrowFromSystemServer(); 9728 } 9729 } 9730 return false; 9731 } 9732 9733 /** 9734 * For apps targeting {@link Build.VERSION_CODES#VANILLA_ICE_CREAM} and above, the 9735 * {@link #isDeviceOwnerApp} method will use the user contained within the 9736 * context. 9737 * For apps targeting an SDK version <em>below</em> this, the user of the calling process will 9738 * be used (Process.myUserHandle()). 9739 * 9740 * @hide 9741 */ 9742 @ChangeId 9743 @EnabledSince(targetSdkVersion = Build.VERSION_CODES.VANILLA_ICE_CREAM) 9744 public static final long IS_DEVICE_OWNER_USER_AWARE = 307233716L; 9745 9746 /** 9747 * Used to determine if a particular package has been registered as a Device Owner app. 9748 * A device owner app is a special device admin that cannot be deactivated by the user, once 9749 * activated as a device admin. It also cannot be uninstalled. To check whether a particular 9750 * package is currently registered as the device owner app, pass in the package name from 9751 * {@link Context#getPackageName()} to this method.<p/>This is useful for device 9752 * admin apps that want to check whether they are also registered as the device owner app. The 9753 * exact mechanism by which a device admin app is registered as a device owner app is defined by 9754 * the setup process. 9755 * @param packageName the package name of the app, to compare with the registered device owner 9756 * app, if any. 9757 * @return whether or not the package is registered as the device owner app. 9758 */ 9759 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.VANILLA_ICE_CREAM) isDeviceOwnerApp(String packageName)9760 public boolean isDeviceOwnerApp(String packageName) { 9761 throwIfParentInstance("isDeviceOwnerApp"); 9762 if (android.permission.flags.Flags.systemServerRoleControllerEnabled() 9763 && CompatChanges.isChangeEnabled(IS_DEVICE_OWNER_USER_AWARE)) { 9764 return isDeviceOwnerAppOnContextUser(packageName); 9765 } 9766 return isDeviceOwnerAppOnCallingUser(packageName); 9767 } 9768 9769 /** 9770 * @return true if a package is registered as device owner, only when it's running on the 9771 * calling user. 9772 * 9773 * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity. 9774 * @hide 9775 */ isDeviceOwnerAppOnCallingUser(String packageName)9776 public boolean isDeviceOwnerAppOnCallingUser(String packageName) { 9777 return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true); 9778 } 9779 9780 /** 9781 * @return true if a package is registered as device owner, even if it's running on a different 9782 * user. 9783 * 9784 * <p>Requires the MANAGE_USERS permission. 9785 * 9786 * @hide 9787 */ isDeviceOwnerAppOnAnyUser(String packageName)9788 public boolean isDeviceOwnerAppOnAnyUser(String packageName) { 9789 return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false); 9790 } 9791 9792 /** 9793 * @return device owner component name, only when it's running on the calling user. 9794 * 9795 * @hide 9796 */ getDeviceOwnerComponentOnCallingUser()9797 public ComponentName getDeviceOwnerComponentOnCallingUser() { 9798 return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true); 9799 } 9800 9801 /** 9802 * @return device owner component name, even if it's running on a different user. 9803 * 9804 * @hide 9805 */ 9806 @SystemApi 9807 @RequiresPermission(anyOf = { 9808 android.Manifest.permission.MANAGE_USERS, 9809 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS 9810 }) getDeviceOwnerComponentOnAnyUser()9811 public ComponentName getDeviceOwnerComponentOnAnyUser() { 9812 return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false); 9813 } 9814 isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)9815 private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) { 9816 if (packageName == null) { 9817 return false; 9818 } 9819 final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly); 9820 if (deviceOwner == null) { 9821 return false; 9822 } 9823 return packageName.equals(deviceOwner.getPackageName()); 9824 } 9825 isDeviceOwnerAppOnContextUser(String packageName)9826 private boolean isDeviceOwnerAppOnContextUser(String packageName) { 9827 if (packageName == null) { 9828 return false; 9829 } 9830 ComponentName deviceOwner = null; 9831 if (mService != null) { 9832 try { 9833 deviceOwner = mService.getDeviceOwnerComponentOnUser(myUserId()); 9834 } catch (RemoteException re) { 9835 throw re.rethrowFromSystemServer(); 9836 } 9837 } 9838 if (deviceOwner == null) { 9839 return false; 9840 } 9841 return packageName.equals(deviceOwner.getPackageName()); 9842 } 9843 getDeviceOwnerComponentInner(boolean callingUserOnly)9844 private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) { 9845 if (mService != null) { 9846 try { 9847 return mService.getDeviceOwnerComponent(callingUserOnly); 9848 } catch (RemoteException re) { 9849 throw re.rethrowFromSystemServer(); 9850 } 9851 } 9852 return null; 9853 } 9854 9855 /** 9856 * @return Handle of the user who runs device owner, or {@code null} if there's no device owner. 9857 * 9858 * @hide 9859 */ 9860 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) 9861 @SystemApi getDeviceOwnerUser()9862 public @Nullable UserHandle getDeviceOwnerUser() { 9863 if (mService != null) { 9864 try { 9865 int userId = mService.getDeviceOwnerUserId(); 9866 9867 if (userId != UserHandle.USER_NULL) { 9868 return UserHandle.of(userId); 9869 } 9870 } catch (RemoteException re) { 9871 throw re.rethrowFromSystemServer(); 9872 } 9873 } 9874 return null; 9875 } 9876 9877 /** 9878 * @hide 9879 */ getDeviceOwnerUserId()9880 public int getDeviceOwnerUserId() { 9881 if (mService != null) { 9882 try { 9883 return mService.getDeviceOwnerUserId(); 9884 } catch (RemoteException re) { 9885 throw re.rethrowFromSystemServer(); 9886 } 9887 } 9888 return UserHandle.USER_NULL; 9889 } 9890 9891 /** 9892 * Clears the current device owner. The caller must be the device owner. This function should be 9893 * used cautiously as once it is called it cannot be undone. The device owner can only be set as 9894 * a part of device setup, before it completes. 9895 * <p> 9896 * While some policies previously set by the device owner will be cleared by this method, it is 9897 * a best-effort process and some other policies will still remain in place after the device 9898 * owner is cleared. 9899 * 9900 * @param packageName The package name of the device owner. 9901 * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName} 9902 * does not own the current device owner component. 9903 * 9904 * @deprecated This method is expected to be used for testing purposes only. The device owner 9905 * will lose control of the device and its data after calling it. In order to protect any 9906 * sensitive data that remains on the device, it is advised that the device owner factory resets 9907 * the device instead of calling this method. See {@link #wipeData(int)}. 9908 */ 9909 @Deprecated clearDeviceOwnerApp(String packageName)9910 public void clearDeviceOwnerApp(String packageName) { 9911 throwIfParentInstance("clearDeviceOwnerApp"); 9912 if (mService != null) { 9913 try { 9914 mService.clearDeviceOwner(packageName); 9915 } catch (RemoteException re) { 9916 throw re.rethrowFromSystemServer(); 9917 } 9918 } 9919 } 9920 9921 /** 9922 * Returns the device owner package name, only if it's running on the calling user. 9923 * 9924 * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity. 9925 * 9926 * @hide 9927 */ 9928 @SystemApi 9929 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) getDeviceOwner()9930 public @Nullable String getDeviceOwner() { 9931 throwIfParentInstance("getDeviceOwner"); 9932 final ComponentName name = getDeviceOwnerComponentOnCallingUser(); 9933 return name != null ? name.getPackageName() : null; 9934 } 9935 9936 private IpcDataCache<Void, Boolean> mHasDeviceOwnerCache = 9937 new IpcDataCache<>(sDpmCaches.child("hasDeviceOwner"), 9938 (query) -> getService().hasDeviceOwner()); 9939 9940 /** 9941 * Called by the system to find out whether the device is managed by a Device Owner. 9942 * 9943 * @return whether the device is managed by a Device Owner. 9944 * @throws SecurityException if the caller is not the device owner, does not hold 9945 * MANAGE_USERS or MANAGE_PROFILE_AND_DEVICE_OWNERS permissions and is not the system. 9946 * 9947 * @hide 9948 */ 9949 @SystemApi 9950 @SuppressLint("RequiresPermission") isDeviceManaged()9951 public boolean isDeviceManaged() { 9952 return mHasDeviceOwnerCache.query(null); 9953 } 9954 9955 /** 9956 * Returns the device owner name. Note this method *will* return the device owner 9957 * name when it's running on a different user. 9958 * 9959 * @hide 9960 */ 9961 @SystemApi 9962 @RequiresPermission(anyOf = { 9963 android.Manifest.permission.MANAGE_USERS, 9964 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS 9965 }) getDeviceOwnerNameOnAnyUser()9966 public String getDeviceOwnerNameOnAnyUser() { 9967 throwIfParentInstance("getDeviceOwnerNameOnAnyUser"); 9968 if (mService != null) { 9969 try { 9970 return mService.getDeviceOwnerName(); 9971 } catch (RemoteException re) { 9972 throw re.rethrowFromSystemServer(); 9973 } 9974 } 9975 return null; 9976 } 9977 9978 /** 9979 * @hide 9980 * @deprecated Use #ACTION_SET_PROFILE_OWNER 9981 * Sets the given component as an active admin and registers the package as the profile 9982 * owner for this user. The package must already be installed and there shouldn't be 9983 * an existing profile owner registered for this user. Also, this method must be called 9984 * before the user setup has been completed. 9985 * <p> 9986 * This method can only be called by system apps that hold MANAGE_USERS permission and 9987 * MANAGE_DEVICE_ADMINS permission. 9988 * @param admin The component to register as an active admin and profile owner. 9989 * @param ownerName The user-visible name of the entity that is managing this user. 9990 * @return whether the admin was successfully registered as the profile owner. 9991 * @throws IllegalArgumentException if packageName is null, the package isn't installed, or 9992 * the user has already been set up. 9993 */ 9994 @Deprecated 9995 @SystemApi 9996 @RequiresPermission(MANAGE_DEVICE_ADMINS) setActiveProfileOwner(@onNull ComponentName admin, String ownerName)9997 public boolean setActiveProfileOwner(@NonNull ComponentName admin, String ownerName) 9998 throws IllegalArgumentException { 9999 throwIfParentInstance("setActiveProfileOwner"); 10000 if (mService != null) { 10001 try { 10002 final int myUserId = myUserId(); 10003 mService.setActiveAdmin(admin, false, myUserId, null); 10004 return mService.setProfileOwner(admin, myUserId); 10005 } catch (RemoteException re) { 10006 throw re.rethrowFromSystemServer(); 10007 } 10008 } 10009 return false; 10010 } 10011 10012 /** 10013 * Clears the active profile owner. The caller must be the profile owner of this user, otherwise 10014 * a SecurityException will be thrown. This method is not available to managed profile owners. 10015 * <p> 10016 * While some policies previously set by the profile owner will be cleared by this method, it is 10017 * a best-effort process and some other policies will still remain in place after the profile 10018 * owner is cleared. 10019 * 10020 * @param admin The component to remove as the profile owner. 10021 * @throws SecurityException if {@code admin} is not an active profile owner, or the method is 10022 * being called from a managed profile. 10023 * 10024 * @deprecated This method is expected to be used for testing purposes only. The profile owner 10025 * will lose control of the user and its data after calling it. In order to protect any 10026 * sensitive data that remains on this user, it is advised that the profile owner deletes it 10027 * instead of calling this method. See {@link #wipeData(int)}. 10028 */ 10029 @Deprecated clearProfileOwner(@onNull ComponentName admin)10030 public void clearProfileOwner(@NonNull ComponentName admin) { 10031 throwIfParentInstance("clearProfileOwner"); 10032 if (mService != null) { 10033 try { 10034 mService.clearProfileOwner(admin); 10035 } catch (RemoteException re) { 10036 throw re.rethrowFromSystemServer(); 10037 } 10038 } 10039 } 10040 10041 /** 10042 * @hide 10043 * Checks whether the user was already setup. 10044 */ hasUserSetupCompleted()10045 public boolean hasUserSetupCompleted() { 10046 if (mService != null) { 10047 try { 10048 return mService.hasUserSetupCompleted(); 10049 } catch (RemoteException re) { 10050 throw re.rethrowFromSystemServer(); 10051 } 10052 } 10053 return true; 10054 } 10055 10056 /** 10057 * @hide 10058 * Sets the given component as the profile owner of the given user profile. The package must 10059 * already be installed. There must not already be a profile owner for this user. 10060 * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call 10061 * this method. 10062 * Calling this after the setup phase of the specified user has completed is allowed only if: 10063 * - the caller is SYSTEM_UID. 10064 * - or the caller is the shell uid, and there are no accounts on the specified user. 10065 * @param admin the component name to be registered as profile owner. 10066 * @param userHandle the userId to set the profile owner for. 10067 * @return whether the component was successfully registered as the profile owner. 10068 * @throws IllegalArgumentException if admin is null, the package isn't installed, or the 10069 * preconditions mentioned are not met. 10070 */ setProfileOwner(@onNull ComponentName admin, int userHandle)10071 public boolean setProfileOwner(@NonNull ComponentName admin, int userHandle) 10072 throws IllegalArgumentException { 10073 if (mService != null) { 10074 try { 10075 return mService.setProfileOwner(admin, userHandle); 10076 } catch (RemoteException re) { 10077 throw re.rethrowFromSystemServer(); 10078 } 10079 } 10080 return false; 10081 } 10082 10083 /** 10084 * Sets the device owner information to be shown on the lock screen. 10085 * <p> 10086 * Device owner information set using this method overrides any owner information manually set 10087 * by the user and prevents the user from further changing it. 10088 * <p> 10089 * If the device owner information is {@code null} or empty then the device owner info is 10090 * cleared and the user owner info is shown on the lock screen if it is set. 10091 * <p> 10092 * If the device owner information contains only whitespaces then the message on the lock screen 10093 * will be blank and the user will not be allowed to change it. 10094 * <p> 10095 * If the device owner information needs to be localized, it is the responsibility of the 10096 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast 10097 * and set a new version of this string accordingly. 10098 * <p> 10099 * May be called by the device owner or the profile owner of an organization-owned device. 10100 * 10101 * @param admin The name of the admin component to check. 10102 * @param info Device owner information which will be displayed instead of the user owner info. 10103 * @throws SecurityException if {@code admin} is not a device owner. 10104 */ setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)10105 public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) { 10106 throwIfParentInstance("setDeviceOwnerLockScreenInfo"); 10107 if (mService != null) { 10108 try { 10109 mService.setDeviceOwnerLockScreenInfo(admin, info); 10110 } catch (RemoteException re) { 10111 throw re.rethrowFromSystemServer(); 10112 } 10113 } 10114 } 10115 10116 /** 10117 * @return The device owner information. If it is not set returns {@code null}. 10118 */ getDeviceOwnerLockScreenInfo()10119 public CharSequence getDeviceOwnerLockScreenInfo() { 10120 throwIfParentInstance("getDeviceOwnerLockScreenInfo"); 10121 if (mService != null) { 10122 try { 10123 return mService.getDeviceOwnerLockScreenInfo(); 10124 } catch (RemoteException re) { 10125 throw re.rethrowFromSystemServer(); 10126 } 10127 } 10128 return null; 10129 } 10130 10131 /** 10132 * Called by device or profile owners to suspend packages for this user. This function can be 10133 * called by a device owner, profile owner, or by a delegate given the 10134 * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}. 10135 * <p> 10136 * A suspended package will not be able to start activities. Its notifications will be hidden, 10137 * it will not show up in recents, will not be able to show toasts or dialogs or ring the 10138 * device. 10139 * <p> 10140 * The package must already be installed. If the package is uninstalled while suspended the 10141 * package will no longer be suspended. The admin can block this by using 10142 * {@link #setUninstallBlocked}. 10143 * 10144 * <p>Some apps cannot be suspended, such as device admins, the active launcher, the required 10145 * package installer, the required package uninstaller, the required package verifier, the 10146 * default dialer, and the permission controller. 10147 * 10148 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 10149 * caller is not a device admin. 10150 * @param packageNames The package names to suspend or unsuspend. 10151 * @param suspended If set to {@code true} than the packages will be suspended, if set to 10152 * {@code false} the packages will be unsuspended. 10153 * @return an array of package names for which the suspended status is not set as requested in 10154 * this method. 10155 * @throws SecurityException if {@code admin} is not a device or profile owner. 10156 * @see #setDelegatedScopes 10157 * @see #DELEGATION_PACKAGE_ACCESS 10158 */ 10159 @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true) 10160 @NonNull setPackagesSuspended(@ullable ComponentName admin, @NonNull String[] packageNames, boolean suspended)10161 public String[] setPackagesSuspended(@Nullable ComponentName admin, 10162 @NonNull String[] packageNames, boolean suspended) { 10163 throwIfParentInstance("setPackagesSuspended"); 10164 if (mService != null) { 10165 try { 10166 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames, 10167 suspended); 10168 } catch (RemoteException re) { 10169 throw re.rethrowFromSystemServer(); 10170 } 10171 } 10172 return packageNames; 10173 } 10174 10175 /** 10176 * Determine if a package is suspended. This function can be called by a device owner, profile 10177 * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via 10178 * {@link #setDelegatedScopes} or by holders of the permission 10179 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PACKAGE_STATE}. 10180 * 10181 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 10182 * caller is not a device admin. 10183 * @param packageName The name of the package to retrieve the suspended status of. 10184 * @return {@code true} if the package is suspended or {@code false} if the package is not 10185 * suspended, could not be found or an error occurred. 10186 * @throws SecurityException if {@code admin} is not a device or profile owner or has not been 10187 * granted the permission 10188 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PACKAGE_STATE}. 10189 * @throws NameNotFoundException if the package could not be found. 10190 * @see #setDelegatedScopes 10191 * @see #DELEGATION_PACKAGE_ACCESS 10192 */ 10193 @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true) isPackageSuspended(@ullable ComponentName admin, String packageName)10194 public boolean isPackageSuspended(@Nullable ComponentName admin, String packageName) 10195 throws NameNotFoundException { 10196 throwIfParentInstance("isPackageSuspended"); 10197 if (mService != null) { 10198 try { 10199 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName); 10200 } catch (RemoteException e) { 10201 throw e.rethrowFromSystemServer(); 10202 } catch (IllegalArgumentException ex) { 10203 Log.e(TAG, "IllegalArgumentException checking isPackageSuspended", ex); 10204 throw new NameNotFoundException(packageName); 10205 } 10206 } 10207 return false; 10208 } 10209 10210 /** 10211 * Sets the enabled state of the profile. A profile should be enabled only once it is ready to 10212 * be used. Only the profile owner can call this. 10213 * 10214 * @see #isProfileOwnerApp 10215 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 10216 * @throws SecurityException if {@code admin} is not a profile owner. 10217 */ setProfileEnabled(@onNull ComponentName admin)10218 public void setProfileEnabled(@NonNull ComponentName admin) { 10219 throwIfParentInstance("setProfileEnabled"); 10220 if (mService != null) { 10221 try { 10222 mService.setProfileEnabled(admin); 10223 } catch (RemoteException e) { 10224 throw e.rethrowFromSystemServer(); 10225 } 10226 } 10227 } 10228 10229 /** 10230 * Sets the name of the profile. In the device owner case it sets the name of the user which it 10231 * is called from. Only a profile owner or device owner can call this. If this is never called 10232 * by the profile or device owner, the name will be set to default values. 10233 * 10234 * @see #isProfileOwnerApp 10235 * @see #isDeviceOwnerApp 10236 * @param admin Which {@link DeviceAdminReceiver} this request is associate with. 10237 * @param profileName The name of the profile. If the name is longer than 200 characters 10238 * it will be truncated. 10239 * @throws SecurityException if {@code admin} is not a device or profile owner. 10240 */ setProfileName(@onNull ComponentName admin, String profileName)10241 public void setProfileName(@NonNull ComponentName admin, String profileName) { 10242 throwIfParentInstance("setProfileName"); 10243 if (mService != null) { 10244 try { 10245 mService.setProfileName(admin, profileName); 10246 } catch (RemoteException e) { 10247 throw e.rethrowFromSystemServer(); 10248 } 10249 } 10250 } 10251 10252 /** 10253 * Used to determine if a particular package is registered as the profile owner for the 10254 * user. A profile owner is a special device admin that has additional privileges 10255 * within the profile. 10256 * 10257 * @param packageName The package name of the app to compare with the registered profile owner. 10258 * @return Whether or not the package is registered as the profile owner. 10259 */ 10260 @UserHandleAware isProfileOwnerApp(String packageName)10261 public boolean isProfileOwnerApp(String packageName) { 10262 throwIfParentInstance("isProfileOwnerApp"); 10263 if (mService != null) { 10264 try { 10265 ComponentName profileOwner = mService.getProfileOwnerAsUser(myUserId()); 10266 return profileOwner != null 10267 && profileOwner.getPackageName().equals(packageName); 10268 } catch (RemoteException re) { 10269 throw re.rethrowFromSystemServer(); 10270 } 10271 } 10272 return false; 10273 } 10274 10275 /** 10276 * @hide 10277 * @return the packageName of the owner of the given user profile or {@code null} if no profile 10278 * owner has been set for that user. 10279 * @throws IllegalArgumentException if the userId is invalid. 10280 */ 10281 @SystemApi getProfileOwner()10282 public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException { 10283 throwIfParentInstance("getProfileOwner"); 10284 return getProfileOwnerAsUser(mContext.getUserId()); 10285 } 10286 10287 /** 10288 * @see #getProfileOwner() 10289 * @hide 10290 */ 10291 @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS, 10292 conditional = true) getProfileOwnerAsUser(@onNull UserHandle user)10293 public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) { 10294 if (mService != null) { 10295 try { 10296 return mService.getProfileOwnerAsUser(user.getIdentifier()); 10297 } catch (RemoteException re) { 10298 throw re.rethrowFromSystemServer(); 10299 } 10300 } 10301 return null; 10302 } 10303 10304 /** 10305 * @hide 10306 */ 10307 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) getProfileOwnerAsUser(final int userId)10308 public @Nullable ComponentName getProfileOwnerAsUser(final int userId) { 10309 if (mService != null) { 10310 try { 10311 return mService.getProfileOwnerAsUser(userId); 10312 } catch (RemoteException re) { 10313 throw re.rethrowFromSystemServer(); 10314 } 10315 } 10316 return null; 10317 } 10318 10319 private final IpcDataCache<UserHandle, ComponentName> 10320 mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache = 10321 new IpcDataCache<>(sDpmCaches.child("getProfileOwnerOrDeviceOwnerSupervisionComponent"), 10322 (arg) -> getService().getProfileOwnerOrDeviceOwnerSupervisionComponent(arg)); 10323 10324 /** 10325 * Returns the configured supervision app if it exists and is the device owner or policy owner. 10326 * @hide 10327 */ getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle user)10328 public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent( 10329 @NonNull UserHandle user) { 10330 if (mService != null) { 10331 return mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache.query(user); 10332 } 10333 return null; 10334 } 10335 10336 /** 10337 * Checks if the specified component is the supervision component. 10338 * @hide 10339 */ isSupervisionComponent(@onNull ComponentName who)10340 public boolean isSupervisionComponent(@NonNull ComponentName who) { 10341 if (mService != null) { 10342 try { 10343 return getService().isSupervisionComponent(who); 10344 } catch (RemoteException re) { 10345 throw re.rethrowFromSystemServer(); 10346 } 10347 } 10348 return false; 10349 } 10350 10351 /** 10352 * @hide 10353 * @return the human readable name of the organisation associated with this DPM or {@code null} 10354 * if one is not set. 10355 * @throws IllegalArgumentException if the userId is invalid. 10356 */ getProfileOwnerName()10357 public @Nullable String getProfileOwnerName() throws IllegalArgumentException { 10358 if (mService != null) { 10359 try { 10360 return mService.getProfileOwnerName(mContext.getUserId()); 10361 } catch (RemoteException re) { 10362 throw re.rethrowFromSystemServer(); 10363 } 10364 } 10365 return null; 10366 } 10367 10368 /** 10369 * @hide 10370 * @param userId The user for whom to fetch the profile owner name, if any. 10371 * @return the human readable name of the organisation associated with this profile owner or 10372 * null if one is not set. 10373 * @throws IllegalArgumentException if the userId is invalid. 10374 */ 10375 @SystemApi 10376 @RequiresPermission(anyOf = { 10377 android.Manifest.permission.MANAGE_USERS, 10378 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS 10379 }) getProfileOwnerNameAsUser(int userId)10380 public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException { 10381 throwIfParentInstance("getProfileOwnerNameAsUser"); 10382 if (mService != null) { 10383 try { 10384 return mService.getProfileOwnerName(userId); 10385 } catch (RemoteException re) { 10386 throw re.rethrowFromSystemServer(); 10387 } 10388 } 10389 return null; 10390 } 10391 10392 private final IpcDataCache<Void, Boolean> mIsOrganizationOwnedDeviceWithManagedProfileCache = 10393 new IpcDataCache(sDpmCaches.child("isOrganizationOwnedDeviceWithManagedProfile"), 10394 (query) -> getService().isOrganizationOwnedDeviceWithManagedProfile()); 10395 10396 /** 10397 * Apps can use this method to find out if the device was provisioned as 10398 * organization-owend device with a managed profile. 10399 * 10400 * This, together with checking whether the device has a device owner (by calling 10401 * {@link #isDeviceOwnerApp}), could be used to learn whether the device is owned by an 10402 * organization or an individual: 10403 * If this method returns true OR {@link #isDeviceOwnerApp} returns true (for any package), 10404 * then the device is owned by an organization. Otherwise, it's owned by an individual. 10405 * 10406 * @return {@code true} if the device was provisioned as organization-owned device, 10407 * {@code false} otherwise. 10408 */ isOrganizationOwnedDeviceWithManagedProfile()10409 public boolean isOrganizationOwnedDeviceWithManagedProfile() { 10410 throwIfParentInstance("isOrganizationOwnedDeviceWithManagedProfile"); 10411 if (mService != null) { 10412 return mIsOrganizationOwnedDeviceWithManagedProfileCache.query(null); 10413 } 10414 return false; 10415 } 10416 10417 /** 10418 * Returns whether the specified package can read the device identifiers. 10419 * 10420 * @param packageName The package name of the app to check for device identifier access. 10421 * @param pid The process id of the package to be checked. 10422 * @param uid The uid of the package to be checked. 10423 * @return whether the package can read the device identifiers. 10424 * 10425 * @hide 10426 */ hasDeviceIdentifierAccess(@onNull String packageName, int pid, int uid)10427 public boolean hasDeviceIdentifierAccess(@NonNull String packageName, int pid, int uid) { 10428 throwIfParentInstance("hasDeviceIdentifierAccess"); 10429 if (packageName == null) { 10430 return false; 10431 } 10432 if (mService != null) { 10433 try { 10434 return mService.checkDeviceIdentifierAccess(packageName, pid, uid); 10435 } catch (RemoteException re) { 10436 throw re.rethrowFromSystemServer(); 10437 } 10438 } 10439 return false; 10440 } 10441 10442 /** 10443 * Called by a profile owner or device owner or holder of the permission 10444 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. to set a default activity 10445 * that the system selects to handle intents that match the given {@link IntentFilter} instead 10446 * of showing the default disambiguation mechanism. 10447 * This activity will remain the default intent handler even if the set of potential event 10448 * handlers for the intent filter changes and if the intent preferences are reset. 10449 * <p> 10450 * Note that the target application should still declare the activity in the manifest, the API 10451 * just sets the activity to be the default one to handle the given intent filter. 10452 * <p> 10453 * The default disambiguation mechanism takes over if the activity is not installed (anymore). 10454 * When the activity is (re)installed, it is automatically reset as default intent handler for 10455 * the filter. 10456 * <p> 10457 * Note that calling this API to set a default intent handler, only allow to avoid the default 10458 * disambiguation mechanism. Implicit intents that do not trigger this mechanism (like invoking 10459 * the browser) cannot be configured as they are controlled by other configurations. 10460 * <p> 10461 * The calling device admin must be a profile owner or device owner. If it is not, a security 10462 * exception will be thrown. 10463 * <p> 10464 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the persistent preferred 10465 * activity policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 10466 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 10467 * successfully set or not. This callback will contain: 10468 * <ul> 10469 * <li> The policy identifier 10470 * {@link DevicePolicyIdentifiers#PERSISTENT_PREFERRED_ACTIVITY_POLICY} 10471 * <li> The additional policy params bundle, which contains 10472 * {@link PolicyUpdateReceiver#EXTRA_INTENT_FILTER} the intent filter the policy applies to 10473 * <li> The {@link TargetUser} that this policy relates to 10474 * <li> The {@link PolicyUpdateResult}, which will be 10475 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 10476 * reason the policy failed to be set 10477 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 10478 * </ul> 10479 * If there has been a change to the policy, 10480 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 10481 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 10482 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 10483 * will contain the reason why the policy changed. 10484 * 10485 * <p>NOTE: Performs disk I/O and shouldn't be called on the main thread. 10486 * 10487 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 10488 * caller is not a device admin. 10489 * @param filter The IntentFilter for which a default handler is added. 10490 * @param activity The Activity that is added as default intent handler. 10491 * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the 10492 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. 10493 */ 10494 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true) 10495 @SupportsCoexistence addPersistentPreferredActivity(@ullable ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)10496 public void addPersistentPreferredActivity(@Nullable ComponentName admin, IntentFilter filter, 10497 @NonNull ComponentName activity) { 10498 throwIfParentInstance("addPersistentPreferredActivity"); 10499 if (mService != null) { 10500 try { 10501 mService.addPersistentPreferredActivity(admin, mContext.getPackageName(), filter, 10502 activity); 10503 } catch (RemoteException e) { 10504 throw e.rethrowFromSystemServer(); 10505 } 10506 } 10507 } 10508 10509 /** 10510 * Called by a profile owner or device owner or holder of the 10511 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK} to remove all 10512 * persistent intent handler preferences associated with the given package that were set by 10513 * {@link #addPersistentPreferredActivity}. 10514 * <p> 10515 * The calling device admin must be a profile owner. If it is not, a security exception will be 10516 * thrown. 10517 * <p> 10518 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the persistent preferred 10519 * activity policy has been cleared, {@link PolicyUpdateReceiver#onPolicySetResult(Context, 10520 * String, Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy 10521 * was successfully cleared or not. This callback will contain: 10522 * <ul> 10523 * <li> The policy identifier 10524 * {@link DevicePolicyIdentifiers#PERSISTENT_PREFERRED_ACTIVITY_POLICY} 10525 * <li> The additional policy params bundle, which contains 10526 * {@link PolicyUpdateReceiver#EXTRA_INTENT_FILTER} the intent filter the policy applies to 10527 * <li> The {@link TargetUser} that this policy relates to 10528 * <li> The {@link PolicyUpdateResult}, which will be 10529 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully cleared or the 10530 * reason the policy failed to be cleared 10531 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 10532 * </ul> 10533 * If there has been a change to the policy, 10534 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 10535 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 10536 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 10537 * will contain the reason why the policy changed. 10538 * 10539 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 10540 * caller is not a device admin. 10541 * @param packageName The name of the package for which preferences are removed. 10542 * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the 10543 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. 10544 */ 10545 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true) 10546 @SupportsCoexistence clearPackagePersistentPreferredActivities(@ullable ComponentName admin, String packageName)10547 public void clearPackagePersistentPreferredActivities(@Nullable ComponentName admin, 10548 String packageName) { 10549 throwIfParentInstance("clearPackagePersistentPreferredActivities"); 10550 if (mService != null) { 10551 try { 10552 mService.clearPackagePersistentPreferredActivities( 10553 admin, 10554 mContext.getPackageName(), 10555 packageName); 10556 } catch (RemoteException e) { 10557 throw e.rethrowFromSystemServer(); 10558 } 10559 } 10560 } 10561 10562 /** 10563 * Must be called by a device owner or a profile owner of an organization-owned managed profile 10564 * to set the default SMS application. 10565 * <p> 10566 * This method can be called on the {@link DevicePolicyManager} instance, returned by 10567 * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner 10568 * of an organization-owned managed profile and the package must be a pre-installed system 10569 * package. If called on the parent instance, then the default SMS application is set on the 10570 * personal profile. 10571 * <p> 10572 * Starting from Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the profile 10573 * owner of an organization-owned managed profile can also call this method directly (not on the 10574 * parent profile instance) to set the default SMS application in the work profile. This is only 10575 * meaningful when work profile telephony is enabled by {@link #setManagedSubscriptionsPolicy}. 10576 * 10577 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 10578 * caller is not a device admin. 10579 * @param packageName The name of the package to set as the default SMS application. 10580 * @throws SecurityException if {@code admin} is not a device or profile owner or if 10581 * called on the parent profile and the {@code admin} is not a 10582 * profile owner of an organization-owned managed profile. 10583 * @throws IllegalArgumentException if called on the parent profile and the package 10584 * provided is not a pre-installed system package. 10585 * @throws IllegalStateException while trying to set default sms app on the profile and 10586 * {@link ManagedSubscriptionsPolicy#TYPE_ALL_MANAGED_SUBSCRIPTIONS} 10587 * policy is not set. 10588 */ 10589 @RequiresPermission(value = MANAGE_DEVICE_POLICY_DEFAULT_SMS, conditional = true) setDefaultSmsApplication(@ullable ComponentName admin, @NonNull String packageName)10590 public void setDefaultSmsApplication(@Nullable ComponentName admin, 10591 @NonNull String packageName) { 10592 if (mService != null) { 10593 try { 10594 mService.setDefaultSmsApplication(admin, mContext.getPackageName(), packageName, 10595 mParentInstance); 10596 } catch (RemoteException e) { 10597 throw e.rethrowFromSystemServer(); 10598 } 10599 } 10600 } 10601 10602 /** 10603 * Must be called by a device owner or a profile owner of an organization-owned managed profile 10604 * to set the default dialer application for the calling user. 10605 * <p> 10606 * When the profile owner of an organization-owned managed profile calls this method, it sets 10607 * the default dialer application in the work profile. This is only meaningful when work profile 10608 * telephony is enabled by {@link #setManagedSubscriptionsPolicy}. 10609 * <p> 10610 * If the device does not support telephony ({@link PackageManager#FEATURE_TELEPHONY}), calling 10611 * this method will do nothing. 10612 * 10613 * @param packageName The name of the package to set as the default dialer application. 10614 * @throws SecurityException if {@code admin} is not a device or profile owner or a 10615 * profile owner of an organization-owned managed profile. 10616 * @throws IllegalArgumentException if the package cannot be set as the default dialer, for 10617 * example if the package is not installed or does not expose 10618 * the expected activities or services that a dialer app is 10619 * required to have. 10620 */ setDefaultDialerApplication(@onNull String packageName)10621 public void setDefaultDialerApplication(@NonNull String packageName) { 10622 throwIfParentInstance("setDefaultDialerApplication"); 10623 if (mService != null) { 10624 try { 10625 mService.setDefaultDialerApplication(packageName); 10626 } catch (RemoteException e) { 10627 throw e.rethrowFromSystemServer(); 10628 } 10629 } 10630 } 10631 10632 /** 10633 * Called by a profile owner or device owner to grant permission to a package to manage 10634 * application restrictions for the calling user via {@link #setApplicationRestrictions} and 10635 * {@link #getApplicationRestrictions}. 10636 * <p> 10637 * This permission is persistent until it is later cleared by calling this method with a 10638 * {@code null} value or uninstalling the managing package. 10639 * <p> 10640 * The supplied application restriction managing package must be installed when calling this 10641 * API, otherwise an {@link NameNotFoundException} will be thrown. 10642 * 10643 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 10644 * @param packageName The package name which will be given access to application restrictions 10645 * APIs. If {@code null} is given the current package will be cleared. 10646 * @throws SecurityException if {@code admin} is not a device or profile owner. 10647 * @throws NameNotFoundException if {@code packageName} is not found 10648 * 10649 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes} 10650 * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead. 10651 */ 10652 @Deprecated setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)10653 public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin, 10654 @Nullable String packageName) throws NameNotFoundException { 10655 throwIfParentInstance("setApplicationRestrictionsManagingPackage"); 10656 if (mService != null) { 10657 try { 10658 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) { 10659 throw new NameNotFoundException(packageName); 10660 } 10661 } catch (RemoteException e) { 10662 throw e.rethrowFromSystemServer(); 10663 } 10664 } 10665 } 10666 10667 /** 10668 * Called by a profile owner or device owner to retrieve the application restrictions managing 10669 * package for the current user, or {@code null} if none is set. If there are multiple 10670 * delegates this function will return one of them. 10671 * 10672 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 10673 * @return The package name allowed to manage application restrictions on the current user, or 10674 * {@code null} if none is set. 10675 * @throws SecurityException if {@code admin} is not a device or profile owner. 10676 * 10677 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages} 10678 * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead. 10679 */ 10680 @Deprecated 10681 @Nullable getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)10682 public String getApplicationRestrictionsManagingPackage( 10683 @NonNull ComponentName admin) { 10684 throwIfParentInstance("getApplicationRestrictionsManagingPackage"); 10685 if (mService != null) { 10686 try { 10687 return mService.getApplicationRestrictionsManagingPackage(admin); 10688 } catch (RemoteException e) { 10689 throw e.rethrowFromSystemServer(); 10690 } 10691 } 10692 return null; 10693 } 10694 10695 /** 10696 * Called by any application to find out whether it has been granted permission via 10697 * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions 10698 * for the calling user. 10699 * 10700 * <p>This is done by comparing the calling Linux uid with the uid of the package specified by 10701 * that method. 10702 * 10703 * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes} 10704 * instead. 10705 */ 10706 @Deprecated isCallerApplicationRestrictionsManagingPackage()10707 public boolean isCallerApplicationRestrictionsManagingPackage() { 10708 throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage"); 10709 if (mService != null) { 10710 try { 10711 return mService.isCallerApplicationRestrictionsManagingPackage( 10712 mContext.getPackageName()); 10713 } catch (RemoteException e) { 10714 throw e.rethrowFromSystemServer(); 10715 } 10716 } 10717 return false; 10718 } 10719 10720 /** 10721 * Sets the application restrictions for a given target application running in the calling user. 10722 * <p> 10723 * The caller must be a profile or device owner on that user, or the package allowed to manage 10724 * application restrictions via {@link #setDelegatedScopes} with the 10725 * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown. 10726 * <p> 10727 * The provided {@link Bundle} consists of key-value pairs, where the types of values may be: 10728 * <ul> 10729 * <li>{@code boolean} 10730 * <li>{@code int} 10731 * <li>{@code String} or {@code String[]} 10732 * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]} 10733 * </ul> 10734 * <p> 10735 * If the restrictions are not available yet, but may be applied in the near future, the caller 10736 * can notify the target application of that by adding 10737 * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter. 10738 * <p> 10739 * The application restrictions are only made visible to the target application via 10740 * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device 10741 * owner, and the application restrictions managing package via 10742 * {@link #getApplicationRestrictions}. 10743 * 10744 * <p>Starting from Android Version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, 10745 * multiple admins can set app restrictions for the same application, the target application can 10746 * get the list of app restrictions set by each admin via 10747 * {@link android.content.RestrictionsManager#getApplicationRestrictionsPerAdmin}. 10748 * 10749 * <p>Starting from Android Version {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, 10750 * the device policy management role holder can also set app restrictions on any applications 10751 * in the calling user, as well as the parent user of an organization-owned managed profile via 10752 * the {@link DevicePolicyManager} instance returned by 10753 * {@link #getParentProfileInstance(ComponentName)}. App restrictions set by the device policy 10754 * management role holder are not returned by 10755 * {@link UserManager#getApplicationRestrictions(String)}. The target application should use 10756 * {@link android.content.RestrictionsManager#getApplicationRestrictionsPerAdmin} to retrieve 10757 * them, alongside any app restrictions the profile or device owner might have set. 10758 * 10759 * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread 10760 * 10761 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 10762 * {@code null} if called by the application restrictions managing package. 10763 * @param packageName The name of the package to update restricted settings for. 10764 * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new 10765 * set of active restrictions. 10766 * @throws SecurityException if {@code admin} is not a device or profile owner. 10767 * @see #setDelegatedScopes 10768 * @see #DELEGATION_APP_RESTRICTIONS 10769 * @see UserManager#KEY_RESTRICTIONS_PENDING 10770 */ 10771 @WorkerThread setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)10772 public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName, 10773 Bundle settings) { 10774 if (mService != null) { 10775 try { 10776 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName, 10777 settings, mParentInstance); 10778 } catch (RemoteException e) { 10779 throw e.rethrowFromSystemServer(); 10780 } 10781 } 10782 } 10783 10784 /** 10785 * Sets a list of configuration features to enable for a trust agent component. This is meant to 10786 * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust 10787 * agents but those enabled by this function call. If flag 10788 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect. 10789 * <p> 10790 * For any specific trust agent, whether it is disabled or not depends on the aggregated state 10791 * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent 10792 * configuration as set by this function call. In particular: if any admin sets 10793 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any 10794 * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent 10795 * will receive the list of configurations from all admins who set 10796 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its 10797 * behavior. The exact meaning of aggregation is trust-agent-specific. 10798 * <p> 10799 * A calling device admin must have requested 10800 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method; 10801 * if not, a security exception will be thrown. 10802 * <p> 10803 * This method can be called on the {@link DevicePolicyManager} instance returned by 10804 * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for 10805 * the parent profile. 10806 * <p> 10807 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling 10808 * this method has no effect - no trust agent configuration will be set. 10809 * 10810 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 10811 * caller is not a device admin 10812 * @param target Component name of the agent to be configured. 10813 * @param configuration Trust-agent-specific feature configuration bundle. Please consult 10814 * documentation of the specific trust agent to determine the interpretation of this 10815 * bundle. 10816 * @throws SecurityException if {@code admin} is not an active administrator or does not use 10817 * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} 10818 */ 10819 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) 10820 @RequiresPermission(value = MANAGE_DEVICE_POLICY_KEYGUARD, conditional = true) setTrustAgentConfiguration(@ullable ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)10821 public void setTrustAgentConfiguration(@Nullable ComponentName admin, 10822 @NonNull ComponentName target, PersistableBundle configuration) { 10823 if (mService != null) { 10824 try { 10825 mService.setTrustAgentConfiguration( 10826 admin, mContext.getPackageName(), target, configuration, mParentInstance); 10827 } catch (RemoteException e) { 10828 throw e.rethrowFromSystemServer(); 10829 } 10830 } 10831 } 10832 10833 /** 10834 * Gets configuration for the given trust agent based on aggregating all calls to 10835 * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for 10836 * all device admins. 10837 * <p> 10838 * This method can be called on the {@link DevicePolicyManager} instance returned by 10839 * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set 10840 * on the parent profile. 10841 * <p> 10842 * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is 10843 * always returned. 10844 * 10845 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null, 10846 * this function returns a list of configurations for all admins that declare 10847 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares 10848 * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call 10849 * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} 10850 * for this {@param agent} or calls it with a null configuration, null is returned. 10851 * @param agent Which component to get enabled features for. 10852 * @return configuration for the given trust agent. 10853 */ 10854 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)10855 public @Nullable List<PersistableBundle> getTrustAgentConfiguration( 10856 @Nullable ComponentName admin, @NonNull ComponentName agent) { 10857 return getTrustAgentConfiguration(admin, agent, myUserId()); 10858 } 10859 10860 /** @hide per-user version */ 10861 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 10862 @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN) getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)10863 public @Nullable List<PersistableBundle> getTrustAgentConfiguration( 10864 @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) { 10865 if (mService != null) { 10866 try { 10867 return mService.getTrustAgentConfiguration(admin, agent, userHandle, 10868 mParentInstance); 10869 } catch (RemoteException e) { 10870 throw e.rethrowFromSystemServer(); 10871 } 10872 } 10873 return new ArrayList<PersistableBundle>(); // empty list 10874 } 10875 10876 /** 10877 * Called by a profile owner of a managed profile to set whether caller-Id information from the 10878 * managed profile will be shown in the parent profile, for incoming calls. 10879 * <p> 10880 * The calling device admin must be a profile owner. If it is not, a security exception will be 10881 * thrown. 10882 * <p> 10883 * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, calling this function 10884 * is similar to calling {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)} 10885 * with a {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} policy type when {@code disabled} is 10886 * false or a {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST} policy type when 10887 * {@code disabled} is true. 10888 * 10889 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 10890 * @param disabled If true caller-Id information in the managed profile is not displayed. 10891 * @throws SecurityException if {@code admin} is not a profile owner. 10892 * @deprecated starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, use 10893 * {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)} instead 10894 */ 10895 @Deprecated setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)10896 public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) { 10897 throwIfParentInstance("setCrossProfileCallerIdDisabled"); 10898 if (mService != null) { 10899 try { 10900 mService.setCrossProfileCallerIdDisabled(admin, disabled); 10901 } catch (RemoteException e) { 10902 throw e.rethrowFromSystemServer(); 10903 } 10904 } 10905 } 10906 10907 /** 10908 * Called by a profile owner of a managed profile to determine whether or not caller-Id 10909 * information has been disabled. 10910 * <p> 10911 * The calling device admin must be a profile owner. If it is not, a security exception will be 10912 * thrown. 10913 * <p> 10914 * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, 10915 * this will return true when 10916 * {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)} 10917 * has been set with a non-null policy whose policy type is NOT 10918 * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} 10919 * 10920 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 10921 * @throws SecurityException if {@code admin} is not a profile owner. 10922 * @deprecated starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, use 10923 * {@link #getManagedProfileCallerIdAccessPolicy()} instead 10924 */ 10925 @Deprecated getCrossProfileCallerIdDisabled(@onNull ComponentName admin)10926 public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) { 10927 throwIfParentInstance("getCrossProfileCallerIdDisabled"); 10928 if (mService != null) { 10929 try { 10930 return mService.getCrossProfileCallerIdDisabled(admin); 10931 } catch (RemoteException e) { 10932 throw e.rethrowFromSystemServer(); 10933 } 10934 } 10935 return false; 10936 } 10937 10938 /** 10939 * Called by the system to determine whether or not caller-Id information has been disabled. 10940 * <p> 10941 * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, 10942 * this will return true when 10943 * {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)} 10944 * has been set with a non-null policy whose policy type is NOT 10945 * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} 10946 * 10947 * @param userHandle The user for whom to check the caller-id permission 10948 * @deprecated use {@link #hasManagedProfileCallerIdAccess(UserHandle, String)} and provide the 10949 * package name requesting access 10950 * @hide 10951 */ 10952 @Deprecated getCrossProfileCallerIdDisabled(UserHandle userHandle)10953 public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) { 10954 if (mService != null) { 10955 try { 10956 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier()); 10957 } catch (RemoteException e) { 10958 throw e.rethrowFromSystemServer(); 10959 } 10960 } 10961 return false; 10962 } 10963 10964 /** 10965 * Called by a device owner or profile owner of a managed profile to set the credential manager 10966 * policy. 10967 * 10968 * <p>Affects APIs exposed by {@link android.credentials.CredentialManager}. 10969 * 10970 * <p>A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST} policy type will limit the credential 10971 * providers that the user can use to the list of packages in the policy. 10972 * 10973 * <p>A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM} policy type 10974 * allows access from the OEM default credential providers and the allowlist of credential 10975 * providers. 10976 * 10977 * <p>A {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} policy type will block the credential 10978 * providers listed in the policy from being used by the user. 10979 * 10980 * @param policy the policy to set, setting this value to {@code null} will allow all packages 10981 * @throws SecurityException if caller is not a device owner or profile owner of a 10982 * managed profile 10983 */ setCredentialManagerPolicy(@ullable PackagePolicy policy)10984 public void setCredentialManagerPolicy(@Nullable PackagePolicy policy) { 10985 throwIfParentInstance("setCredentialManagerPolicy"); 10986 if (mService != null) { 10987 try { 10988 mService.setCredentialManagerPolicy(policy); 10989 } catch (RemoteException e) { 10990 throw e.rethrowFromSystemServer(); 10991 } 10992 } 10993 } 10994 10995 /** 10996 * Called by a device owner or profile owner of a managed profile to retrieve the credential 10997 * manager policy. 10998 * 10999 * @throws SecurityException if caller is not a device owner or profile owner of a 11000 * managed profile. 11001 * @return the current credential manager policy if null then this policy has not been 11002 * configured. 11003 */ 11004 @UserHandleAware( 11005 enabledSinceTargetSdkVersion = UPSIDE_DOWN_CAKE, 11006 requiresPermissionIfNotCaller = INTERACT_ACROSS_USERS) getCredentialManagerPolicy()11007 public @Nullable PackagePolicy getCredentialManagerPolicy() { 11008 throwIfParentInstance("getCredentialManagerPolicy"); 11009 if (mService != null) { 11010 try { 11011 return mService.getCredentialManagerPolicy(myUserId()); 11012 } catch (RemoteException e) { 11013 throw e.rethrowFromSystemServer(); 11014 } 11015 } 11016 return null; 11017 } 11018 11019 /** 11020 * Called by a profile owner of a managed profile to set the packages that are allowed to 11021 * lookup contacts in the managed profile based on caller id information. 11022 * <p> 11023 * For example, the policy determines if a dialer app in the parent profile resolving 11024 * an incoming call can search the caller id data, such as phone number, 11025 * of managed contacts and return managed contacts that match. 11026 * <p> 11027 * The calling device admin must be a profile owner of a managed profile. 11028 * If it is not, a {@link SecurityException} will be thrown. 11029 * <p> 11030 * A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM} policy type 11031 * allows access from the OEM default packages for the Sms, Dialer and Contact roles, 11032 * in addition to the packages specified in {@link PackagePolicy#getPackageNames()} 11033 * 11034 * @param policy the policy to set, setting this value to {@code null} will allow 11035 * all packages 11036 * @throws SecurityException if caller is not a profile owner of a managed profile 11037 */ setManagedProfileCallerIdAccessPolicy(@ullable PackagePolicy policy)11038 public void setManagedProfileCallerIdAccessPolicy(@Nullable PackagePolicy policy) { 11039 throwIfParentInstance("setManagedProfileCallerIdAccessPolicy"); 11040 if (mService != null) { 11041 try { 11042 mService.setManagedProfileCallerIdAccessPolicy(policy); 11043 } catch (RemoteException e) { 11044 throw e.rethrowFromSystemServer(); 11045 } 11046 } 11047 } 11048 11049 /** 11050 * Called by a profile owner of a managed profile to retrieve the caller id policy. 11051 * <p> 11052 * The calling device admin must be a profile owner of a managed profile. 11053 * If it is not, a {@link SecurityException} will be thrown. 11054 * 11055 * @throws SecurityException if caller is not a profile owner of a managed profile. 11056 * @return the current caller id policy 11057 */ getManagedProfileCallerIdAccessPolicy()11058 public @Nullable PackagePolicy getManagedProfileCallerIdAccessPolicy() { 11059 throwIfParentInstance("getManagedProfileCallerIdAccessPolicy"); 11060 if (mService != null) { 11061 try { 11062 return mService.getManagedProfileCallerIdAccessPolicy(); 11063 } catch (RemoteException e) { 11064 throw e.rethrowFromSystemServer(); 11065 } 11066 } 11067 return null; 11068 } 11069 11070 /** 11071 * Determine whether the given package is allowed to query the requested user to 11072 * populate caller id information 11073 * 11074 * @param userHandle The user for whom to check the contacts search permission 11075 * @param packageName the name of the package requesting access 11076 * @return true if package should be granted access, false otherwise 11077 * @hide 11078 */ 11079 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) hasManagedProfileCallerIdAccess(@onNull UserHandle userHandle, @NonNull String packageName)11080 public boolean hasManagedProfileCallerIdAccess(@NonNull UserHandle userHandle, 11081 @NonNull String packageName) { 11082 if (mService == null) { 11083 return true; 11084 } 11085 try { 11086 return mService.hasManagedProfileCallerIdAccess(userHandle.getIdentifier(), 11087 packageName); 11088 } catch (RemoteException e) { 11089 throw e.rethrowFromSystemServer(); 11090 } 11091 } 11092 11093 /** 11094 * Called by a profile owner of a managed profile to set the packages that are allowed 11095 * access to the managed profile contacts from the parent user. 11096 * <p> 11097 * For example, the system will enforce the provided policy and determine 11098 * if contacts in the managed profile are shown when queried by an application 11099 * in the parent user. 11100 * <p> 11101 * The calling device admin must be a profile owner of a managed profile. 11102 * If it is not, a {@link SecurityException} will be thrown. 11103 * <p> 11104 * A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM} policy type 11105 * allows access from the OEM default packages for the Sms, Dialer and Contact roles, 11106 * in addition to the packages specified in {@link PackagePolicy#getPackageNames()} 11107 * 11108 * @param policy the policy to set, setting this value to {@code null} will allow 11109 * all packages 11110 * @throws SecurityException if caller is not a profile owner of a managed profile 11111 */ setManagedProfileContactsAccessPolicy(@ullable PackagePolicy policy)11112 public void setManagedProfileContactsAccessPolicy(@Nullable PackagePolicy policy) { 11113 throwIfParentInstance("setManagedProfileContactsAccessPolicy"); 11114 if (mService != null) { 11115 try { 11116 mService.setManagedProfileContactsAccessPolicy(policy); 11117 } catch (RemoteException e) { 11118 throw e.rethrowFromSystemServer(); 11119 } 11120 } 11121 } 11122 11123 /** 11124 * Called by a profile owner of a managed profile to determine the current policy applied 11125 * to managed profile contacts. 11126 * <p> 11127 * The calling device admin must be a profile owner of a managed profile. 11128 * If it is not, a {@link SecurityException} will be thrown. 11129 * 11130 * @throws SecurityException if caller is not a profile owner of a managed profile. 11131 * @return the current contacts search policy 11132 */ getManagedProfileContactsAccessPolicy()11133 public @Nullable PackagePolicy getManagedProfileContactsAccessPolicy() { 11134 throwIfParentInstance("getManagedProfileContactsAccessPolicy"); 11135 if (mService == null) { 11136 return null; 11137 } 11138 try { 11139 return mService.getManagedProfileContactsAccessPolicy(); 11140 } catch (RemoteException e) { 11141 throw e.rethrowFromSystemServer(); 11142 } 11143 } 11144 11145 /** 11146 * Determine whether requesting package has ability to access contacts of the requested user 11147 * 11148 * @param userHandle The user for whom to check the contacts search permission 11149 * @param packageName packageName requesting access to contact search 11150 * @return true when package is allowed access, false otherwise 11151 * @hide 11152 */ 11153 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) hasManagedProfileContactsAccess(@onNull UserHandle userHandle, @NonNull String packageName)11154 public boolean hasManagedProfileContactsAccess(@NonNull UserHandle userHandle, 11155 @NonNull String packageName) { 11156 if (mService != null) { 11157 try { 11158 return mService.hasManagedProfileContactsAccess(userHandle.getIdentifier(), 11159 packageName); 11160 } catch (RemoteException e) { 11161 throw e.rethrowFromSystemServer(); 11162 } 11163 } 11164 return false; 11165 } 11166 11167 /** 11168 * Called by a profile owner of a managed profile to set whether contacts search from the 11169 * managed profile will be shown in the parent profile, for incoming calls. 11170 * <p> 11171 * The calling device admin must be a profile owner. If it is not, a security exception will be 11172 * thrown. 11173 * 11174 * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, calling this function 11175 * is similar to calling {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)} with a 11176 * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} policy type when {@code disabled} is false 11177 * or a {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST} policy type when {@code disabled} 11178 * is true. 11179 * 11180 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11181 * @param disabled If true contacts search in the managed profile is not displayed. 11182 * @throws SecurityException if {@code admin} is not a profile owner. 11183 * 11184 * @deprecated From {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} use 11185 * {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)} 11186 */ 11187 @Deprecated setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)11188 public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin, 11189 boolean disabled) { 11190 throwIfParentInstance("setCrossProfileContactsSearchDisabled"); 11191 if (mService != null) { 11192 try { 11193 mService.setCrossProfileContactsSearchDisabled(admin, disabled); 11194 } catch (RemoteException e) { 11195 throw e.rethrowFromSystemServer(); 11196 } 11197 } 11198 } 11199 11200 /** 11201 * Called by a profile owner of a managed profile to determine whether or not contacts search 11202 * has been disabled. 11203 * <p> 11204 * The calling device admin must be a profile owner. If it is not, a security exception will be 11205 * thrown. 11206 * <p> 11207 * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, 11208 * this will return true when 11209 * {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)} 11210 * has been set with a non-null policy whose policy type is NOT 11211 * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} 11212 * 11213 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11214 * @throws SecurityException if {@code admin} is not a profile owner. 11215 * @deprecated From {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} use 11216 * {@link #getManagedProfileContactsAccessPolicy()} 11217 */ 11218 @Deprecated getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)11219 public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) { 11220 throwIfParentInstance("getCrossProfileContactsSearchDisabled"); 11221 if (mService != null) { 11222 try { 11223 return mService.getCrossProfileContactsSearchDisabled(admin); 11224 } catch (RemoteException e) { 11225 throw e.rethrowFromSystemServer(); 11226 } 11227 } 11228 return false; 11229 } 11230 11231 /** 11232 * Determine whether or not contacts search has been disabled. 11233 * <p> 11234 * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, 11235 * this will return true when 11236 * {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)} 11237 * has been set with a non-null policy whose policy type is NOT 11238 * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} 11239 * @param userHandle The user for whom to check the contacts search permission 11240 * @deprecated use {@link #hasManagedProfileContactsAccess(UserHandle, String)} and provide the 11241 * package name requesting access 11242 * @hide 11243 */ 11244 @Deprecated getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)11245 public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) { 11246 if (mService != null) { 11247 try { 11248 return mService 11249 .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier()); 11250 } catch (RemoteException e) { 11251 throw e.rethrowFromSystemServer(); 11252 } 11253 } 11254 return false; 11255 } 11256 11257 /** 11258 * Start Quick Contact on the managed profile for the user, if the policy allows. 11259 * 11260 * @hide 11261 */ startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)11262 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 11263 boolean isContactIdIgnored, long directoryId, Intent originalIntent) { 11264 if (mService != null) { 11265 try { 11266 mService.startManagedQuickContact(actualLookupKey, actualContactId, 11267 isContactIdIgnored, directoryId, originalIntent); 11268 } catch (RemoteException e) { 11269 throw e.rethrowFromSystemServer(); 11270 } 11271 } 11272 } 11273 11274 /** 11275 * Start Quick Contact on the managed profile for the user, if the policy allows. 11276 * @hide 11277 */ startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)11278 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 11279 Intent originalIntent) { 11280 startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT, 11281 originalIntent); 11282 } 11283 11284 /** 11285 * Called by a profile owner of a managed profile to set whether bluetooth devices can access 11286 * enterprise contacts. 11287 * <p> 11288 * The calling device admin must be a profile owner. If it is not, a security exception will be 11289 * thrown. 11290 * <p> 11291 * This API works on managed profile only. 11292 * 11293 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11294 * @param disabled If true, bluetooth devices cannot access enterprise contacts. 11295 * @throws SecurityException if {@code admin} is not a profile owner. 11296 */ setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)11297 public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) { 11298 throwIfParentInstance("setBluetoothContactSharingDisabled"); 11299 if (mService != null) { 11300 try { 11301 mService.setBluetoothContactSharingDisabled(admin, disabled); 11302 } catch (RemoteException e) { 11303 throw e.rethrowFromSystemServer(); 11304 } 11305 } 11306 } 11307 11308 /** 11309 * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices 11310 * cannot access enterprise contacts. 11311 * <p> 11312 * The calling device admin must be a profile owner. If it is not, a security exception will be 11313 * thrown. 11314 * <p> 11315 * This API works on managed profile only. 11316 * 11317 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11318 * @throws SecurityException if {@code admin} is not a profile owner. 11319 */ getBluetoothContactSharingDisabled(@onNull ComponentName admin)11320 public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) { 11321 throwIfParentInstance("getBluetoothContactSharingDisabled"); 11322 if (mService != null) { 11323 try { 11324 return mService.getBluetoothContactSharingDisabled(admin); 11325 } catch (RemoteException e) { 11326 throw e.rethrowFromSystemServer(); 11327 } 11328 } 11329 return true; 11330 } 11331 11332 /** 11333 * Determine whether or not Bluetooth devices cannot access contacts. 11334 * <p> 11335 * This API works on managed profile UserHandle only. 11336 * 11337 * @param userHandle The user for whom to check the caller-id permission 11338 * @hide 11339 */ 11340 @SystemApi 11341 @RequiresPermission(permission.INTERACT_ACROSS_USERS) getBluetoothContactSharingDisabled(@onNull UserHandle userHandle)11342 public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) { 11343 if (mService != null) { 11344 try { 11345 return mService.getBluetoothContactSharingDisabledForUser(userHandle 11346 .getIdentifier()); 11347 } catch (RemoteException e) { 11348 throw e.rethrowFromSystemServer(); 11349 } 11350 } 11351 return true; 11352 } 11353 11354 /** 11355 * Called by the profile owner of a managed profile so that some intents sent in the managed 11356 * profile can also be resolved in the parent, or vice versa. Only activity intents are 11357 * supported. 11358 * 11359 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11360 * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the 11361 * other profile 11362 * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and 11363 * {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported. 11364 * @throws SecurityException if {@code admin} is not a device or profile owner. 11365 */ 11366 @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true) addCrossProfileIntentFilter(@ullable ComponentName admin, IntentFilter filter, int flags)11367 public void addCrossProfileIntentFilter(@Nullable ComponentName admin, IntentFilter filter, 11368 int flags) { 11369 throwIfParentInstance("addCrossProfileIntentFilter"); 11370 if (mService != null) { 11371 try { 11372 mService.addCrossProfileIntentFilter(admin, mContext.getPackageName(), filter, 11373 flags); 11374 } catch (RemoteException e) { 11375 throw e.rethrowFromSystemServer(); 11376 } 11377 } 11378 } 11379 11380 /** 11381 * Called by a profile owner of a managed profile to remove the cross-profile intent filters 11382 * that go from the managed profile to the parent, or from the parent to the managed profile. 11383 * Only removes those that have been set by the profile owner. 11384 * <p> 11385 * <em>Note</em>: A list of default cross profile intent filters are set up by the system when 11386 * the profile is created, some of them ensure the proper functioning of the profile, while 11387 * others enable sharing of data from the parent to the managed profile for user convenience. 11388 * These default intent filters are not cleared when this API is called. If the default cross 11389 * profile data sharing is not desired, they can be disabled with 11390 * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}. 11391 * 11392 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11393 * @throws SecurityException if {@code admin} is not a profile owner. 11394 */ 11395 @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true) clearCrossProfileIntentFilters(@ullable ComponentName admin)11396 public void clearCrossProfileIntentFilters(@Nullable ComponentName admin) { 11397 throwIfParentInstance("clearCrossProfileIntentFilters"); 11398 if (mService != null) { 11399 try { 11400 mService.clearCrossProfileIntentFilters(admin, mContext.getPackageName()); 11401 } catch (RemoteException e) { 11402 throw e.rethrowFromSystemServer(); 11403 } 11404 } 11405 } 11406 11407 /** 11408 * Called by a profile or device owner to set the permitted 11409 * {@link android.accessibilityservice.AccessibilityService}. When set by 11410 * a device owner or profile owner the restriction applies to all profiles of the user the 11411 * device owner or profile owner is an admin for. By default, the user can use any accessibility 11412 * service. When zero or more packages have been added, accessibility services that are not in 11413 * the list and not part of the system can not be enabled by the user. 11414 * <p> 11415 * Calling with a {@code null} value for the list disables the restriction so that all services 11416 * can be used, calling with an empty list only allows the built-in system services. Any 11417 * non-system accessibility service that's currently enabled must be included in the list. 11418 * <p> 11419 * System accessibility services are always available to the user and this method can't 11420 * disable them. 11421 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11422 * @param packageNames List of accessibility service package names. 11423 * @return {@code true} if the operation succeeded, or {@code false} if the list didn't 11424 * contain every enabled non-system accessibility service. 11425 * @throws SecurityException if {@code admin} is not a device or profile owner. 11426 */ setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)11427 public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin, 11428 List<String> packageNames) { 11429 throwIfParentInstance("setPermittedAccessibilityServices"); 11430 if (mService != null) { 11431 try { 11432 return mService.setPermittedAccessibilityServices(admin, packageNames); 11433 } catch (RemoteException e) { 11434 throw e.rethrowFromSystemServer(); 11435 } 11436 } 11437 return false; 11438 } 11439 11440 /** 11441 * Returns the list of permitted accessibility services set by this device or profile owner. 11442 * <p> 11443 * An empty list means no accessibility services except system services are allowed. 11444 * {@code null} means all accessibility services are allowed. 11445 * 11446 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11447 * @return List of accessiblity service package names. 11448 * @throws SecurityException if {@code admin} is not a device or profile owner. 11449 */ getPermittedAccessibilityServices(@onNull ComponentName admin)11450 public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) { 11451 throwIfParentInstance("getPermittedAccessibilityServices"); 11452 if (mService != null) { 11453 try { 11454 return mService.getPermittedAccessibilityServices(admin); 11455 } catch (RemoteException e) { 11456 throw e.rethrowFromSystemServer(); 11457 } 11458 } 11459 return null; 11460 } 11461 11462 /** 11463 * Called by the system to check if a specific accessibility service is disabled by admin. 11464 * 11465 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11466 * @param packageName Accessibility service package name that needs to be checked. 11467 * @param userHandle user id the admin is running as. 11468 * @return true if the accessibility service is permitted, otherwise false. 11469 * 11470 * @hide 11471 */ isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)11472 public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin, 11473 @NonNull String packageName, int userHandle) { 11474 if (mService != null) { 11475 try { 11476 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName, 11477 userHandle); 11478 } catch (RemoteException e) { 11479 throw e.rethrowFromSystemServer(); 11480 } 11481 } 11482 return false; 11483 } 11484 11485 /** 11486 * Returns the list of accessibility services permitted by the device or profiles 11487 * owners of this user. 11488 * 11489 * <p>{@code null} means all accessibility services are allowed, if a non-null list is returned 11490 * it will contain the intersection of the permitted lists for any device or profile 11491 * owners that apply to this user. It will also include any system accessibility services. 11492 * 11493 * @param userId which user to check for. 11494 * @return List of accessiblity service package names. 11495 * @hide 11496 */ 11497 @SystemApi 11498 @RequiresPermission(anyOf = { 11499 android.Manifest.permission.MANAGE_USERS, 11500 android.Manifest.permission.QUERY_ADMIN_POLICY}) getPermittedAccessibilityServices(int userId)11501 public @Nullable List<String> getPermittedAccessibilityServices(int userId) { 11502 throwIfParentInstance("getPermittedAccessibilityServices"); 11503 if (mService != null) { 11504 try { 11505 return mService.getPermittedAccessibilityServicesForUser(userId); 11506 } catch (RemoteException e) { 11507 throw e.rethrowFromSystemServer(); 11508 } 11509 } 11510 return null; 11511 } 11512 11513 /** 11514 * Called by a profile or device owner or holder of the 11515 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_INPUT_METHODS} permission to set 11516 * the permitted input methods services for this user. By default, the user can use any input 11517 * method. 11518 * <p> 11519 * This method can be called on the {@link DevicePolicyManager} instance, 11520 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be 11521 * a profile owner of an organization-owned device. 11522 * <p> 11523 * If called on the parent instance: 11524 * <ul> 11525 * <li>The permitted input methods will be applied on the personal profile</li> 11526 * <li>Can only permit all input methods (calling this method with a {@code null} package 11527 * list) or only permit system input methods (calling this method with an empty package 11528 * list). This is to prevent the caller from learning which packages are installed on 11529 * the personal side</li> 11530 * </ul> 11531 * <p> 11532 * When zero or more packages have been added, input method that are not in the list and not 11533 * part of the system can not be enabled by the user. This method will fail if it is called for 11534 * a admin that is not for the foreground user or a profile of the foreground user. Any 11535 * non-system input method service that's currently enabled must be included in the list. 11536 * <p> 11537 * Calling with a null value for the list disables the restriction so that all input methods can 11538 * be used, calling with an empty list disables all but the system's own input methods. 11539 * <p> 11540 * System input methods are always available to the user - this method can't modify this. 11541 * 11542 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 11543 * caller is not a device admin 11544 * @param packageNames List of input method package names. 11545 * @return {@code true} if the operation succeeded, or {@code false} if the list didn't 11546 * contain every enabled non-system input method service. 11547 * @throws SecurityException if {@code admin} is not a device or profile owner and does not 11548 * hold the {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_INPUT_METHODS} 11549 * permission, or if called on the parent profile and the 11550 * {@code admin} is not a profile owner of an organization-owned 11551 * managed profile. 11552 * @throws IllegalArgumentException if called on the parent profile, the {@code admin} is a 11553 * profile owner of an organization-owned managed profile and the 11554 * list of permitted input method package names is not null or empty. 11555 */ 11556 @SupportsCoexistence 11557 @RequiresPermission(value = MANAGE_DEVICE_POLICY_INPUT_METHODS, conditional = true) setPermittedInputMethods( @ullable ComponentName admin, List<String> packageNames)11558 public boolean setPermittedInputMethods( 11559 @Nullable ComponentName admin, List<String> packageNames) { 11560 if (mService != null) { 11561 try { 11562 return mService.setPermittedInputMethods( 11563 admin, mContext.getPackageName(), packageNames, mParentInstance); 11564 } catch (RemoteException e) { 11565 throw e.rethrowFromSystemServer(); 11566 } 11567 } 11568 return false; 11569 } 11570 11571 11572 /** 11573 * Returns the list of permitted input methods set by this device or profile owner. 11574 * <p> 11575 * This method can be called on the {@link DevicePolicyManager} instance, 11576 * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be 11577 * a profile owner of an organization-owned managed profile. If called on the parent instance, 11578 * then the returned list of permitted input methods are those which are applied on the 11579 * personal profile. 11580 * <p> 11581 * An empty list means no input methods except system input methods are allowed. Null means all 11582 * input methods are allowed. 11583 * 11584 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 11585 * caller is not a device admin 11586 * @return List of input method package names. 11587 * @throws SecurityException if {@code admin} is not a device, profile owner or if called on 11588 * the parent profile and the {@code admin} is not a profile owner 11589 * of an organization-owned managed profile. 11590 */ 11591 @RequiresPermission(value = MANAGE_DEVICE_POLICY_INPUT_METHODS, conditional = true) getPermittedInputMethods(@ullable ComponentName admin)11592 public @Nullable List<String> getPermittedInputMethods(@Nullable ComponentName admin) { 11593 if (mService != null) { 11594 try { 11595 return mService.getPermittedInputMethods(admin, mContext.getPackageName(), mParentInstance); 11596 } catch (RemoteException e) { 11597 throw e.rethrowFromSystemServer(); 11598 } 11599 } 11600 return null; 11601 } 11602 11603 /** 11604 * Called by the system to check if a specific input method is disabled by admin. 11605 * <p> 11606 * This method can be called on the {@link DevicePolicyManager} instance, 11607 * returned by {@link #getParentProfileInstance(ComponentName)}. If called on the parent 11608 * instance, this method will check whether the given input method is permitted on 11609 * the personal profile. 11610 * 11611 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11612 * @param packageName Input method package name that needs to be checked. 11613 * @param userHandle user id the admin is running as. 11614 * @return true if the input method is permitted, otherwise false. 11615 * 11616 * @hide 11617 */ isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)11618 public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin, 11619 @NonNull String packageName, int userHandle) { 11620 if (mService != null) { 11621 try { 11622 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle, 11623 mParentInstance); 11624 } catch (RemoteException e) { 11625 throw e.rethrowFromSystemServer(); 11626 } 11627 } 11628 return false; 11629 } 11630 11631 /** 11632 * Returns the list of input methods permitted by the device or profiles owners. 11633 * 11634 * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the 11635 * result for the calling user.</p> 11636 * 11637 * <p>On Android P and prior devices, this method returns the result for the current user.</p> 11638 * 11639 * <p>Null means all input methods are allowed, if a non-null list is returned 11640 * it will contain the intersection of the permitted lists for any device or profile 11641 * owners that apply to this user. It will also include any system input methods. 11642 * 11643 * @return List of input method package names. 11644 * @hide 11645 * 11646 * @see #setPermittedAccessibilityServices(ComponentName, List) 11647 */ 11648 @SystemApi 11649 @RequiresPermission(anyOf = { 11650 android.Manifest.permission.MANAGE_USERS, 11651 android.Manifest.permission.QUERY_ADMIN_POLICY}) getPermittedInputMethodsForCurrentUser()11652 public @Nullable List<String> getPermittedInputMethodsForCurrentUser() { 11653 throwIfParentInstance("getPermittedInputMethodsForCurrentUser"); 11654 if (mService != null) { 11655 try { 11656 return mService.getPermittedInputMethodsAsUser(UserHandle.myUserId()); 11657 } catch (RemoteException e) { 11658 throw e.rethrowFromSystemServer(); 11659 } 11660 } 11661 return null; 11662 } 11663 11664 /** 11665 * Returns the list of input methods permitted. 11666 * 11667 * <p>{@code null} means all input methods are allowed, if a non-null list is returned 11668 * it will contain the intersection of the permitted lists for any device or profile 11669 * owners that apply to this user. It will also include any system input methods. 11670 * 11671 * @return List of input method package names. 11672 * @hide 11673 * 11674 * @see #setPermittedAccessibilityServices(ComponentName, List) 11675 */ 11676 @UserHandleAware 11677 @RequiresPermission(allOf = { 11678 INTERACT_ACROSS_USERS_FULL, 11679 android.Manifest.permission.MANAGE_USERS 11680 }, conditional = true) getPermittedInputMethods()11681 public @Nullable List<String> getPermittedInputMethods() { 11682 throwIfParentInstance("getPermittedInputMethods"); 11683 if (mService != null) { 11684 try { 11685 return mService.getPermittedInputMethodsAsUser(myUserId()); 11686 } catch (RemoteException e) { 11687 throw e.rethrowFromSystemServer(); 11688 } 11689 } 11690 return null; 11691 } 11692 11693 /** 11694 * Called by a profile owner of a managed profile to set the packages that are allowed to use 11695 * a {@link android.service.notification.NotificationListenerService} in the primary user to 11696 * see notifications from the managed profile. By default all packages are permitted by this 11697 * policy. When zero or more packages have been added, notification listeners installed on the 11698 * primary user that are not in the list and are not part of the system won't receive events 11699 * for managed profile notifications. 11700 * <p> 11701 * Calling with a {@code null} value for the list disables the restriction so that all 11702 * notification listener services be used. Calling with an empty list disables all but the 11703 * system's own notification listeners. System notification listener services are always 11704 * available to the user. 11705 * <p> 11706 * If a device or profile owner want to stop notification listeners in their user from seeing 11707 * that user's notifications they should prevent that service from running instead (e.g. via 11708 * {@link #setApplicationHidden(ComponentName, String, boolean)}) 11709 * 11710 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11711 * @param packageList List of package names to allowlist 11712 * @return true if setting the restriction succeeded. It will fail if called outside a managed 11713 * profile 11714 * @throws SecurityException if {@code admin} is not a profile owner. 11715 * 11716 * @see android.service.notification.NotificationListenerService 11717 */ setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)11718 public boolean setPermittedCrossProfileNotificationListeners( 11719 @NonNull ComponentName admin, @Nullable List<String> packageList) { 11720 throwIfParentInstance("setPermittedCrossProfileNotificationListeners"); 11721 if (mService != null) { 11722 try { 11723 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList); 11724 } catch (RemoteException e) { 11725 throw e.rethrowFromSystemServer(); 11726 } 11727 } 11728 return false; 11729 } 11730 11731 /** 11732 * Returns the list of packages installed on the primary user that allowed to use a 11733 * {@link android.service.notification.NotificationListenerService} to receive 11734 * notifications from this managed profile, as set by the profile owner. 11735 * <p> 11736 * An empty list means no notification listener services except system ones are allowed. 11737 * A {@code null} return value indicates that all notification listeners are allowed. 11738 */ getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)11739 public @Nullable List<String> getPermittedCrossProfileNotificationListeners( 11740 @NonNull ComponentName admin) { 11741 throwIfParentInstance("getPermittedCrossProfileNotificationListeners"); 11742 if (mService != null) { 11743 try { 11744 return mService.getPermittedCrossProfileNotificationListeners(admin); 11745 } catch (RemoteException e) { 11746 throw e.rethrowFromSystemServer(); 11747 } 11748 } 11749 return null; 11750 } 11751 11752 /** 11753 * Returns true if {@code NotificationListenerServices} from the given package are allowed to 11754 * receive events for notifications from the given user id. Can only be called by the system uid 11755 * 11756 * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List) 11757 * 11758 * @hide 11759 */ isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)11760 public boolean isNotificationListenerServicePermitted( 11761 @NonNull String packageName, @UserIdInt int userId) { 11762 if (mService != null) { 11763 try { 11764 return mService.isNotificationListenerServicePermitted(packageName, userId); 11765 } catch (RemoteException e) { 11766 throw e.rethrowFromSystemServer(); 11767 } 11768 } 11769 return true; 11770 } 11771 11772 /** 11773 * Get the list of apps to keep around as APKs even if no user has currently installed it. This 11774 * function can be called by a device owner or by a delegate given the 11775 * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}. 11776 * <p> 11777 * Please note that packages returned in this method are not automatically pre-cached. 11778 * 11779 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 11780 * {@code null} if the caller is a keep uninstalled packages delegate. 11781 * @return List of package names to keep cached. 11782 * @see #setDelegatedScopes 11783 * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES 11784 */ getKeepUninstalledPackages(@ullable ComponentName admin)11785 public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) { 11786 throwIfParentInstance("getKeepUninstalledPackages"); 11787 if (mService != null) { 11788 try { 11789 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName()); 11790 } catch (RemoteException e) { 11791 throw e.rethrowFromSystemServer(); 11792 } 11793 } 11794 return null; 11795 } 11796 11797 /** 11798 * Set a list of apps to keep around as APKs even if no user has currently installed it. This 11799 * function can be called by a device owner or by a delegate given the 11800 * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}. 11801 * 11802 * <p>Please note that setting this policy does not imply that specified apps will be 11803 * automatically pre-cached.</p> 11804 * 11805 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 11806 * {@code null} if the caller is a keep uninstalled packages delegate. 11807 * @param packageNames List of package names to keep cached. 11808 * @throws SecurityException if {@code admin} is not a device owner. 11809 * @see #setDelegatedScopes 11810 * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES 11811 */ setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)11812 public void setKeepUninstalledPackages(@Nullable ComponentName admin, 11813 @NonNull List<String> packageNames) { 11814 throwIfParentInstance("setKeepUninstalledPackages"); 11815 if (mService != null) { 11816 try { 11817 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames); 11818 } catch (RemoteException e) { 11819 throw e.rethrowFromSystemServer(); 11820 } 11821 } 11822 } 11823 11824 /** 11825 * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user. 11826 */ 11827 public static final int SKIP_SETUP_WIZARD = 0x0001; 11828 11829 /** 11830 * Flag used by {@link #createAndManageUser} to specify that the user should be created 11831 * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the 11832 * device. 11833 */ 11834 public static final int MAKE_USER_EPHEMERAL = 0x0002; 11835 11836 /** 11837 * Flag used by {@link #createAndManageUser} to specify that the user should be created as a 11838 * demo user. 11839 * @hide 11840 */ 11841 public static final int MAKE_USER_DEMO = 0x0004; 11842 11843 /** 11844 * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip 11845 * the disabling of system apps during provisioning. 11846 */ 11847 public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010; 11848 11849 /** 11850 * @hide 11851 */ 11852 @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = { 11853 SKIP_SETUP_WIZARD, 11854 MAKE_USER_EPHEMERAL, 11855 MAKE_USER_DEMO, 11856 LEAVE_ALL_SYSTEM_APPS_ENABLED 11857 }) 11858 @Retention(RetentionPolicy.SOURCE) 11859 public @interface CreateAndManageUserFlags {} 11860 11861 /** 11862 * Called by a device owner to create a user with the specified name and a given component of 11863 * the calling package as profile owner. The UserHandle returned by this method should not be 11864 * persisted as user handles are recycled as users are removed and created. If you need to 11865 * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new 11866 * user will not be started in the background. 11867 * <p> 11868 * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a 11869 * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will 11870 * be registered as an active admin on the new user. The profile owner package will be installed 11871 * on the new user. 11872 * <p> 11873 * If the adminExtras are not null, they will be stored on the device until the user is started 11874 * for the first time. Then the extras will be passed to the admin when onEnable is called. 11875 * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting 11876 * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of 11877 * returning {@code null} on failure. 11878 * 11879 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11880 * @param name The user's name. 11881 * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the 11882 * same package as admin, otherwise no user is created and an 11883 * IllegalArgumentException is thrown. 11884 * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new 11885 * user. 11886 * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and 11887 * {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported. 11888 * @see UserHandle 11889 * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the 11890 * user could not be created. 11891 * @throws SecurityException if headless device is in 11892 * {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER} mode. 11893 * @throws SecurityException if {@code admin} is not a device owner 11894 * @throws UserOperationException if the user could not be created and the calling app is 11895 * targeting {@link android.os.Build.VERSION_CODES#P} and running on 11896 * {@link android.os.Build.VERSION_CODES#P}. 11897 */ createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)11898 public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin, 11899 @NonNull String name, 11900 @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, 11901 @CreateAndManageUserFlags int flags) { 11902 throwIfParentInstance("createAndManageUser"); 11903 try { 11904 return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags); 11905 } catch (ServiceSpecificException e) { 11906 throw new UserOperationException(e.getMessage(), e.errorCode); 11907 } catch (RemoteException re) { 11908 throw re.rethrowFromSystemServer(); 11909 } 11910 } 11911 11912 /** 11913 * Called by a device owner to remove a user/profile and all associated data. The primary user 11914 * can not be removed. 11915 * 11916 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11917 * @param userHandle the user to remove. 11918 * @return {@code true} if the user was removed, {@code false} otherwise. 11919 * @throws SecurityException if {@code admin} is not a device owner. 11920 */ removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)11921 public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) { 11922 throwIfParentInstance("removeUser"); 11923 try { 11924 return mService.removeUser(admin, userHandle); 11925 } catch (RemoteException re) { 11926 throw re.rethrowFromSystemServer(); 11927 } 11928 } 11929 11930 /** 11931 * Called by a device owner to switch the specified secondary user to the foreground. 11932 * 11933 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11934 * @param userHandle the user to switch to; null will switch to primary. 11935 * @return {@code true} if the switch was successful, {@code false} otherwise. 11936 * @throws SecurityException if {@code admin} is not a device owner. 11937 * @see Intent#ACTION_USER_FOREGROUND 11938 * @see #getSecondaryUsers(ComponentName) 11939 */ switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)11940 public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) { 11941 throwIfParentInstance("switchUser"); 11942 try { 11943 return mService.switchUser(admin, userHandle); 11944 } catch (RemoteException re) { 11945 throw re.rethrowFromSystemServer(); 11946 } 11947 } 11948 11949 /** 11950 * Called by a device owner to start the specified secondary user in background. 11951 * 11952 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11953 * @param userHandle the user to be started in background. 11954 * @return one of the following result codes: 11955 * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN}, 11956 * {@link UserManager#USER_OPERATION_SUCCESS}, 11957 * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE}, 11958 * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS}, 11959 * @throws SecurityException if {@code admin} is not a device owner. 11960 * @see #getSecondaryUsers(ComponentName) 11961 */ startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)11962 public @UserOperationResult int startUserInBackground( 11963 @NonNull ComponentName admin, @NonNull UserHandle userHandle) { 11964 throwIfParentInstance("startUserInBackground"); 11965 try { 11966 return mService.startUserInBackground(admin, userHandle); 11967 } catch (RemoteException re) { 11968 throw re.rethrowFromSystemServer(); 11969 } 11970 } 11971 11972 /** 11973 * Called by a device owner to stop the specified secondary user. 11974 * 11975 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 11976 * @param userHandle the user to be stopped. 11977 * @return one of the following result codes: 11978 * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN}, 11979 * {@link UserManager#USER_OPERATION_SUCCESS}, 11980 * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE}, 11981 * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER} 11982 * @throws SecurityException if {@code admin} is not a device owner. 11983 * @see #getSecondaryUsers(ComponentName) 11984 */ stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)11985 public @UserOperationResult int stopUser( 11986 @NonNull ComponentName admin, @NonNull UserHandle userHandle) { 11987 throwIfParentInstance("stopUser"); 11988 try { 11989 return mService.stopUser(admin, userHandle); 11990 } catch (RemoteException re) { 11991 throw re.rethrowFromSystemServer(); 11992 } 11993 } 11994 11995 /** 11996 * Called by a profile owner of secondary user that is affiliated with the device to stop the 11997 * calling user and switch back to primary user (when the user was 11998 * {@link #switchUser(ComponentName, UserHandle)} switched to) or stop the user (when it was 11999 * {@link #startUserInBackground(ComponentName, UserHandle) started in background}. 12000 * 12001 * <p>Notice that on devices running with 12002 * {@link UserManager#isHeadlessSystemUserMode() headless system user mode}, there is no primary 12003 * user, so it switches back to the user that was in the foreground before the first call to 12004 * {@link #switchUser(ComponentName, UserHandle)} (or fails with 12005 * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN} if that method was not called prior to this 12006 * call). 12007 * 12008 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 12009 * @return one of the following result codes: 12010 * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN}, 12011 * {@link UserManager#USER_OPERATION_SUCCESS}, 12012 * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE}, 12013 * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER} 12014 * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device. 12015 * @see #getSecondaryUsers(ComponentName) 12016 */ logoutUser(@onNull ComponentName admin)12017 public @UserOperationResult int logoutUser(@NonNull ComponentName admin) { 12018 throwIfParentInstance("logoutUser"); 12019 try { 12020 return mService.logoutUser(admin); 12021 } catch (RemoteException re) { 12022 throw re.rethrowFromSystemServer(); 12023 } 12024 } 12025 12026 /** 12027 * Called by a profile owner of an organization-owned device to specify {@link 12028 * ManagedSubscriptionsPolicy} 12029 * 12030 * <p>Managed subscriptions policy controls how SIMs would be associated with the 12031 * managed profile. For example a policy of type 12032 * {@link ManagedSubscriptionsPolicy#TYPE_ALL_MANAGED_SUBSCRIPTIONS} assigns all 12033 * SIM-based subscriptions to the managed profile. In this case OEM default 12034 * dialer and messages app are automatically installed in the managed profile 12035 * and all incoming and outgoing calls and text messages are handled by them. 12036 * <p>This API can only be called during device setup. 12037 * 12038 * @param policy {@link ManagedSubscriptionsPolicy} policy, passing null for this resets the 12039 * policy to be the default. 12040 * @throws SecurityException if the caller is not a profile owner on an organization-owned 12041 * managed profile. 12042 * @throws IllegalStateException if called after the device setup has been completed. 12043 * @throws UnsupportedOperationException if managed subscriptions policy is not explicitly 12044 * enabled by the device policy management role holder during device setup. 12045 * @see ManagedSubscriptionsPolicy 12046 */ setManagedSubscriptionsPolicy(@ullable ManagedSubscriptionsPolicy policy)12047 public void setManagedSubscriptionsPolicy(@Nullable ManagedSubscriptionsPolicy policy) { 12048 throwIfParentInstance("setManagedSubscriptionsPolicy"); 12049 try { 12050 mService.setManagedSubscriptionsPolicy(policy); 12051 } catch (RemoteException re) { 12052 throw re.rethrowFromSystemServer(); 12053 } 12054 } 12055 12056 /** 12057 * Returns the current {@link ManagedSubscriptionsPolicy}. 12058 * If the policy has not been set, it will return a default policy of Type {@link 12059 * ManagedSubscriptionsPolicy#TYPE_ALL_PERSONAL_SUBSCRIPTIONS}. 12060 * 12061 * @see #setManagedSubscriptionsPolicy(ManagedSubscriptionsPolicy) 12062 */ 12063 @NonNull getManagedSubscriptionsPolicy()12064 public ManagedSubscriptionsPolicy getManagedSubscriptionsPolicy() { 12065 throwIfParentInstance("getManagedSubscriptionsPolicy"); 12066 try { 12067 return mService.getManagedSubscriptionsPolicy(); 12068 } catch (RemoteException re) { 12069 throw re.rethrowFromSystemServer(); 12070 } 12071 } 12072 12073 /** 12074 * Similar to {@link #logoutUser(ComponentName)}, except: 12075 * 12076 * <ul> 12077 * <li>Called by system (like Settings), not admin. 12078 * <li>It logs out the current user, not the caller. 12079 * </ul> 12080 * 12081 * @hide 12082 */ 12083 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 12084 android.Manifest.permission.INTERACT_ACROSS_USERS}) 12085 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) logoutUser()12086 public @UserOperationResult int logoutUser() { 12087 // TODO(b/214336184): add CTS test 12088 try { 12089 return mService.logoutUserInternal(); 12090 } catch (RemoteException re) { 12091 throw re.rethrowFromSystemServer(); 12092 } 12093 } 12094 12095 /** 12096 * Gets the user a {@link #logoutUser(ComponentName)} call would switch to, 12097 * or {@code null} if the current user is not in a session (i.e., if it was not 12098 * {@link #switchUser(ComponentName, UserHandle) switched} or 12099 * {@link #startUserInBackground(ComponentName, UserHandle) started in background} by the 12100 * device admin. 12101 * 12102 * @hide 12103 */ 12104 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 12105 android.Manifest.permission.INTERACT_ACROSS_USERS}) 12106 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) getLogoutUser()12107 public @Nullable UserHandle getLogoutUser() { 12108 // TODO(b/214336184): add CTS test 12109 try { 12110 int userId = mService.getLogoutUserId(); 12111 return userId == UserHandle.USER_NULL ? null : UserHandle.of(userId); 12112 } catch (RemoteException re) { 12113 throw re.rethrowFromSystemServer(); 12114 } 12115 } 12116 12117 /** 12118 * Called by a device owner to list all secondary users on the device. Managed profiles are not 12119 * considered as secondary users. 12120 * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser} 12121 * and {@link #stopUser}. 12122 * 12123 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 12124 * @return list of other {@link UserHandle}s on the device. 12125 * @throws SecurityException if {@code admin} is not a device owner. 12126 * @see #removeUser(ComponentName, UserHandle) 12127 * @see #switchUser(ComponentName, UserHandle) 12128 * @see #startUserInBackground(ComponentName, UserHandle) 12129 * @see #stopUser(ComponentName, UserHandle) 12130 */ getSecondaryUsers(@onNull ComponentName admin)12131 public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) { 12132 throwIfParentInstance("getSecondaryUsers"); 12133 try { 12134 return mService.getSecondaryUsers(admin); 12135 } catch (RemoteException re) { 12136 throw re.rethrowFromSystemServer(); 12137 } 12138 } 12139 12140 /** 12141 * Checks if the profile owner is running in an ephemeral user. 12142 * 12143 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 12144 * @return whether the profile owner is running in an ephemeral user. 12145 */ isEphemeralUser(@onNull ComponentName admin)12146 public boolean isEphemeralUser(@NonNull ComponentName admin) { 12147 throwIfParentInstance("isEphemeralUser"); 12148 try { 12149 return mService.isEphemeralUser(admin); 12150 } catch (RemoteException re) { 12151 throw re.rethrowFromSystemServer(); 12152 } 12153 } 12154 12155 /** 12156 * Retrieves the application restrictions for a given target application running in the calling 12157 * user. 12158 * <p> 12159 * The caller must be a profile or device owner on that user, or the package allowed to manage 12160 * application restrictions via {@link #setDelegatedScopes} with the 12161 * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown. 12162 * 12163 * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread 12164 * 12165 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 12166 * {@code null} if called by the application restrictions managing package. 12167 * @param packageName The name of the package to fetch restricted settings of. 12168 * @return {@link Bundle} of settings corresponding to what was set last time 12169 * {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty 12170 * {@link Bundle} if no restrictions have been set. 12171 * @throws SecurityException if {@code admin} is not a device or profile owner. 12172 * @see #setDelegatedScopes 12173 * @see #DELEGATION_APP_RESTRICTIONS 12174 */ 12175 @WorkerThread getApplicationRestrictions( @ullable ComponentName admin, String packageName)12176 public @NonNull Bundle getApplicationRestrictions( 12177 @Nullable ComponentName admin, String packageName) { 12178 12179 if (mService != null) { 12180 try { 12181 return mService.getApplicationRestrictions(admin, mContext.getPackageName(), 12182 packageName, mParentInstance); 12183 } catch (RemoteException e) { 12184 throw e.rethrowFromSystemServer(); 12185 } 12186 } 12187 return null; 12188 } 12189 12190 /** 12191 * Called by a profile owner, device owner or a holder of any permission that is associated with 12192 * a user restriction to set a user restriction specified by the key. 12193 * <p> 12194 * The calling device admin must be a profile owner, device owner or holder of any permission 12195 * that is associated with a user restriction; if it is not, a security 12196 * exception will be thrown. 12197 * <p> 12198 * The profile owner of an organization-owned managed profile may invoke this method on 12199 * the {@link DevicePolicyManager} instance it obtained from 12200 * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions. 12201 * <p> 12202 * See the constants in {@link android.os.UserManager} for the list of restrictions that can 12203 * be enforced device-wide. These constants will also state in their documentation which 12204 * permission is required to manage the restriction using this API. 12205 * 12206 * <p> 12207 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the user restriction 12208 * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 12209 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 12210 * successfully set or not. This callback will contain: 12211 * <ul> 12212 * <li> The policy identifier returned from 12213 * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)} 12214 * <li> The {@link TargetUser} that this policy relates to 12215 * <li> The {@link PolicyUpdateResult}, which will be 12216 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 12217 * reason the policy failed to be set 12218 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 12219 * </ul> 12220 * If there has been a change to the policy, 12221 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 12222 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 12223 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 12224 * will contain the reason why the policy changed. 12225 * 12226 * @param admin Which {@link DeviceAdminReceiver} this request is associated with or 12227 * {@code null} if the caller is not a device admin. 12228 * @param key The key of the restriction. 12229 * @throws SecurityException if {@code admin} is not a device or profile owner and if the caller 12230 * has not been granted the permission to set the given user restriction. 12231 */ 12232 // NB: For permission-based callers using this API will result in applying the restriction 12233 // locally on the calling user or locally on the parent profile if called from through parent 12234 // instance. To set a restriction globally, call addUserRestrictionGlobally() instead. 12235 // Permission-based callers must target Android U or above. 12236 @SupportsCoexistence addUserRestriction(@ullable ComponentName admin, @UserManager.UserRestrictionKey String key)12237 public void addUserRestriction(@Nullable ComponentName admin, 12238 @UserManager.UserRestrictionKey String key) { 12239 if (mService != null) { 12240 try { 12241 mService.setUserRestriction( 12242 admin, mContext.getPackageName(), key, true, mParentInstance); 12243 } catch (RemoteException e) { 12244 throw e.rethrowFromSystemServer(); 12245 } 12246 } 12247 } 12248 12249 /** 12250 * Adds a user restriction on {@code targetUser}, specified by the {@code key}. 12251 * 12252 * <p>Called by a system service only, meaning that the caller's UID must be equal to 12253 * {@link Process#SYSTEM_UID}. 12254 * 12255 * @param systemEntity The service entity that adds the restriction. A user restriction set by 12256 * a service entity can only be cleared by the same entity. This can be 12257 * just the calling package name, or any string of the caller's choice 12258 * can be used. 12259 * @param key The key of the restriction. 12260 * @param targetUser The user to add the restriction on. 12261 * @throws SecurityException if the caller is not a system service 12262 * 12263 * @hide 12264 */ addUserRestriction(@onNull String systemEntity, @NonNull @UserManager.UserRestrictionKey String key, @UserIdInt int targetUser)12265 public void addUserRestriction(@NonNull String systemEntity, 12266 @NonNull @UserManager.UserRestrictionKey String key, @UserIdInt int targetUser) { 12267 if (mService != null) { 12268 try { 12269 mService.setUserRestrictionForUser( 12270 systemEntity, key, /* enable= */ true, targetUser); 12271 } catch (RemoteException e) { 12272 throw e.rethrowFromSystemServer(); 12273 } 12274 } 12275 } 12276 12277 /** 12278 * Called by a profile owner, device owner or a holder of any permission that is associated with 12279 * a user restriction to set a user restriction specified by the provided {@code key} globally 12280 * on all users. To clear the restriction use {@link #clearUserRestriction}. 12281 * 12282 * <p>For a given user, a restriction will be set if it was applied globally or locally by any 12283 * admin. 12284 * 12285 * <p> The calling device admin must be a profile owner, device owner or a holder of any 12286 * permission that is associated with a user restriction; if it is not, a security 12287 * exception will be thrown. 12288 * 12289 * <p> See the constants in {@link android.os.UserManager} for the list of restrictions that can 12290 * be enforced device-wide. These constants will also state in their documentation which 12291 * permission is required to manage the restriction using this API. 12292 * <p> 12293 * After the user restriction policy has been set, 12294 * {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle, TargetUser, 12295 * PolicyUpdateResult)} will notify the admin on whether the policy was successfully set or not. 12296 * This callback will contain: 12297 * <ul> 12298 * <li> The policy identifier returned from 12299 * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)} 12300 * <li> The {@link TargetUser} that this policy relates to 12301 * <li> The {@link PolicyUpdateResult}, which will be 12302 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 12303 * reason the policy failed to be set 12304 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 12305 * </ul> 12306 * If there has been a change to the policy, 12307 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 12308 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 12309 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 12310 * will contain the reason why the policy changed. 12311 * 12312 * @param key The key of the restriction. 12313 * @throws SecurityException if {@code admin} is not a device or profile owner and if the 12314 * caller has not been granted the permission to set the given user restriction. 12315 * @throws IllegalStateException if caller is not targeting Android 12316 * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or above. 12317 */ 12318 @SupportsCoexistence addUserRestrictionGlobally(@onNull @serManager.UserRestrictionKey String key)12319 public void addUserRestrictionGlobally(@NonNull @UserManager.UserRestrictionKey String key) { 12320 throwIfParentInstance("addUserRestrictionGlobally"); 12321 if (mService != null) { 12322 try { 12323 mService.setUserRestrictionGlobally(mContext.getPackageName(), key); 12324 } catch (RemoteException e) { 12325 throw e.rethrowFromSystemServer(); 12326 } 12327 } 12328 } 12329 12330 /** 12331 * Adds a user restriction globally, specified by the {@code key}. 12332 * 12333 * <p>Called by a system service only, meaning that the caller's UID must be equal to 12334 * {@link Process#SYSTEM_UID}. 12335 * 12336 * @param systemEntity The service entity that adds the restriction. A user restriction set by 12337 * a service entity can only be cleared by the same entity. This can be 12338 * just the calling package name, or any string of the caller's choice 12339 * can be used. 12340 * @param key The key of the restriction. 12341 * @throws SecurityException if the caller is not a system service. 12342 * 12343 * @hide 12344 */ addUserRestrictionGlobally(@onNull String systemEntity, @NonNull @UserManager.UserRestrictionKey String key)12345 public void addUserRestrictionGlobally(@NonNull String systemEntity, 12346 @NonNull @UserManager.UserRestrictionKey String key) { 12347 if (mService != null) { 12348 try { 12349 mService.setUserRestrictionGloballyFromSystem(systemEntity, key, 12350 /* enable= */ true); 12351 } catch (RemoteException e) { 12352 throw e.rethrowFromSystemServer(); 12353 } 12354 } 12355 } 12356 12357 /** 12358 * Called by a profile owner, device owner or a holder of any permission that is associated with 12359 * a user restriction to clear a user restriction specified by the key. 12360 * <p> 12361 * The calling device admin must be a profile or device owner; if it is not, a security 12362 * exception will be thrown. 12363 * <p> 12364 * The profile owner of an organization-owned managed profile may invoke this method on 12365 * the {@link DevicePolicyManager} instance it obtained from 12366 * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions. 12367 * <p> 12368 * See the constants in {@link android.os.UserManager} for the list of restrictions. These 12369 * constants state in their documentation which permission is required to manage the restriction 12370 * using this API. 12371 * 12372 * <p> 12373 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the user restriction 12374 * policy has been cleared, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 12375 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 12376 * successfully cleared or not. This callback will contain: 12377 * <ul> 12378 * <li> The policy identifier returned from 12379 * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)} 12380 * <li> The {@link TargetUser} that this policy relates to 12381 * <li> The {@link PolicyUpdateResult}, which will be 12382 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully cleared or the 12383 * reason the policy failed to be cleared 12384 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 12385 * </ul> 12386 * If there has been a change to the policy, 12387 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 12388 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 12389 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 12390 * will contain the reason why the policy changed. 12391 * 12392 * @param admin Which {@link DeviceAdminReceiver} this request is associated with or 12393 * {@code null} if the caller is not a device admin. 12394 * @param key The key of the restriction. 12395 * @throws SecurityException if {@code admin} is not a device or profile owner and if the 12396 * caller has not been granted the permission to set the given user restriction. 12397 */ 12398 // NB: For permission-based callers using this API will result in clearing any local and global 12399 // restriction with the specified key that was previously set by the caller. 12400 // Permission-based callers must target Android U or above. 12401 @SupportsCoexistence clearUserRestriction(@ullable ComponentName admin, @UserManager.UserRestrictionKey String key)12402 public void clearUserRestriction(@Nullable ComponentName admin, 12403 @UserManager.UserRestrictionKey String key) { 12404 if (mService != null) { 12405 try { 12406 mService.setUserRestriction( 12407 admin, mContext.getPackageName(), key, false, mParentInstance); 12408 } catch (RemoteException e) { 12409 throw e.rethrowFromSystemServer(); 12410 } 12411 } 12412 } 12413 12414 /** 12415 * Clears a user restriction from {@code targetUser}, specified by the {@code key}. 12416 * 12417 * <p>Called by a system service only, meaning that the caller's UID must be equal to 12418 * {@link Process#SYSTEM_UID}. 12419 * 12420 * @param systemEntity The system entity that clears the restriction. A user restriction 12421 * set by a system entity can only be cleared by the same entity. This 12422 * can be just the calling package name, or any string of the caller's 12423 * choice can be used. 12424 * @param key The key of the restriction. 12425 * @param targetUser The user to clear the restriction from. 12426 * @throws SecurityException if the caller is not a system service 12427 * 12428 * @hide 12429 */ clearUserRestriction(@onNull String systemEntity, @NonNull @UserManager.UserRestrictionKey String key, @UserIdInt int targetUser)12430 public void clearUserRestriction(@NonNull String systemEntity, 12431 @NonNull @UserManager.UserRestrictionKey String key, @UserIdInt int targetUser) { 12432 if (mService != null) { 12433 try { 12434 mService.setUserRestrictionForUser( 12435 systemEntity, key, /* enable= */ false, targetUser); 12436 } catch (RemoteException e) { 12437 throw e.rethrowFromSystemServer(); 12438 } 12439 } 12440 } 12441 12442 /** 12443 * Clears a user restriction globally, specified by the {@code key}. 12444 * 12445 * <p>Called by a system service only, meaning that the caller's UID must be equal to 12446 * {@link Process#SYSTEM_UID}. 12447 * 12448 * @param systemEntity The system entity that clears the restriction. A user restriction 12449 * set by a system entity can only be cleared by the same entity. This 12450 * can be just the calling package name, or any string of the caller's 12451 * choice can be used. 12452 * @param key The key of the restriction. 12453 * @throws SecurityException if the caller is not a system service. 12454 * 12455 * @hide 12456 */ clearUserRestrictionGlobally(@onNull String systemEntity, @NonNull @UserManager.UserRestrictionKey String key)12457 public void clearUserRestrictionGlobally(@NonNull String systemEntity, 12458 @NonNull @UserManager.UserRestrictionKey String key) { 12459 if (mService != null) { 12460 try { 12461 mService.setUserRestrictionGloballyFromSystem(systemEntity, key, 12462 /* enable= */ false); 12463 } catch (RemoteException e) { 12464 throw e.rethrowFromSystemServer(); 12465 } 12466 } 12467 } 12468 12469 /** 12470 * Called by an admin to get user restrictions set by themselves with 12471 * {@link #addUserRestriction(ComponentName, String)}. 12472 * <p> 12473 * The target user may have more restrictions set by the system or other admin. 12474 * To get all the user restrictions currently set, use 12475 * {@link UserManager#getUserRestrictions()}. 12476 * <p> 12477 * The profile owner of an organization-owned managed profile may invoke this method on 12478 * the {@link DevicePolicyManager} instance it obtained from 12479 * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions 12480 * it previously set with {@link #addUserRestriction(ComponentName, String)}. 12481 * 12482 * <p>For callers targeting Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or 12483 * above, this API will return the local restrictions set on the calling user, or on the parent 12484 * profile if called from the {@link DevicePolicyManager} instance obtained from 12485 * {@link #getParentProfileInstance(ComponentName)}. To get global restrictions set by admin, 12486 * call {@link #getUserRestrictionsGlobally()} instead. 12487 * 12488 * <p>Note that this is different that the returned restrictions for callers targeting pre 12489 * Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, were this API returns 12490 * all local/global restrictions set by the admin on the calling user using 12491 * {@link #addUserRestriction(ComponentName, String)} or the parent user if called on the 12492 * {@link DevicePolicyManager} instance it obtained from {@link #getParentProfileInstance}. 12493 * 12494 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 12495 * @return a {@link Bundle} whose keys are the user restrictions, and the values a 12496 * {@code boolean} indicating whether the restriction is set. 12497 * @throws SecurityException if {@code admin} is not a device or profile owner. 12498 */ getUserRestrictions(@onNull ComponentName admin)12499 public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) { 12500 Bundle ret = null; 12501 if (mService != null) { 12502 try { 12503 ret = mService.getUserRestrictions( 12504 admin, mContext.getPackageName(), mParentInstance); 12505 } catch (RemoteException e) { 12506 throw e.rethrowFromSystemServer(); 12507 } 12508 } 12509 return ret == null ? new Bundle() : ret; 12510 } 12511 12512 /** 12513 * Called by a profile or device owner to get global user restrictions set with 12514 * {@link #addUserRestrictionGlobally(String)}. 12515 * <p> 12516 * To get all the user restrictions currently set for a certain user, use 12517 * {@link UserManager#getUserRestrictions()}. 12518 * @return a {@link Bundle} whose keys are the user restrictions, and the values a 12519 * {@code boolean} indicating whether the restriction is set. 12520 * @throws SecurityException if {@code admin} is not a device or profile owner. 12521 * @throws IllegalStateException if caller is not targeting Android 12522 * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or above. 12523 */ getUserRestrictionsGlobally()12524 public @NonNull Bundle getUserRestrictionsGlobally() { 12525 throwIfParentInstance("createAdminSupportIntent"); 12526 Bundle ret = null; 12527 if (mService != null) { 12528 try { 12529 ret = mService.getUserRestrictionsGlobally(mContext.getPackageName()); 12530 } catch (RemoteException e) { 12531 throw e.rethrowFromSystemServer(); 12532 } 12533 } 12534 return ret == null ? new Bundle() : ret; 12535 } 12536 12537 /** 12538 * Called by any app to display a support dialog when a feature was disabled by an admin. 12539 * This returns an intent that can be used with {@link Context#startActivity(Intent)} to 12540 * display the dialog. It will tell the user that the feature indicated by {@code restriction} 12541 * was disabled by an admin, and include a link for more information. The default content of 12542 * the dialog can be changed by the restricting admin via 12543 * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not 12544 * set (i.e. the feature is available), then the return value will be {@code null}. 12545 * @param restriction Indicates for which feature the dialog should be displayed. Can be a 12546 * user restriction from {@link UserManager}, e.g. 12547 * {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants 12548 * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}. 12549 * @return Intent An intent to be used to start the dialog-activity if the restriction is 12550 * set by an admin, or null if the restriction does not exist or no admin set it. 12551 */ createAdminSupportIntent(@onNull String restriction)12552 public Intent createAdminSupportIntent(@NonNull String restriction) { 12553 throwIfParentInstance("createAdminSupportIntent"); 12554 Intent result = null; 12555 if (mService != null) { 12556 try { 12557 result = mService.createAdminSupportIntent(restriction); 12558 if (result != null) { 12559 result.prepareToEnterProcess(LOCAL_FLAG_FROM_SYSTEM, 12560 mContext.getAttributionSource()); 12561 } 12562 } catch (RemoteException e) { 12563 throw e.rethrowFromSystemServer(); 12564 } 12565 } 12566 return result; 12567 } 12568 12569 /** 12570 * @param userId The user for whom to retrieve information. 12571 * @param restriction The restriction enforced by admin. It could be any user restriction or 12572 * policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and 12573 * {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}. 12574 * @return Details of admin and user which enforced the restriction for the userId. If 12575 * restriction is null, profile owner for the user or device owner info is returned. 12576 * @hide 12577 */ getEnforcingAdminAndUserDetails(int userId, @Nullable String restriction)12578 public @Nullable Bundle getEnforcingAdminAndUserDetails(int userId, 12579 @Nullable String restriction) { 12580 if (mService != null) { 12581 try { 12582 return mService.getEnforcingAdminAndUserDetails(userId, restriction); 12583 } catch (RemoteException e) { 12584 throw e.rethrowFromSystemServer(); 12585 } 12586 } 12587 return null; 12588 } 12589 12590 /** 12591 * Returns the {@link EnforcingAdmin} who have set this policy. 12592 * 12593 * <p>Important: this API is a temporary solution, hence should be kept hidden. That is because 12594 * the string argument can't define policies with arguments. 12595 * 12596 * <p>Note that for {@link #POLICY_SUSPEND_PACKAGES} it returns the PO or DO to keep the 12597 * behavior the same as before the bug fix for b/192245204. 12598 * 12599 * <p>This API is only callable by the system UID 12600 * 12601 * @param userId The user for whom to retrieve the information. 12602 * @param identifier The policy enforced by admins. It could be any user restriction or 12603 * policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and 12604 * {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}. This also works 12605 * for {@link DevicePolicyIdentifiers#MEMORY_TAGGING_POLICY}. 12606 * 12607 * @hide 12608 */ getEnforcingAdmin(int userId, String identifier)12609 public @Nullable EnforcingAdmin getEnforcingAdmin(int userId, String identifier) { 12610 if (mService != null) { 12611 try { 12612 return mService.getEnforcingAdmin(userId, identifier); 12613 } catch (RemoteException e) { 12614 throw e.rethrowFromSystemServer(); 12615 } 12616 } 12617 return null; 12618 } 12619 12620 /** 12621 * Returns the list of {@link EnforcingAdmin}s who have set this restriction. 12622 * 12623 * <p>Note that for {@link #POLICY_SUSPEND_PACKAGES} it returns the PO or DO to keep the 12624 * behavior the same as before the bug fix for b/192245204. 12625 * 12626 * <p>This API is only callable by the system UID 12627 * 12628 * @param userId The user for whom to retrieve the information. 12629 * @param restriction The restriction enforced by admins. It could be any user restriction or 12630 * policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and 12631 * {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}. 12632 * 12633 * @hide 12634 */ getEnforcingAdminsForRestriction(int userId, @NonNull String restriction)12635 public @NonNull Set<EnforcingAdmin> getEnforcingAdminsForRestriction(int userId, 12636 @NonNull String restriction) { 12637 if (mService != null) { 12638 try { 12639 return new HashSet<>(mService.getEnforcingAdminsForRestriction( 12640 userId, restriction)); 12641 } catch (RemoteException e) { 12642 throw e.rethrowFromSystemServer(); 12643 } 12644 } 12645 return null; 12646 } 12647 12648 /** 12649 * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and 12650 * actual package file remain. This function can be called by a device owner, profile owner, or 12651 * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via 12652 * {@link #setDelegatedScopes}. 12653 * <p> 12654 * This method can be called on the {@link DevicePolicyManager} instance, returned by 12655 * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner 12656 * of an organization-owned managed profile and the package must be a system package. If called 12657 * on the parent instance, then the package is hidden or unhidden in the personal profile. 12658 * <p> 12659 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the application hidden 12660 * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 12661 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 12662 * successfully set or not. This callback will contain: 12663 * <ul> 12664 * <li> The policy identifier 12665 * {@link DevicePolicyIdentifiers#APPLICATION_HIDDEN_POLICY} 12666 * <li> The additional policy params bundle, which contains 12667 * {@link PolicyUpdateReceiver#EXTRA_PACKAGE_NAME} the package name the policy applies to 12668 * <li> The {@link TargetUser} that this policy relates to 12669 * <li> The {@link PolicyUpdateResult}, which will be 12670 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 12671 * reason the policy failed to be set 12672 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 12673 * </ul> 12674 * If there has been a change to the policy, 12675 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 12676 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 12677 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 12678 * will contain the reason why the policy changed. 12679 * 12680 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 12681 * {@code null} if the caller is not a device admin. 12682 * @param packageName The name of the package to hide or unhide. 12683 * @param hidden {@code true} if the package should be hidden, {@code false} if it should be 12684 * unhidden. 12685 * @return boolean Whether the hidden setting of the package was successfully updated. 12686 * @throws SecurityException if {@code admin} is not a device or profile owner or if called on 12687 * the parent profile and the {@code admin} is not a profile owner of an 12688 * organization-owned managed profile. 12689 * @throws IllegalArgumentException if called on the parent profile and the package provided 12690 * is not a system package. 12691 * @see #setDelegatedScopes 12692 * @see #DELEGATION_PACKAGE_ACCESS 12693 */ 12694 @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true) 12695 @SupportsCoexistence setApplicationHidden(@ullable ComponentName admin, String packageName, boolean hidden)12696 public boolean setApplicationHidden(@Nullable ComponentName admin, String packageName, 12697 boolean hidden) { 12698 if (mService != null) { 12699 try { 12700 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName, 12701 hidden, mParentInstance); 12702 } catch (RemoteException e) { 12703 throw e.rethrowFromSystemServer(); 12704 } 12705 } 12706 return false; 12707 } 12708 12709 /** 12710 * Determine if a package is hidden. This function can be called by a device owner, profile 12711 * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via 12712 * {@link #setDelegatedScopes}. 12713 * <p> 12714 * This method can be called on the {@link DevicePolicyManager} instance, returned by 12715 * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner 12716 * of an organization-owned managed profile and the package must be a system package. If called 12717 * on the parent instance, this will determine whether the package is hidden or unhidden in the 12718 * personal profile. 12719 * <p> 12720 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the 12721 * current resolved policy rather than the policy set by the calling admin. 12722 * 12723 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 12724 * {@code null} if the caller is not a device admin. 12725 * @param packageName The name of the package to retrieve the hidden status of. 12726 * @return boolean {@code true} if the package is hidden, {@code false} otherwise. 12727 * @throws SecurityException if {@code admin} is not a device or profile owner or if called on 12728 * the parent profile and the {@code admin} is not a profile owner of an 12729 * organization-owned managed profile. 12730 * @throws IllegalArgumentException if called on the parent profile and the package provided 12731 * is not a system package. 12732 * @see #setDelegatedScopes 12733 * @see #DELEGATION_PACKAGE_ACCESS 12734 */ 12735 @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true) isApplicationHidden(@ullable ComponentName admin, String packageName)12736 public boolean isApplicationHidden(@Nullable ComponentName admin, String packageName) { 12737 if (mService != null) { 12738 try { 12739 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName, 12740 mParentInstance); 12741 } catch (RemoteException e) { 12742 throw e.rethrowFromSystemServer(); 12743 } 12744 } 12745 return false; 12746 } 12747 12748 /** 12749 * Re-enable a system app that was disabled by default when the user was initialized. This 12750 * function can be called by a device owner, profile owner, or by a delegate given the 12751 * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}. 12752 * 12753 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 12754 * {@code null} if the caller is an enable system app delegate. 12755 * @param packageName The package to be re-enabled in the calling profile. 12756 * @throws SecurityException if {@code admin} is not a device or profile owner. 12757 * @see #setDelegatedScopes 12758 * @see #DELEGATION_PACKAGE_ACCESS 12759 */ enableSystemApp(@onNull ComponentName admin, String packageName)12760 public void enableSystemApp(@NonNull ComponentName admin, String packageName) { 12761 throwIfParentInstance("enableSystemApp"); 12762 if (mService != null) { 12763 try { 12764 mService.enableSystemApp(admin, mContext.getPackageName(), packageName); 12765 } catch (RemoteException e) { 12766 throw e.rethrowFromSystemServer(); 12767 } 12768 } 12769 } 12770 12771 /** 12772 * Re-enable system apps by intent that were disabled by default when the user was initialized. 12773 * This function can be called by a device owner, profile owner, or by a delegate given the 12774 * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}. 12775 * 12776 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 12777 * {@code null} if the caller is an enable system app delegate. 12778 * @param intent An intent matching the app(s) to be installed. All apps that resolve for this 12779 * intent will be re-enabled in the calling profile. 12780 * @return int The number of activities that matched the intent and were installed. 12781 * @throws SecurityException if {@code admin} is not a device or profile owner. 12782 * @see #setDelegatedScopes 12783 * @see #DELEGATION_PACKAGE_ACCESS 12784 */ enableSystemApp(@onNull ComponentName admin, Intent intent)12785 public int enableSystemApp(@NonNull ComponentName admin, Intent intent) { 12786 throwIfParentInstance("enableSystemApp"); 12787 if (mService != null) { 12788 try { 12789 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent); 12790 } catch (RemoteException e) { 12791 throw e.rethrowFromSystemServer(); 12792 } 12793 } 12794 return 0; 12795 } 12796 12797 /** 12798 * Install an existing package that has been installed in another user, or has been kept after 12799 * removal via {@link #setKeepUninstalledPackages}. 12800 * This function can be called by a device owner, profile owner or a delegate given 12801 * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}. 12802 * When called in a secondary user or managed profile, the user/profile must be affiliated with 12803 * the device. See {@link #isAffiliatedUser}. 12804 * 12805 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 12806 * @param packageName The package to be installed in the calling profile. 12807 * @return {@code true} if the app is installed; {@code false} otherwise. 12808 * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of 12809 * an affiliated user or profile. 12810 * @see #setKeepUninstalledPackages 12811 * @see #setDelegatedScopes 12812 * @see #isAffiliatedUser 12813 * @see #DELEGATION_PACKAGE_ACCESS 12814 */ installExistingPackage(@onNull ComponentName admin, String packageName)12815 public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) { 12816 throwIfParentInstance("installExistingPackage"); 12817 if (mService != null) { 12818 try { 12819 return mService.installExistingPackage(admin, mContext.getPackageName(), 12820 packageName); 12821 } catch (RemoteException e) { 12822 throw e.rethrowFromSystemServer(); 12823 } 12824 } 12825 return false; 12826 } 12827 12828 /** 12829 * Called by a device owner or profile owner to disable account management for a specific type 12830 * of account. 12831 * <p> 12832 * The calling device admin must be a device owner or profile owner. If it is not, a security 12833 * exception will be thrown. 12834 * <p> 12835 * When account management is disabled for an account type, adding or removing an account of 12836 * that type will not be possible. 12837 * <p> 12838 * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use 12839 * {@link android.accounts.AccountManager} APIs to add or remove accounts when account 12840 * management for a specific type is disabled. 12841 * <p> 12842 * This method may be called on the {@code DevicePolicyManager} instance returned from 12843 * {@link #getParentProfileInstance(ComponentName)} by the profile owner on an 12844 * organization-owned device, to restrict accounts that may not be managed on the primary 12845 * profile. 12846 * <p> 12847 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the account management 12848 * disabled policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 12849 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 12850 * successfully set or not. This callback will contain: 12851 * <ul> 12852 * <li> The policy identifier 12853 * {@link DevicePolicyIdentifiers#ACCOUNT_MANAGEMENT_DISABLED_POLICY} 12854 * <li> The additional policy params bundle, which contains 12855 * {@link PolicyUpdateReceiver#EXTRA_ACCOUNT_TYPE} the account type the policy applies to 12856 * <li> The {@link TargetUser} that this policy relates to 12857 * <li> The {@link PolicyUpdateResult}, which will be 12858 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 12859 * reason the policy failed to be set 12860 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 12861 * </ul> 12862 * If there has been a change to the policy, 12863 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 12864 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 12865 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 12866 * will contain the reason why the policy changed. 12867 * 12868 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 12869 * caller is not a device admin. 12870 * @param accountType For which account management is disabled or enabled. 12871 * @param disabled The boolean indicating that account management will be disabled (true) or 12872 * enabled (false). 12873 * @throws SecurityException if {@code admin} is not a device or profile owner. 12874 */ 12875 @RequiresPermission(value = MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT, conditional = true) 12876 @SupportsCoexistence setAccountManagementDisabled(@ullable ComponentName admin, String accountType, boolean disabled)12877 public void setAccountManagementDisabled(@Nullable ComponentName admin, String accountType, 12878 boolean disabled) { 12879 if (mService != null) { 12880 try { 12881 mService.setAccountManagementDisabled(admin, mContext.getPackageName(), accountType, 12882 disabled, mParentInstance); 12883 } catch (RemoteException e) { 12884 throw e.rethrowFromSystemServer(); 12885 } 12886 } 12887 } 12888 12889 /** 12890 * Gets the array of accounts for which account management is disabled by the profile owner 12891 * or device owner. 12892 * 12893 * <p> Account management can be disabled/enabled by calling 12894 * {@link #setAccountManagementDisabled}. 12895 * <p> 12896 * This method may be called on the {@code DevicePolicyManager} instance returned from 12897 * {@link #getParentProfileInstance(ComponentName)}. Note that only a profile owner on 12898 * an organization-owned device can affect account types on the parent profile instance. 12899 * 12900 * @return a list of account types for which account management has been disabled. 12901 * 12902 * @see #setAccountManagementDisabled 12903 */ getAccountTypesWithManagementDisabled()12904 public @Nullable String[] getAccountTypesWithManagementDisabled() { 12905 return getAccountTypesWithManagementDisabledAsUser(myUserId(), mParentInstance); 12906 } 12907 12908 /** 12909 * @see #getAccountTypesWithManagementDisabled() 12910 * Note that calling this method on the parent profile instance will return the same 12911 * value as calling it on the main {@code DevicePolicyManager} instance. 12912 * @hide 12913 */ 12914 @RequiresPermission(value = MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT, conditional = true) getAccountTypesWithManagementDisabledAsUser(int userId)12915 public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 12916 return getAccountTypesWithManagementDisabledAsUser(userId, false); 12917 } 12918 12919 /** 12920 * @see #getAccountTypesWithManagementDisabled() 12921 * @hide 12922 */ getAccountTypesWithManagementDisabledAsUser( int userId, boolean parentInstance)12923 public @Nullable String[] getAccountTypesWithManagementDisabledAsUser( 12924 int userId, boolean parentInstance) { 12925 if (mService != null) { 12926 try { 12927 return mService.getAccountTypesWithManagementDisabledAsUser(userId, 12928 mContext.getPackageName(), parentInstance); 12929 } catch (RemoteException e) { 12930 throw e.rethrowFromSystemServer(); 12931 } 12932 } 12933 12934 return null; 12935 } 12936 12937 /** 12938 * Called by device owner or profile owner to set whether a secondary lockscreen needs to be 12939 * shown. 12940 * 12941 * <p>The secondary lockscreen will by displayed after the primary keyguard security screen 12942 * requirements are met. To provide the lockscreen content the DO/PO will need to provide a 12943 * service handling the {@link #ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE} intent action, 12944 * extending the {@link DevicePolicyKeyguardService} class. 12945 * 12946 * <p>Relevant interactions on the secondary lockscreen should be communicated back to the 12947 * keyguard via {@link IKeyguardCallback}, such as when the screen is ready to be dismissed. 12948 * 12949 * <p>This API, and associated APIs, can only be called by the default supervision app when it 12950 * is set as the device owner or profile owner. 12951 * 12952 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 12953 * @param enabled Whether or not the lockscreen needs to be shown. 12954 * @throws SecurityException if {@code admin} is not a device or profile owner. 12955 * @see #isSecondaryLockscreenEnabled 12956 * @deprecated Use {@link #setSecondaryLockscreenEnabled(boolean,PersistableBundle)} instead. 12957 * @hide 12958 */ 12959 @Deprecated 12960 @SystemApi 12961 @FlaggedApi(FLAG_SECONDARY_LOCKSCREEN_API_ENABLED) setSecondaryLockscreenEnabled(@onNull ComponentName admin, boolean enabled)12962 public void setSecondaryLockscreenEnabled(@NonNull ComponentName admin, boolean enabled) { 12963 throwIfParentInstance("setSecondaryLockscreenEnabled"); 12964 if (mService != null) { 12965 try { 12966 mService.setSecondaryLockscreenEnabled(admin, enabled, null); 12967 } catch (RemoteException e) { 12968 throw e.rethrowFromSystemServer(); 12969 } 12970 } 12971 } 12972 12973 /** 12974 * Called by the system supervision app to set whether a secondary lockscreen needs to be shown. 12975 * 12976 * <p>The secondary lockscreen will by displayed after the primary keyguard security screen 12977 * requirements are met. 12978 * 12979 * <p>This API, and associated APIs, can only be called by the default supervision app. 12980 * 12981 * @param enabled Whether or not the lockscreen needs to be shown. 12982 * @param options A {@link PersistableBundle} to supply options to the lock screen. 12983 * @hide 12984 */ 12985 @SystemApi 12986 @FlaggedApi(FLAG_SECONDARY_LOCKSCREEN_API_ENABLED) setSecondaryLockscreenEnabled(boolean enabled, @Nullable PersistableBundle options)12987 public void setSecondaryLockscreenEnabled(boolean enabled, 12988 @Nullable PersistableBundle options) { 12989 throwIfParentInstance("setSecondaryLockscreenEnabled"); 12990 if (mService != null) { 12991 try { 12992 mService.setSecondaryLockscreenEnabled(null, enabled, options); 12993 } catch (RemoteException e) { 12994 throw e.rethrowFromSystemServer(); 12995 } 12996 } 12997 } 12998 12999 /** 13000 * Returns whether the secondary lock screen needs to be shown. 13001 * @see #setSecondaryLockscreenEnabled 13002 * @hide 13003 */ 13004 @SystemApi isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)13005 public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) { 13006 throwIfParentInstance("isSecondaryLockscreenEnabled"); 13007 if (mService != null) { 13008 try { 13009 return mService.isSecondaryLockscreenEnabled(userHandle); 13010 } catch (RemoteException e) { 13011 throw e.rethrowFromSystemServer(); 13012 } 13013 } 13014 return false; 13015 } 13016 13017 /** 13018 * Sets which packages may enter lock task mode. 13019 * <p> 13020 * Any packages that share uid with an allowed package will also be allowed to activate lock 13021 * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task 13022 * package list results in locked tasks belonging to those packages to be finished. 13023 * <p> 13024 * This function can only be called by the device owner, a profile owner of an affiliated user 13025 * or profile, or the profile owner when no device owner is set or holders of the permission 13026 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. See 13027 * {@link #isAffiliatedUser}. 13028 * Any package set via this method will be cleared if the user becomes unaffiliated. 13029 * <p> 13030 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the lock task policy has 13031 * been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle, TargetUser, 13032 * PolicyUpdateResult)} will notify the admin on whether the policy was successfully set or not. 13033 * This callback will contain: 13034 * <ul> 13035 * <li> The policy identifier {@link DevicePolicyIdentifiers#LOCK_TASK_POLICY} 13036 * <li> The {@link TargetUser} that this policy relates to 13037 * <li> The {@link PolicyUpdateResult}, which will be 13038 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 13039 * reason the policy failed to be set 13040 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 13041 * </ul> 13042 * If there has been a change to the policy, 13043 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 13044 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 13045 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 13046 * will contain the reason why the policy changed. 13047 * <p> 13048 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, lock task features and lock task 13049 * packages are bundled as one policy. A failure to apply one will result in a failure to apply 13050 * the other. 13051 * 13052 * @param packages The list of packages allowed to enter lock task mode 13053 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13054 * caller is not a device admin. 13055 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an 13056 * affiliated user or profile, or the profile owner when no device owner is set or holder of the 13057 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. 13058 * @see #isAffiliatedUser 13059 * @see Activity#startLockTask() 13060 * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String) 13061 * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent) 13062 * @see UserManager#DISALLOW_CREATE_WINDOWS 13063 */ 13064 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true) 13065 @SupportsCoexistence setLockTaskPackages(@ullable ComponentName admin, @NonNull String[] packages)13066 public void setLockTaskPackages(@Nullable ComponentName admin, @NonNull String[] packages) 13067 throws SecurityException { 13068 throwIfParentInstance("setLockTaskPackages"); 13069 if (mService != null) { 13070 try { 13071 mService.setLockTaskPackages(admin, mContext.getPackageName(), packages); 13072 } catch (RemoteException e) { 13073 throw e.rethrowFromSystemServer(); 13074 } 13075 } 13076 } 13077 13078 /** 13079 * Returns the list of packages allowed to start the lock task mode. 13080 * <p> 13081 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the 13082 * current resolved policy rather than the policy set by the calling admin. 13083 * 13084 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13085 * caller is not a device admin. 13086 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an 13087 * affiliated user or profile, or the profile owner when no device owner is set or holder of the 13088 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. 13089 * @see #isAffiliatedUser 13090 * @see #setLockTaskPackages 13091 */ 13092 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true) getLockTaskPackages(@ullable ComponentName admin)13093 public @NonNull String[] getLockTaskPackages(@Nullable ComponentName admin) { 13094 throwIfParentInstance("getLockTaskPackages"); 13095 if (mService != null) { 13096 try { 13097 return mService.getLockTaskPackages(admin, mContext.getPackageName()); 13098 } catch (RemoteException e) { 13099 throw e.rethrowFromSystemServer(); 13100 } 13101 } 13102 return new String[0]; 13103 } 13104 13105 /** 13106 * This function lets the caller know whether the given component is allowed to start the 13107 * lock task mode. 13108 * @param pkg The package to check 13109 */ isLockTaskPermitted(String pkg)13110 public boolean isLockTaskPermitted(String pkg) { 13111 throwIfParentInstance("isLockTaskPermitted"); 13112 if (mService != null) { 13113 try { 13114 return mService.isLockTaskPermitted(pkg); 13115 } catch (RemoteException e) { 13116 throw e.rethrowFromSystemServer(); 13117 } 13118 } 13119 return false; 13120 } 13121 13122 /** 13123 * Sets which system features are enabled when the device runs in lock task mode. This method 13124 * doesn't affect the features when lock task mode is inactive. Any system features not included 13125 * in {@code flags} are implicitly disabled when calling this method. By default, only 13126 * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To 13127 * disable the global actions dialog, call this method omitting 13128 * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}. 13129 * 13130 * <p>This method can only be called by the device owner, a profile owner of an affiliated 13131 * user or profile, or the profile owner when no device owner is set or holders of the 13132 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. See 13133 * {@link #isAffiliatedUser}. 13134 * Any features set using this method are cleared if the user becomes unaffiliated. 13135 * <p> 13136 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the lock task features 13137 * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle, 13138 * TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 13139 * successfully set or not. This callback will contain: 13140 * <ul> 13141 * <li> The policy identifier {@link DevicePolicyIdentifiers#LOCK_TASK_POLICY} 13142 * <li> The {@link TargetUser} that this policy relates to 13143 * <li> The {@link PolicyUpdateResult}, which will be 13144 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 13145 * reason the policy failed to be set 13146 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 13147 * </ul> 13148 * If there has been a change to the policy, 13149 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 13150 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 13151 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 13152 * will contain the reason why the policy changed. 13153 * <p> 13154 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, lock task features and lock task 13155 * packages are bundled as one policy. A failure to apply one will result in a failure to apply 13156 * the other. 13157 * 13158 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13159 * caller is not a device admin. 13160 * @param flags The system features enabled during lock task mode. 13161 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an 13162 * affiliated user or profile, or the profile owner when no device owner is set or holder of the 13163 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. 13164 * @see #isAffiliatedUser 13165 **/ 13166 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true) 13167 @SupportsCoexistence setLockTaskFeatures(@ullable ComponentName admin, @LockTaskFeature int flags)13168 public void setLockTaskFeatures(@Nullable ComponentName admin, @LockTaskFeature int flags) { 13169 throwIfParentInstance("setLockTaskFeatures"); 13170 if (mService != null) { 13171 try { 13172 mService.setLockTaskFeatures(admin, mContext.getPackageName(), flags); 13173 } catch (RemoteException e) { 13174 throw e.rethrowFromSystemServer(); 13175 } 13176 } 13177 } 13178 13179 /** 13180 * Gets which system features are enabled for LockTask mode. 13181 * <p> 13182 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the 13183 * current resolved policy rather than the policy set by the calling admin. 13184 * 13185 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13186 * caller is not a device admin. 13187 * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list. 13188 * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an 13189 * affiliated user or profile, or the profile owner when no device owner is set or holder of the 13190 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. 13191 * @see #isAffiliatedUser 13192 * @see #setLockTaskFeatures 13193 */ 13194 @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true) getLockTaskFeatures(@ullable ComponentName admin)13195 public @LockTaskFeature int getLockTaskFeatures(@Nullable ComponentName admin) { 13196 throwIfParentInstance("getLockTaskFeatures"); 13197 if (mService != null) { 13198 try { 13199 return mService.getLockTaskFeatures(admin, mContext.getPackageName()); 13200 } catch (RemoteException e) { 13201 throw e.rethrowFromSystemServer(); 13202 } 13203 } 13204 return 0; 13205 } 13206 13207 /** 13208 * Sets whether preferential network service is enabled. 13209 * For example, an organization can have a deal/agreement with a carrier that all of 13210 * the work data from its employees’ devices will be sent via a network service dedicated 13211 * for enterprise use. 13212 * 13213 * An example of a supported preferential network service is the Enterprise 13214 * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally 13215 * configure enterprise APN to set up data call for the preferential network service. 13216 * These APNs can be added using {@link #addOverrideApn}. 13217 * 13218 * By default, preferential network service is disabled on the work profile and 13219 * fully managed devices, on supported carriers and devices. 13220 * Admins can explicitly enable it with this API. 13221 * 13222 * <p> This method enables preferential network service with a default configuration. 13223 * To fine-tune the configuration, use {@link #setPreferentialNetworkServiceConfigs) instead. 13224 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 13225 * this method can be called by the profile owner of a managed profile. 13226 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 13227 * This method can be called by the profile owner of a managed profile 13228 * or device owner. 13229 * 13230 * @param enabled whether preferential network service should be enabled. 13231 * @throws SecurityException if the caller is not the profile owner or device owner. 13232 **/ setPreferentialNetworkServiceEnabled(boolean enabled)13233 public void setPreferentialNetworkServiceEnabled(boolean enabled) { 13234 throwIfParentInstance("setPreferentialNetworkServiceEnabled"); 13235 PreferentialNetworkServiceConfig.Builder configBuilder = 13236 new PreferentialNetworkServiceConfig.Builder(); 13237 configBuilder.setEnabled(enabled); 13238 if (enabled) { 13239 configBuilder.setNetworkId(NET_ENTERPRISE_ID_1); 13240 } 13241 setPreferentialNetworkServiceConfigs(List.of(configBuilder.build())); 13242 } 13243 13244 /** 13245 * Indicates whether preferential network service is enabled. 13246 * 13247 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 13248 * This method can be called by the profile owner of a managed profile. 13249 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 13250 * This method can be called by the profile owner of a managed profile 13251 * or device owner. 13252 * 13253 * @return whether preferential network service is enabled. 13254 * @throws SecurityException if the caller is not the profile owner or device owner. 13255 */ isPreferentialNetworkServiceEnabled()13256 public boolean isPreferentialNetworkServiceEnabled() { 13257 throwIfParentInstance("isPreferentialNetworkServiceEnabled"); 13258 return getPreferentialNetworkServiceConfigs().stream().anyMatch(c -> c.isEnabled()); 13259 } 13260 13261 /** 13262 * Sets preferential network configurations. 13263 * {@see PreferentialNetworkServiceConfig} 13264 * 13265 * An example of a supported preferential network service is the Enterprise 13266 * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally 13267 * configure enterprise APN to set up data call for the preferential network service. 13268 * These APNs can be added using {@link #addOverrideApn}. 13269 * 13270 * By default, preferential network service is disabled on the work profile and fully managed 13271 * devices, on supported carriers and devices. Admins can explicitly enable it with this API. 13272 * If admin wants to have multiple enterprise slices, 13273 * it can be configured by passing list of {@link PreferentialNetworkServiceConfig} objects. 13274 * 13275 * @param preferentialNetworkServiceConfigs list of preferential network configurations. 13276 * @throws SecurityException if the caller is not the profile owner or device owner. 13277 **/ setPreferentialNetworkServiceConfigs( @onNull List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs)13278 public void setPreferentialNetworkServiceConfigs( 13279 @NonNull List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) { 13280 throwIfParentInstance("setPreferentialNetworkServiceConfigs"); 13281 if (mService == null) { 13282 return; 13283 } 13284 try { 13285 mService.setPreferentialNetworkServiceConfigs(preferentialNetworkServiceConfigs); 13286 } catch (RemoteException e) { 13287 throw e.rethrowFromSystemServer(); 13288 } 13289 } 13290 13291 /** 13292 * Get preferential network configuration 13293 * {@see PreferentialNetworkServiceConfig} 13294 * 13295 * @return preferential network configuration. 13296 * @throws SecurityException if the caller is not the profile owner or device owner. 13297 */ getPreferentialNetworkServiceConfigs()13298 public @NonNull List<PreferentialNetworkServiceConfig> getPreferentialNetworkServiceConfigs() { 13299 throwIfParentInstance("getPreferentialNetworkServiceConfigs"); 13300 if (mService == null) { 13301 return List.of(PreferentialNetworkServiceConfig.DEFAULT); 13302 } 13303 try { 13304 return mService.getPreferentialNetworkServiceConfigs(); 13305 } catch (RemoteException e) { 13306 throw e.rethrowFromSystemServer(); 13307 } 13308 } 13309 13310 /** 13311 * This method is mostly deprecated. 13312 * Most of the settings that still have an effect have dedicated setter methods or user 13313 * restrictions. See individual settings for details. 13314 * <p> 13315 * Called by device owner to update {@link android.provider.Settings.Global} settings. 13316 * Validation that the value of the setting is in the correct form for the setting type should 13317 * be performed by the caller. 13318 * <p> 13319 * The settings that can be updated with this method are: 13320 * <ul> 13321 * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use 13322 * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling 13323 * debugging features and this setting to turn adb on.</li> 13324 * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li> 13325 * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only 13326 * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if 13327 * {@link #setMaximumTimeToLock} is not used to set a timeout.</li> 13328 * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This 13329 * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li> 13330 * </ul> 13331 * <p> 13332 * The following settings used to be supported, but can be controlled in other ways: 13333 * <ul> 13334 * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and 13335 * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li> 13336 * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use 13337 * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME} 13338 * instead.</li> 13339 * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use 13340 * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li> 13341 * </ul> 13342 * <p> 13343 * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}: 13344 * <ul> 13345 * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use 13346 * {@link android.bluetooth.BluetoothAdapter#enable()} and 13347 * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li> 13348 * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li> 13349 * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use 13350 * {@link android.media.AudioManager#setRingerMode(int)} instead.</li> 13351 * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li> 13352 * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use 13353 * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li> 13354 * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li> 13355 * </ul> 13356 * 13357 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 13358 * @param setting The name of the setting to update. 13359 * @param value The value to update the setting to. 13360 * @throws SecurityException if {@code admin} is not a device owner. 13361 */ setGlobalSetting(@onNull ComponentName admin, String setting, String value)13362 public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) { 13363 throwIfParentInstance("setGlobalSetting"); 13364 if (mService != null) { 13365 try { 13366 mService.setGlobalSetting(admin, setting, value); 13367 } catch (RemoteException e) { 13368 throw e.rethrowFromSystemServer(); 13369 } 13370 } 13371 } 13372 13373 /** @hide */ 13374 @StringDef({ 13375 Settings.System.SCREEN_BRIGHTNESS_MODE, 13376 Settings.System.SCREEN_BRIGHTNESS, 13377 Settings.System.SCREEN_OFF_TIMEOUT 13378 }) 13379 @Retention(RetentionPolicy.SOURCE) 13380 public @interface SystemSettingsWhitelist {} 13381 13382 /** 13383 * Called by a device or profile owner to update {@link android.provider.Settings.System} 13384 * settings. Validation that the value of the setting is in the correct form for the setting 13385 * type should be performed by the caller. 13386 * <p> 13387 * The settings that can be updated by a device owner or profile owner of secondary user with 13388 * this method are: 13389 * <ul> 13390 * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li> 13391 * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li> 13392 * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li> 13393 * </ul> 13394 * <p> 13395 * Starting from Android {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, a 13396 * profile owner on an organization-owned device can call this method on the parent 13397 * {@link DevicePolicyManager} instance returned by 13398 * {@link #getParentProfileInstance(ComponentName)} to set system settings on the parent user. 13399 * 13400 * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT 13401 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 13402 * @param setting The name of the setting to update. 13403 * @param value The value to update the setting to. 13404 * @throws SecurityException if {@code admin} is not a device or profile owner. 13405 */ setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)13406 public void setSystemSetting(@NonNull ComponentName admin, 13407 @NonNull @SystemSettingsWhitelist String setting, String value) { 13408 if (mService != null) { 13409 try { 13410 mService.setSystemSetting(admin, setting, value, mParentInstance); 13411 } catch (RemoteException e) { 13412 throw e.rethrowFromSystemServer(); 13413 } 13414 } 13415 } 13416 13417 /** 13418 * Called by a device owner or a profile owner of an organization-owned managed profile to 13419 * control whether the user can change networks configured by the admin. When this lockdown is 13420 * enabled, the user can still configure and connect to other Wi-Fi networks, or use other Wi-Fi 13421 * capabilities such as tethering. 13422 * <p> 13423 * WiFi network configuration lockdown is controlled by a global settings 13424 * {@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN} and calling 13425 * this API effectively modifies the global settings. Previously device owners can also 13426 * control this directly via {@link #setGlobalSetting} but they are recommended to switch 13427 * to this API. 13428 * 13429 * @param admin admin Which {@link DeviceAdminReceiver} this request is associated 13430 * with. Null if the caller is not a device admin. 13431 * @param lockdown Whether the admin configured networks should be unmodifiable by the 13432 * user. 13433 * @throws SecurityException if caller is not a device owner or a profile owner of an 13434 * organization-owned managed profile. 13435 */ 13436 @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true) setConfiguredNetworksLockdownState( @ullable ComponentName admin, boolean lockdown)13437 public void setConfiguredNetworksLockdownState( 13438 @Nullable ComponentName admin, boolean lockdown) { 13439 throwIfParentInstance("setConfiguredNetworksLockdownState"); 13440 if (mService != null) { 13441 try { 13442 mService.setConfiguredNetworksLockdownState( 13443 admin, mContext.getPackageName(), lockdown); 13444 } catch (RemoteException e) { 13445 throw e.rethrowFromSystemServer(); 13446 } 13447 } 13448 } 13449 13450 /** 13451 * Called by a device owner or a profile owner of an organization-owned managed profile to 13452 * determine whether the user is prevented from modifying networks configured by the admin. 13453 * 13454 * @param admin admin Which {@link DeviceAdminReceiver} this request is associated 13455 * with. 13456 * @throws SecurityException if caller is not a device owner or a profile owner of an 13457 * organization-owned managed profile. 13458 */ 13459 @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true) hasLockdownAdminConfiguredNetworks(@ullable ComponentName admin)13460 public boolean hasLockdownAdminConfiguredNetworks(@Nullable ComponentName admin) { 13461 throwIfParentInstance("hasLockdownAdminConfiguredNetworks"); 13462 if (mService != null) { 13463 try { 13464 return mService.hasLockdownAdminConfiguredNetworks(admin); 13465 } catch (RemoteException e) { 13466 throw e.rethrowFromSystemServer(); 13467 } 13468 } 13469 return false; 13470 } 13471 13472 /** 13473 * Called by a device owner or a profile owner of an organization-owned managed 13474 * profile to set the system wall clock time. This only takes effect if called when 13475 * {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false} 13476 * will be returned. 13477 * 13478 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13479 * caller is not a device admin. 13480 * @param millis time in milliseconds since the Epoch 13481 * @return {@code true} if set time succeeded, {@code false} otherwise. 13482 * @throws SecurityException if {@code admin} is not a device owner or a profile owner 13483 * of an organization-owned managed profile. 13484 */ 13485 @RequiresPermission(value = SET_TIME, conditional = true) setTime(@ullable ComponentName admin, long millis)13486 public boolean setTime(@Nullable ComponentName admin, long millis) { 13487 throwIfParentInstance("setTime"); 13488 if (mService != null) { 13489 try { 13490 return mService.setTime(admin, mContext.getPackageName(), millis); 13491 } catch (RemoteException e) { 13492 throw e.rethrowFromSystemServer(); 13493 } 13494 } 13495 return false; 13496 } 13497 13498 /** 13499 * Called by a device owner or a profile owner of an organization-owned managed 13500 * profile to set the system's persistent default time zone. This only takes 13501 * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE} 13502 * is 0, otherwise {@code false} will be returned. 13503 * 13504 * @see android.app.AlarmManager#setTimeZone(String) 13505 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13506 * caller is not a device admin. 13507 * @param timeZone one of the Olson ids from the list returned by 13508 * {@link java.util.TimeZone#getAvailableIDs} 13509 * @return {@code true} if set timezone succeeded, {@code false} otherwise. 13510 * @throws SecurityException if {@code admin} is not a device owner or a profile owner 13511 * of an organization-owned managed profile. 13512 */ 13513 @RequiresPermission(value = SET_TIME_ZONE, conditional = true) setTimeZone(@ullable ComponentName admin, String timeZone)13514 public boolean setTimeZone(@Nullable ComponentName admin, String timeZone) { 13515 throwIfParentInstance("setTimeZone"); 13516 if (mService != null) { 13517 try { 13518 return mService.setTimeZone(admin, mContext.getPackageName(), timeZone); 13519 } catch (RemoteException e) { 13520 throw e.rethrowFromSystemServer(); 13521 } 13522 } 13523 return false; 13524 } 13525 13526 /** 13527 * Called by device owners to set the user's global location setting. 13528 * 13529 * 13530 * @param admin Which {@link DeviceAdminReceiver} this request is associated with 13531 * @param locationEnabled whether location should be enabled or disabled. <b>Note: </b> on 13532 * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, calls to 13533 * disable will be ignored. 13534 * @throws SecurityException if {@code admin} is not a device owner. 13535 */ setLocationEnabled(@onNull ComponentName admin, boolean locationEnabled)13536 public void setLocationEnabled(@NonNull ComponentName admin, boolean locationEnabled) { 13537 throwIfParentInstance("setLocationEnabled"); 13538 if (mService != null) { 13539 try { 13540 mService.setLocationEnabled(admin, locationEnabled); 13541 } catch (RemoteException e) { 13542 throw e.rethrowFromSystemServer(); 13543 } 13544 } 13545 } 13546 13547 /** 13548 * This method is mostly deprecated. 13549 * Most of the settings that still have an effect have dedicated setter methods 13550 * (e.g. {@link #setLocationEnabled}) or user restrictions. 13551 * <p> 13552 * 13553 * Called by profile or device owners to update {@link android.provider.Settings.Secure} 13554 * settings. Validation that the value of the setting is in the correct form for the setting 13555 * type should be performed by the caller. 13556 * <p> 13557 * The settings that can be updated by a profile or device owner with this method are: 13558 * <ul> 13559 * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li> 13560 * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li> 13561 * </ul> 13562 * <p> 13563 * A device owner can additionally update the following settings: 13564 * <ul> 13565 * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li> 13566 * </ul> 13567 * 13568 * <strong>Note: Starting from Android O, apps should no longer call this method with the 13569 * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is 13570 * deprecated. Instead, device owners or profile owners should use the restriction 13571 * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}. 13572 * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method 13573 * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, 13574 * an {@link UnsupportedOperationException} is thrown. 13575 * 13576 * Starting from Android Q, the device and profile owner can also call 13577 * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for 13578 * all users. 13579 * </strong> 13580 * 13581 * <strong>Note: Starting from Android R, apps should no longer call this method with the 13582 * setting {@link android.provider.Settings.Secure#LOCATION_MODE}, which is deprecated. Instead, 13583 * device owners should call {@link #setLocationEnabled(ComponentName, boolean)}. This will be 13584 * enforced for all apps targeting Android R or above. 13585 * </strong> 13586 * 13587 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 13588 * @param setting The name of the setting to update. 13589 * @param value The value to update the setting to. 13590 * @throws SecurityException if {@code admin} is not a device or profile owner. 13591 */ setSecureSetting(@onNull ComponentName admin, String setting, String value)13592 public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) { 13593 throwIfParentInstance("setSecureSetting"); 13594 13595 if (mService != null) { 13596 try { 13597 mService.setSecureSetting(admin, setting, value); 13598 } catch (RemoteException e) { 13599 throw e.rethrowFromSystemServer(); 13600 } 13601 } 13602 } 13603 13604 /** 13605 * Designates a specific service component as the provider for making permission requests of a 13606 * local or remote administrator of the user. 13607 * <p/> 13608 * Only a device owner or profile owner can designate the restrictions provider. 13609 * 13610 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 13611 * @param provider The component name of the service that implements 13612 * {@link RestrictionsReceiver}. If this param is null, it removes the restrictions 13613 * provider previously assigned. 13614 * @throws SecurityException if {@code admin} is not a device or profile owner. 13615 */ setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)13616 public void setRestrictionsProvider(@NonNull ComponentName admin, 13617 @Nullable ComponentName provider) { 13618 throwIfParentInstance("setRestrictionsProvider"); 13619 if (mService != null) { 13620 try { 13621 mService.setRestrictionsProvider(admin, provider); 13622 } catch (RemoteException re) { 13623 throw re.rethrowFromSystemServer(); 13624 } 13625 } 13626 } 13627 13628 /** 13629 * Called by profile or device owners to set the global volume mute on or off. 13630 * This has no effect when set on a managed profile. 13631 * 13632 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 13633 * @param on {@code true} to mute global volume, {@code false} to turn mute off. 13634 * @throws SecurityException if {@code admin} is not a device or profile owner. 13635 */ setMasterVolumeMuted(@onNull ComponentName admin, boolean on)13636 public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) { 13637 throwIfParentInstance("setMasterVolumeMuted"); 13638 if (mService != null) { 13639 try { 13640 mService.setMasterVolumeMuted(admin, on); 13641 } catch (RemoteException re) { 13642 throw re.rethrowFromSystemServer(); 13643 } 13644 } 13645 } 13646 13647 /** 13648 * Called by profile or device owners to check whether the global volume mute is on or off. 13649 * 13650 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 13651 * @return {@code true} if global volume is muted, {@code false} if it's not. 13652 * @throws SecurityException if {@code admin} is not a device or profile owner. 13653 */ isMasterVolumeMuted(@onNull ComponentName admin)13654 public boolean isMasterVolumeMuted(@NonNull ComponentName admin) { 13655 throwIfParentInstance("isMasterVolumeMuted"); 13656 if (mService != null) { 13657 try { 13658 return mService.isMasterVolumeMuted(admin); 13659 } catch (RemoteException re) { 13660 throw re.rethrowFromSystemServer(); 13661 } 13662 } 13663 return false; 13664 } 13665 13666 /** 13667 * Change whether a user can uninstall a package. This function can be called by a device owner, 13668 * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via 13669 * {@link #setDelegatedScopes} or holders of the permission 13670 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}. 13671 * <p> 13672 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the set uninstall blocked 13673 * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 13674 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 13675 * successfully set or not. This callback will contain: 13676 * <ul> 13677 * <li> The policy identifier 13678 * {@link DevicePolicyIdentifiers#PACKAGE_UNINSTALL_BLOCKED_POLICY} 13679 * <li> The additional policy params bundle, which contains 13680 * {@link PolicyUpdateReceiver#EXTRA_PACKAGE_NAME} the package name the policy applies to 13681 * <li> The {@link TargetUser} that this policy relates to 13682 * <li> The {@link PolicyUpdateResult}, which will be 13683 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 13684 * reason the policy failed to be set 13685 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 13686 * </ul> 13687 * If there has been a change to the policy, 13688 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 13689 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 13690 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 13691 * will contain the reason why the policy changed. 13692 * 13693 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13694 * caller is not a device admin. 13695 * @param packageName package to change. 13696 * @param uninstallBlocked true if the user shouldn't be able to uninstall the package. 13697 * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the 13698 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}. 13699 * @see #setDelegatedScopes 13700 * @see #DELEGATION_BLOCK_UNINSTALL 13701 */ 13702 @RequiresPermission(value = MANAGE_DEVICE_POLICY_APPS_CONTROL, conditional = true) 13703 @SupportsCoexistence setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)13704 public void setUninstallBlocked(@Nullable ComponentName admin, String packageName, 13705 boolean uninstallBlocked) { 13706 throwIfParentInstance("setUninstallBlocked"); 13707 if (mService != null) { 13708 try { 13709 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName, 13710 uninstallBlocked); 13711 } catch (RemoteException re) { 13712 throw re.rethrowFromSystemServer(); 13713 } 13714 } 13715 } 13716 13717 /** 13718 * Check whether the user has been blocked by device policy from uninstalling a package. 13719 * Requires the caller to be the profile owner if checking a specific admin's policy. 13720 * <p> 13721 * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the 13722 * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter 13723 * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null} 13724 * will cause a NullPointerException to be raised. 13725 * <p> 13726 * <strong>Note:</strong> If your app targets Android 11 (API level 30) or higher, 13727 * this method returns a filtered result. Learn more about how to 13728 * <a href="/training/basics/intents/package-visibility">manage package visibility</a>. 13729 * <p> 13730 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the 13731 * current resolved policy rather than the policy set by the calling admin. 13732 * 13733 * @param admin The name of the admin component whose blocking policy will be checked, or 13734 * {@code null} to check whether any admin has blocked the uninstallation. Starting 13735 * from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} admin will be 13736 * ignored and assumed {@code null}. 13737 * @param packageName package to check. 13738 * @return true if uninstallation is blocked and the given package is visible to you, false 13739 * otherwise if uninstallation isn't blocked or the given package isn't visible to you. 13740 * @throws SecurityException if {@code admin} is not a device or profile owner. 13741 */ isUninstallBlocked(@ullable ComponentName admin, String packageName)13742 public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) { 13743 throwIfParentInstance("isUninstallBlocked"); 13744 if (mService != null) { 13745 try { 13746 return mService.isUninstallBlocked(packageName); 13747 } catch (RemoteException re) { 13748 throw re.rethrowFromSystemServer(); 13749 } 13750 } 13751 return false; 13752 } 13753 13754 /** 13755 * Called by the profile owner of a managed profile or a holder of the permission 13756 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION} to enable 13757 * widget providers from a given package to be available in the parent profile. As a result the 13758 * user will be able to add widgets from the allowlisted package running under the profile to a 13759 * widget host which runs under the parent profile, for example the home screen. Note that a 13760 * package may have zero or more provider components, where each component provides a different 13761 * widget type. 13762 * <p> 13763 * <strong>Note:</strong> By default no widget provider package is allowlisted. 13764 * 13765 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13766 * caller is not a device admin. 13767 * @param packageName The package from which widget providers are allowlisted. 13768 * @return Whether the package was added. 13769 * @throws SecurityException if {@code admin} is not a profile owner and not a holder of the 13770 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION}. 13771 * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String) 13772 * @see #getCrossProfileWidgetProviders(android.content.ComponentName) 13773 */ 13774 @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true) addCrossProfileWidgetProvider(@ullable ComponentName admin, String packageName)13775 public boolean addCrossProfileWidgetProvider(@Nullable ComponentName admin, 13776 String packageName) { 13777 throwIfParentInstance("addCrossProfileWidgetProvider"); 13778 if (mService != null) { 13779 try { 13780 return mService.addCrossProfileWidgetProvider(admin, 13781 mContext.getPackageName(), packageName); 13782 } catch (RemoteException re) { 13783 throw re.rethrowFromSystemServer(); 13784 } 13785 } 13786 return false; 13787 } 13788 13789 /** 13790 * Called by the profile owner of a managed profile or a holder of the permission 13791 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION} to disable 13792 * widget providers from a given package to be available in the parent profile. For this method 13793 * to take effect the package should have been added via 13794 * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}. 13795 * <p> 13796 * <strong>Note:</strong> By default no widget provider package is allowlisted. 13797 * 13798 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13799 * caller is not a device admin. 13800 * @param packageName The package from which widget providers are no longer allowlisted. 13801 * @return Whether the package was removed. 13802 * @throws SecurityException if {@code admin} is not a profile owner and not a holder of the 13803 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION}. 13804 * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String) 13805 * @see #getCrossProfileWidgetProviders(android.content.ComponentName) 13806 */ 13807 @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true) removeCrossProfileWidgetProvider(@ullable ComponentName admin, String packageName)13808 public boolean removeCrossProfileWidgetProvider(@Nullable ComponentName admin, 13809 String packageName) { 13810 throwIfParentInstance("removeCrossProfileWidgetProvider"); 13811 if (mService != null) { 13812 try { 13813 return mService.removeCrossProfileWidgetProvider(admin, mContext.getPackageName(), 13814 packageName); 13815 } catch (RemoteException re) { 13816 throw re.rethrowFromSystemServer(); 13817 } 13818 } 13819 return false; 13820 } 13821 13822 /** 13823 * Called by the profile owner of a managed profile or a holder of the permission 13824 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION} to query 13825 * providers from which packages are available in the parent profile. 13826 * 13827 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13828 * caller is not a device admin. 13829 * @return The allowlisted package list. 13830 * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String) 13831 * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String) 13832 * @throws SecurityException if {@code admin} is not a profile owner and not a holder of the 13833 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION}. 13834 */ 13835 @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true) getCrossProfileWidgetProviders(@ullable ComponentName admin)13836 public @NonNull List<String> getCrossProfileWidgetProviders(@Nullable ComponentName admin) { 13837 throwIfParentInstance("getCrossProfileWidgetProviders"); 13838 if (mService != null) { 13839 try { 13840 List<String> providers = mService.getCrossProfileWidgetProviders(admin, 13841 mContext.getPackageName()); 13842 if (providers != null) { 13843 return providers; 13844 } 13845 } catch (RemoteException re) { 13846 throw re.rethrowFromSystemServer(); 13847 } 13848 } 13849 return Collections.emptyList(); 13850 } 13851 13852 /** 13853 * Called by profile or device owners to set the user's photo. 13854 * 13855 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 13856 * @param icon the bitmap to set as the photo. 13857 * @throws SecurityException if {@code admin} is not a device or profile owner. 13858 */ setUserIcon(@onNull ComponentName admin, Bitmap icon)13859 public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) { 13860 throwIfParentInstance("setUserIcon"); 13861 try { 13862 mService.setUserIcon(admin, icon); 13863 } catch (RemoteException re) { 13864 throw re.rethrowFromSystemServer(); 13865 } 13866 } 13867 13868 /** 13869 * Called by device owners or profile owners of an organization-owned managed profile to set 13870 * a local system update policy. When a new policy is set, 13871 * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcast. 13872 * <p> 13873 * If the supplied system update policy has freeze periods set but the freeze periods do not 13874 * meet 90-day maximum length or 60-day minimum separation requirement set out in 13875 * {@link SystemUpdatePolicy#setFreezePeriods}, 13876 * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system 13877 * keeps a record of freeze periods the device experienced previously, and combines them with 13878 * the new freeze periods to be set when checking the maximum freeze length and minimum freeze 13879 * separation constraints. As a result, freeze periods that passed validation during 13880 * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to 13881 * the freeze period history. If this is causing issues during development, 13882 * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record. 13883 * 13884 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All 13885 * components in the package can set system update policies and the most 13886 * recent policy takes effect. This should be null if the caller is not a device 13887 * admin. 13888 * @param policy the new policy, or {@code null} to clear the current policy. 13889 * @throws SecurityException if {@code admin} is not a device owner or a profile owner of an 13890 * organization-owned managed profile, or the caller is not permitted to set this policy 13891 * @throws IllegalArgumentException if the policy type or maintenance window is not valid. 13892 * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not 13893 * meet the requirement. 13894 * @see SystemUpdatePolicy 13895 * @see SystemUpdatePolicy#setFreezePeriods(List) 13896 */ 13897 @RequiresPermission(value = MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, conditional = true) setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)13898 public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) { 13899 throwIfParentInstance("setSystemUpdatePolicy"); 13900 if (mService != null) { 13901 try { 13902 mService.setSystemUpdatePolicy(admin, mContext.getPackageName(), policy); 13903 } catch (RemoteException re) { 13904 throw re.rethrowFromSystemServer(); 13905 } 13906 } 13907 } 13908 13909 /** 13910 * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}. 13911 * 13912 * @return The current policy object, or {@code null} if no policy is set. 13913 */ getSystemUpdatePolicy()13914 public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() { 13915 throwIfParentInstance("getSystemUpdatePolicy"); 13916 if (mService != null) { 13917 try { 13918 return mService.getSystemUpdatePolicy(); 13919 } catch (RemoteException re) { 13920 throw re.rethrowFromSystemServer(); 13921 } 13922 } 13923 return null; 13924 } 13925 13926 /** 13927 * Reset record of previous system update freeze period the device went through. 13928 * @hide 13929 */ 13930 @TestApi 13931 @RequiresPermission(android.Manifest.permission.CLEAR_FREEZE_PERIOD) clearSystemUpdatePolicyFreezePeriodRecord()13932 public void clearSystemUpdatePolicyFreezePeriodRecord() { 13933 throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord"); 13934 if (mService == null) { 13935 return; 13936 } 13937 try { 13938 mService.clearSystemUpdatePolicyFreezePeriodRecord(); 13939 } catch (RemoteException re) { 13940 throw re.rethrowFromSystemServer(); 13941 } 13942 } 13943 13944 /** 13945 * Called by a device owner or profile owner of secondary users that is affiliated with the 13946 * device to disable the keyguard altogether. 13947 * <p> 13948 * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock 13949 * type. However, this call has no effect if a password, pin or pattern is currently set. If a 13950 * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being 13951 * disabled. 13952 * 13953 * <p> 13954 * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the 13955 * keyguard if it is currently shown. 13956 * 13957 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 13958 * @param disabled {@code true} disables the keyguard, {@code false} reenables it. 13959 * @return {@code false} if attempting to disable the keyguard while a lock password was in 13960 * place. {@code true} otherwise. 13961 * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of 13962 * secondary user that is affiliated with the device. 13963 * @see #isAffiliatedUser 13964 * @see #getSecondaryUsers 13965 */ setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)13966 public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) { 13967 throwIfParentInstance("setKeyguardDisabled"); 13968 try { 13969 return mService.setKeyguardDisabled(admin, disabled); 13970 } catch (RemoteException re) { 13971 throw re.rethrowFromSystemServer(); 13972 } 13973 } 13974 13975 /** 13976 * Called by device owner or profile owner of secondary users that is affiliated with the 13977 * device to disable the status bar. Disabling the status bar blocks notifications and quick 13978 * settings. 13979 * <p> 13980 * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the 13981 * status bar in LockTask mode can be configured with 13982 * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in 13983 * LockTask mode will be registered, but will only take effect when the device leaves LockTask 13984 * mode. 13985 * 13986 * <p>This policy does not have any effect while on the lock screen, where the status bar will 13987 * not be disabled. Using LockTask instead of this method is recommended. 13988 * 13989 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 13990 * caller is not a device admin. 13991 * @param disabled {@code true} disables the status bar, {@code false} reenables it. 13992 * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise. 13993 * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of 13994 * secondary user that is affiliated with the device. 13995 * @see #isAffiliatedUser 13996 * @see #getSecondaryUsers 13997 */ 13998 @RequiresPermission(value = MANAGE_DEVICE_POLICY_STATUS_BAR, conditional = true) setStatusBarDisabled(@ullable ComponentName admin, boolean disabled)13999 public boolean setStatusBarDisabled(@Nullable ComponentName admin, boolean disabled) { 14000 throwIfParentInstance("setStatusBarDisabled"); 14001 try { 14002 return mService.setStatusBarDisabled(admin, mContext.getPackageName(), disabled); 14003 } catch (RemoteException re) { 14004 throw re.rethrowFromSystemServer(); 14005 } 14006 } 14007 14008 /** 14009 * Returns whether the status bar is disabled/enabled, see {@link #setStatusBarDisabled}. 14010 * 14011 * <p>Callable by device owner or profile owner of secondary users that is affiliated with the 14012 * device owner. 14013 * 14014 * <p>This policy has no effect in LockTask mode. The behavior of the 14015 * status bar in LockTask mode can be configured with 14016 * {@link #setLockTaskFeatures(ComponentName, int)}. 14017 * 14018 * <p>This policy also does not have any effect while on the lock screen, where the status bar 14019 * will not be disabled. 14020 * 14021 * @throws SecurityException if the caller is not the device owner, or a profile owner of 14022 * secondary user that is affiliated with the device. 14023 * @see #isAffiliatedUser 14024 * @see #getSecondaryUsers 14025 */ isStatusBarDisabled()14026 public boolean isStatusBarDisabled() { 14027 throwIfParentInstance("isStatusBarDisabled"); 14028 try { 14029 return mService.isStatusBarDisabled(mContext.getPackageName()); 14030 } catch (RemoteException re) { 14031 throw re.rethrowFromSystemServer(); 14032 } 14033 } 14034 14035 /** 14036 * Called by the system update service to notify device and profile owners of pending system 14037 * updates. 14038 * 14039 * This method should only be used when it is unknown whether the pending system 14040 * update is a security patch. Otherwise, use 14041 * {@link #notifyPendingSystemUpdate(long, boolean)}. 14042 * 14043 * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()} 14044 * indicating when the current pending update was first available. {@code -1} if no 14045 * update is available. 14046 * @see #notifyPendingSystemUpdate(long, boolean) 14047 * @hide 14048 */ 14049 @SystemApi 14050 @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE) notifyPendingSystemUpdate(long updateReceivedTime)14051 public void notifyPendingSystemUpdate(long updateReceivedTime) { 14052 throwIfParentInstance("notifyPendingSystemUpdate"); 14053 if (mService != null) { 14054 try { 14055 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime)); 14056 } catch (RemoteException re) { 14057 throw re.rethrowFromSystemServer(); 14058 } 14059 } 14060 } 14061 14062 /** 14063 * Called by the system update service to notify device and profile owners of pending system 14064 * updates. 14065 * 14066 * This method should be used instead of {@link #notifyPendingSystemUpdate(long)} 14067 * when it is known whether the pending system update is a security patch. 14068 * 14069 * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()} 14070 * indicating when the current pending update was first available. {@code -1} if no 14071 * update is available. 14072 * @param isSecurityPatch {@code true} if this system update is purely a security patch; 14073 * {@code false} if not. 14074 * @see #notifyPendingSystemUpdate(long) 14075 * @hide 14076 */ 14077 @SystemApi 14078 @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE) notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)14079 public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) { 14080 throwIfParentInstance("notifyPendingSystemUpdate"); 14081 if (mService != null) { 14082 try { 14083 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime, 14084 isSecurityPatch)); 14085 } catch (RemoteException re) { 14086 throw re.rethrowFromSystemServer(); 14087 } 14088 } 14089 } 14090 14091 /** 14092 * Get information about a pending system update. 14093 * 14094 * Can be called by device or profile owners, and starting from Android 14095 * {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, holders of the permission 14096 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES}. 14097 * 14098 * @param admin Which profile or device owner this request is associated with. 14099 * @return Information about a pending system update or {@code null} if no update pending. 14100 * @throws SecurityException if {@code admin} is not a device, profile owner or holders of 14101 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES}. 14102 * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long) 14103 */ 14104 @RequiresPermission(value = MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES, conditional = true) 14105 @SuppressLint("RequiresPermission") getPendingSystemUpdate(@ullable ComponentName admin)14106 public @Nullable SystemUpdateInfo getPendingSystemUpdate(@Nullable ComponentName admin) { 14107 throwIfParentInstance("getPendingSystemUpdate"); 14108 try { 14109 return mService.getPendingSystemUpdate(admin, mContext.getPackageName()); 14110 } catch (RemoteException re) { 14111 throw re.rethrowFromSystemServer(); 14112 } 14113 } 14114 14115 /** 14116 * Set the default response for future runtime permission requests by applications. This 14117 * function can be called by a device owner, profile owner, or by a delegate given the 14118 * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}. 14119 * The policy can allow for normal operation which prompts the user to grant a permission, or 14120 * can allow automatic granting or denying of runtime permission requests by an application. 14121 * This also applies to new permissions declared by app updates. When a permission is denied or 14122 * granted this way, the effect is equivalent to setting the permission * grant state via 14123 * {@link #setPermissionGrantState}. 14124 * <p/> 14125 * As this policy only acts on runtime permission requests, it only applies to applications 14126 * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later. 14127 * 14128 * <p> 14129 * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, an auto-grant 14130 * policy will not apply to certain sensors-related permissions on some configurations. 14131 * See {@link #setPermissionGrantState(ComponentName, String, String, int)} for the list of 14132 * permissions affected, and the behavior change for managed profiles and fully-managed 14133 * devices. 14134 * 14135 * @param admin Which profile or device owner this request is associated with. 14136 * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT}, 14137 * {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}. 14138 * @throws SecurityException if {@code admin} is not a device or profile owner. 14139 * @see #setPermissionGrantState 14140 * @see #setDelegatedScopes 14141 * @see #DELEGATION_PERMISSION_GRANT 14142 */ setPermissionPolicy(@onNull ComponentName admin, int policy)14143 public void setPermissionPolicy(@NonNull ComponentName admin, int policy) { 14144 throwIfParentInstance("setPermissionPolicy"); 14145 try { 14146 mService.setPermissionPolicy(admin, mContext.getPackageName(), policy); 14147 } catch (RemoteException re) { 14148 throw re.rethrowFromSystemServer(); 14149 } 14150 } 14151 14152 /** 14153 * Returns the current runtime permission policy set by the device or profile owner. The 14154 * default is {@link #PERMISSION_POLICY_PROMPT}. 14155 * 14156 * @param admin Which profile or device owner this request is associated with. 14157 * @return the current policy for future permission requests. 14158 */ getPermissionPolicy(ComponentName admin)14159 public int getPermissionPolicy(ComponentName admin) { 14160 throwIfParentInstance("getPermissionPolicy"); 14161 try { 14162 return mService.getPermissionPolicy(admin); 14163 } catch (RemoteException re) { 14164 throw re.rethrowFromSystemServer(); 14165 } 14166 } 14167 14168 /** 14169 * Sets the grant state of a runtime permission for a specific application. The state can be 14170 * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI, 14171 * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user 14172 * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which 14173 * the permission is granted and the user cannot manage it through the UI. This method can only 14174 * be called by a profile owner, device owner, or a delegate given the 14175 * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}. 14176 * <p/> 14177 * Note that user cannot manage other permissions in the affected group through the UI 14178 * either and their granted state will be kept as the current value. Thus, it's recommended that 14179 * you set the grant state of all the permissions in the affected group. 14180 * <p/> 14181 * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke 14182 * the permission. It retains the previous grant, if any. 14183 * <p/> 14184 * Device admins with a {@code targetSdkVersion} < {@link android.os.Build.VERSION_CODES#Q} 14185 * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion} 14186 * < {@link android.os.Build.VERSION_CODES#M}. 14187 * <p/> 14188 * Admins with a {@code targetSdkVersion} ≥ {@link android.os.Build.VERSION_CODES#Q} can 14189 * grant and revoke permissions of all apps. Similar to the user revoking a permission from a 14190 * application built with a {@code targetSdkVersion} < 14191 * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to 14192 * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted. 14193 * <p> 14194 * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over 14195 * the following, sensors-related, permissions is restricted: 14196 * <ul> 14197 * <li>Manifest.permission.ACCESS_FINE_LOCATION</li> 14198 * <li>Manifest.permission.ACCESS_BACKGROUND_LOCATION</li> 14199 * <li>Manifest.permission.ACCESS_COARSE_LOCATION</li> 14200 * <li>Manifest.permission.CAMERA</li> 14201 * <li>Manifest.permission.RECORD_AUDIO</li> 14202 * <li>Manifest.permission.RECORD_BACKGROUND_AUDIO</li> 14203 * <li>Manifest.permission.ACTIVITY_RECOGNITION</li> 14204 * <li>Manifest.permission.BODY_SENSORS</li> 14205 * </ul> 14206 * On devices running {@link android.os.Build.VERSION_CODES#BAKLAVA}, the 14207 * {@link android.health.connect.HealthPermissions} are also included in the 14208 * restricted list. 14209 * <p> 14210 * A profile owner may not grant these permissions (i.e. call this method with any of the 14211 * permissions listed above and {@code grantState} of {@code #PERMISSION_GRANT_STATE_GRANTED}), 14212 * but may deny them. 14213 * <p> 14214 * A device owner, by default, may continue granting these permissions. However, for increased 14215 * user control, the admin may opt out of controlling grants for these permissions by including 14216 * {@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} in the provisioning parameters. 14217 * In that case the device owner's control will be limited to denying these permissions. 14218 * <p> 14219 * When sensor-related permissions aren't grantable due to the above cases, calling this method 14220 * to grant these permissions will silently fail, if device admins are built with 14221 * {@code targetSdkVersion} < {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}. If 14222 * they are built with {@code targetSdkVersion} >= 14223 * {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, this method will throw a 14224 * {@link SecurityException}. 14225 * <p> 14226 * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over 14227 * the following permissions are restricted for managed profile owners: 14228 * <ul> 14229 * <li>Manifest.permission.READ_SMS</li> 14230 * </ul> 14231 * <p> 14232 * A managed profile owner may not grant these permissions (i.e. call this method with any of 14233 * the permissions listed above and {@code grantState} of 14234 * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them. 14235 * <p> 14236 * Attempts by the admin to grant these permissions, when the admin is restricted from doing 14237 * so, will be silently ignored (no exception will be thrown). 14238 * 14239 * Control over the following permissions are restricted for managed profile owners: 14240 * <ul> 14241 * <li>Manifest.permission.READ_SMS</li> 14242 * </ul> 14243 * <p> 14244 * A managed profile owner may not grant these permissions (i.e. call this method with any of 14245 * the permissions listed above and {@code grantState} of 14246 * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them. 14247 * 14248 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 14249 * caller is not a device admin. 14250 * @param packageName The application to grant or revoke a permission to. 14251 * @param permission The permission to grant or revoke. 14252 * @param grantState The permission grant state which is one of 14253 * {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT}, 14254 * {@link #PERMISSION_GRANT_STATE_GRANTED}, 14255 * @return whether the permission was successfully granted or revoked. 14256 * @throws SecurityException if {@code admin} is not a device or profile owner. 14257 * @see #PERMISSION_GRANT_STATE_DENIED 14258 * @see #PERMISSION_GRANT_STATE_DEFAULT 14259 * @see #PERMISSION_GRANT_STATE_GRANTED 14260 * @see #setDelegatedScopes 14261 * @see #DELEGATION_PERMISSION_GRANT 14262 */ 14263 @RequiresPermission(value = MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, conditional = true) 14264 @SupportsCoexistence setPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)14265 public boolean setPermissionGrantState(@Nullable ComponentName admin, 14266 @NonNull String packageName, @NonNull String permission, 14267 @PermissionGrantState int grantState) { 14268 throwIfParentInstance("setPermissionGrantState"); 14269 try { 14270 CompletableFuture<Boolean> result = new CompletableFuture<>(); 14271 14272 mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName, 14273 permission, grantState, new RemoteCallback((b) -> result.complete(b != null))); 14274 14275 // Timeout 14276 BackgroundThread.getHandler().sendMessageDelayed( 14277 obtainMessage(CompletableFuture::complete, result, false), 14278 20_000); 14279 14280 return result.get(); 14281 } catch (RemoteException re) { 14282 throw re.rethrowFromSystemServer(); 14283 } catch (InterruptedException | ExecutionException e) { 14284 throw new RuntimeException(e); 14285 } 14286 } 14287 14288 /** 14289 * Returns the current grant state of a runtime permission for a specific application. This 14290 * function can be called by a device owner, profile owner, or by a delegate given the 14291 * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}. 14292 * 14293 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 14294 * caller is not a device admin. 14295 * @param packageName The application to check the grant state for. 14296 * @param permission The permission to check for. 14297 * @return the current grant state specified by device policy. If admins have not set a grant 14298 * has not set a grant state, the return value is 14299 * {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the 14300 * permission is currently granted for the package. 14301 * <p/> 14302 * If a grant state was set by the profile or device owner, then the return value will 14303 * be one of {@link #PERMISSION_GRANT_STATE_DENIED} or 14304 * {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is 14305 * currently denied or granted. 14306 * @throws SecurityException if {@code admin} is not a device or profile owner. 14307 * @see #setPermissionGrantState(ComponentName, String, String, int) 14308 * @see PackageManager#checkPermission(String, String) 14309 * @see #setDelegatedScopes 14310 * @see #DELEGATION_PERMISSION_GRANT 14311 */ 14312 @RequiresPermission(value = MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, conditional = true) getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)14313 public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin, 14314 @NonNull String packageName, @NonNull String permission) { 14315 throwIfParentInstance("getPermissionGrantState"); 14316 try { 14317 return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName, 14318 permission); 14319 } catch (RemoteException re) { 14320 throw re.rethrowFromSystemServer(); 14321 } 14322 } 14323 14324 /** 14325 * Returns whether it is possible for the caller to initiate provisioning of a managed profile 14326 * or device, setting itself as the device or profile owner. 14327 * 14328 * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE}, 14329 * {@link #ACTION_PROVISION_MANAGED_PROFILE}. 14330 * @return whether provisioning a managed profile or device is possible. 14331 * @throws IllegalArgumentException if the supplied action is not valid. 14332 */ isProvisioningAllowed(@onNull String action)14333 public boolean isProvisioningAllowed(@NonNull String action) { 14334 throwIfParentInstance("isProvisioningAllowed"); 14335 try { 14336 return mService.isProvisioningAllowed(action, mContext.getPackageName()); 14337 } catch (RemoteException re) { 14338 throw re.rethrowFromSystemServer(); 14339 } 14340 } 14341 14342 /** 14343 * Checks whether it is possible to initiate provisioning a managed device, 14344 * profile or user, setting the given package as owner. 14345 * 14346 * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE}, 14347 * {@link #ACTION_PROVISION_MANAGED_PROFILE} 14348 * @param packageName The package of the component that would be set as device, user, or profile 14349 * owner. 14350 * @return An int constant value indicating whether provisioning is allowed. 14351 * @hide 14352 */ 14353 @SystemApi 14354 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) 14355 @ProvisioningPrecondition checkProvisioningPrecondition( @onNull String action, @NonNull String packageName)14356 public int checkProvisioningPrecondition( 14357 @NonNull String action, @NonNull String packageName) { 14358 try { 14359 return mService.checkProvisioningPrecondition(action, packageName); 14360 } catch (RemoteException re) { 14361 throw re.rethrowFromSystemServer(); 14362 } 14363 } 14364 14365 /** 14366 * Return if this user is a managed profile of another user. An admin can become the profile 14367 * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed 14368 * user with {@link #createAndManageUser} 14369 * @param admin Which profile owner this request is associated with. 14370 * @return if this user is a managed profile of another user. 14371 */ isManagedProfile(@onNull ComponentName admin)14372 public boolean isManagedProfile(@NonNull ComponentName admin) { 14373 throwIfParentInstance("isManagedProfile"); 14374 try { 14375 return mService.isManagedProfile(admin); 14376 } catch (RemoteException re) { 14377 throw re.rethrowFromSystemServer(); 14378 } 14379 } 14380 14381 /** 14382 * Called by a device owner or profile owner on organization-owned device to get the MAC 14383 * address of the Wi-Fi device. 14384 * 14385 * NOTE: The MAC address returned here should only be used for inventory management and is 14386 * not likely to be the MAC address used by the device to connect to Wi-Fi networks: MAC 14387 * addresses used for scanning and connecting to Wi-Fi networks are randomized by default. 14388 * To get the randomized MAC address used, call 14389 * {@link android.net.wifi.WifiConfiguration#getRandomizedMacAddress}. 14390 * 14391 * @param admin Which admin this request is associated with. Null if the caller is not a device 14392 * admin 14393 * @return the MAC address of the Wi-Fi device, or null when the information is not available. 14394 * (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.) 14395 * <p> 14396 * The address will be in the {@code XX:XX:XX:XX:XX:XX} format. 14397 * @throws SecurityException if {@code admin} is not permitted to get wifi mac addresses 14398 */ 14399 // @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true) getWifiMacAddress(@ullable ComponentName admin)14400 public @Nullable String getWifiMacAddress(@Nullable ComponentName admin) { 14401 throwIfParentInstance("getWifiMacAddress"); 14402 try { 14403 return mService.getWifiMacAddress(admin, mContext.getPackageName()); 14404 } catch (RemoteException re) { 14405 throw re.rethrowFromSystemServer(); 14406 } 14407 } 14408 14409 /** 14410 * Called by device owner to reboot the device. If there is an ongoing call on the device, 14411 * throws an {@link IllegalStateException}. 14412 * @param admin Which device owner the request is associated with. 14413 * @throws IllegalStateException if device has an ongoing call. 14414 * @throws SecurityException if {@code admin} is not a device owner. 14415 * @see TelephonyManager#CALL_STATE_IDLE 14416 */ reboot(@onNull ComponentName admin)14417 public void reboot(@NonNull ComponentName admin) { 14418 throwIfParentInstance("reboot"); 14419 try { 14420 mService.reboot(admin); 14421 } catch (RemoteException re) { 14422 throw re.rethrowFromSystemServer(); 14423 } 14424 } 14425 14426 /** 14427 * Called by a device admin to set the short support message. This will be displayed to the user 14428 * in settings screens where functionality has been disabled by the admin. The message should be 14429 * limited to a short statement such as "This setting is disabled by your administrator. Contact 14430 * someone@example.com for support." If the message is longer than 200 characters it may be 14431 * truncated. 14432 * <p> 14433 * If the short support message needs to be localized, it is the responsibility of the 14434 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast 14435 * and set a new version of this string accordingly. 14436 * 14437 * @see #setLongSupportMessage 14438 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 14439 * caller is not a device admin. 14440 * @param message Short message to be displayed to the user in settings or null to clear the 14441 * existing message. 14442 * @throws SecurityException if {@code admin} is not an active administrator. 14443 */ 14444 @RequiresPermission(value = MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE, conditional = true) setShortSupportMessage(@ullable ComponentName admin, @Nullable CharSequence message)14445 public void setShortSupportMessage(@Nullable ComponentName admin, 14446 @Nullable CharSequence message) { 14447 throwIfParentInstance("setShortSupportMessage"); 14448 if (mService != null) { 14449 try { 14450 mService.setShortSupportMessage(admin, mContext.getPackageName(), message); 14451 } catch (RemoteException e) { 14452 throw e.rethrowFromSystemServer(); 14453 } 14454 } 14455 } 14456 14457 /** 14458 * Called by a device admin or holder of the permission 14459 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE} to get the short 14460 * support message. 14461 * 14462 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 14463 * caller is not a device admin. 14464 * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or 14465 * null if no message has been set. 14466 * @throws SecurityException if {@code admin} is not an active administrator and not a holder of 14467 * the permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE}.. 14468 */ 14469 @RequiresPermission(value = MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE, conditional = true) getShortSupportMessage(@ullable ComponentName admin)14470 public CharSequence getShortSupportMessage(@Nullable ComponentName admin) { 14471 throwIfParentInstance("getShortSupportMessage"); 14472 if (mService != null) { 14473 try { 14474 return mService.getShortSupportMessage(admin, mContext.getPackageName()); 14475 } catch (RemoteException e) { 14476 throw e.rethrowFromSystemServer(); 14477 } 14478 } 14479 return null; 14480 } 14481 14482 /** 14483 * Called by a device admin to set the long support message. This will be displayed to the user 14484 * in the device administrators settings screen. If the message is longer than 20000 characters 14485 * it may be truncated. 14486 * <p> 14487 * If the long support message needs to be localized, it is the responsibility of the 14488 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast 14489 * and set a new version of this string accordingly. 14490 * 14491 * @see #setShortSupportMessage 14492 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 14493 * @param message Long message to be displayed to the user in settings or null to clear the 14494 * existing message. 14495 * @throws SecurityException if {@code admin} is not an active administrator. 14496 */ setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)14497 public void setLongSupportMessage(@NonNull ComponentName admin, 14498 @Nullable CharSequence message) { 14499 throwIfParentInstance("setLongSupportMessage"); 14500 if (mService != null) { 14501 try { 14502 mService.setLongSupportMessage(admin, message); 14503 } catch (RemoteException e) { 14504 throw e.rethrowFromSystemServer(); 14505 } 14506 } 14507 } 14508 14509 /** 14510 * Called by a device admin to get the long support message. 14511 * 14512 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 14513 * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or 14514 * null if no message has been set. 14515 * @throws SecurityException if {@code admin} is not an active administrator. 14516 */ getLongSupportMessage(@onNull ComponentName admin)14517 public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) { 14518 throwIfParentInstance("getLongSupportMessage"); 14519 if (mService != null) { 14520 try { 14521 return mService.getLongSupportMessage(admin); 14522 } catch (RemoteException e) { 14523 throw e.rethrowFromSystemServer(); 14524 } 14525 } 14526 return null; 14527 } 14528 14529 /** 14530 * Called by the system to get the short support message. 14531 * 14532 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 14533 * @param userHandle user id the admin is running as. 14534 * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} 14535 * 14536 * @hide 14537 */ getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)14538 public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin, 14539 int userHandle) { 14540 if (mService != null) { 14541 try { 14542 return mService.getShortSupportMessageForUser(admin, userHandle); 14543 } catch (RemoteException e) { 14544 throw e.rethrowFromSystemServer(); 14545 } 14546 } 14547 return null; 14548 } 14549 14550 14551 /** 14552 * Called by the system to get the long support message. 14553 * 14554 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 14555 * @param userHandle user id the admin is running as. 14556 * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} 14557 * 14558 * @hide 14559 */ getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)14560 public @Nullable CharSequence getLongSupportMessageForUser( 14561 @NonNull ComponentName admin, int userHandle) { 14562 if (mService != null) { 14563 try { 14564 return mService.getLongSupportMessageForUser(admin, userHandle); 14565 } catch (RemoteException e) { 14566 throw e.rethrowFromSystemServer(); 14567 } 14568 } 14569 return null; 14570 } 14571 14572 /** 14573 * Called by the profile owner of a managed profile or other apps in a managed profile to 14574 * obtain a {@link DevicePolicyManager} whose calls act on the parent profile. 14575 * 14576 * <p>The following methods are supported for the parent instance, all other methods will 14577 * throw a SecurityException when called on the parent instance: 14578 * <ul> 14579 * <li>{@link #getPasswordQuality}</li> 14580 * <li>{@link #setPasswordQuality}</li> 14581 * <li>{@link #getPasswordMinimumLength}</li> 14582 * <li>{@link #setPasswordMinimumLength}</li> 14583 * <li>{@link #getPasswordMinimumUpperCase}</li> 14584 * <li>{@link #setPasswordMinimumUpperCase}</li> 14585 * <li>{@link #getPasswordMinimumLowerCase}</li> 14586 * <li>{@link #setPasswordMinimumLowerCase}</li> 14587 * <li>{@link #getPasswordMinimumLetters}</li> 14588 * <li>{@link #setPasswordMinimumLetters}</li> 14589 * <li>{@link #getPasswordMinimumNumeric}</li> 14590 * <li>{@link #setPasswordMinimumNumeric}</li> 14591 * <li>{@link #getPasswordMinimumSymbols}</li> 14592 * <li>{@link #setPasswordMinimumSymbols}</li> 14593 * <li>{@link #getPasswordMinimumNonLetter}</li> 14594 * <li>{@link #setPasswordMinimumNonLetter}</li> 14595 * <li>{@link #getPasswordHistoryLength}</li> 14596 * <li>{@link #setPasswordHistoryLength}</li> 14597 * <li>{@link #getPasswordExpirationTimeout}</li> 14598 * <li>{@link #setPasswordExpirationTimeout}</li> 14599 * <li>{@link #getPasswordExpiration}</li> 14600 * <li>{@link #getPasswordMaximumLength}</li> 14601 * <li>{@link #isActivePasswordSufficient}</li> 14602 * <li>{@link #getCurrentFailedPasswordAttempts}</li> 14603 * <li>{@link #getMaximumFailedPasswordsForWipe}</li> 14604 * <li>{@link #setMaximumFailedPasswordsForWipe}</li> 14605 * <li>{@link #getMaximumTimeToLock}</li> 14606 * <li>{@link #setMaximumTimeToLock}</li> 14607 * <li>{@link #lockNow}</li> 14608 * <li>{@link #getKeyguardDisabledFeatures}</li> 14609 * <li>{@link #setKeyguardDisabledFeatures}</li> 14610 * <li>{@link #getTrustAgentConfiguration}</li> 14611 * <li>{@link #setTrustAgentConfiguration}</li> 14612 * <li>{@link #getRequiredStrongAuthTimeout}</li> 14613 * <li>{@link #setRequiredStrongAuthTimeout}</li> 14614 * <li>{@link #getAccountTypesWithManagementDisabled}</li> 14615 * <li>{@link #setRequiredPasswordComplexity(int)} </li> 14616 * <li>{@link #getRequiredPasswordComplexity()}</li> 14617 * </ul> 14618 * <p> 14619 * The following methods are supported for the parent instance but can only be called by the 14620 * profile owner on an <a href="#organization-owned">organization owned</a> managed profile: 14621 * <ul> 14622 * <li>{@link #getPasswordComplexity}</li> 14623 * <li>{@link #setCameraDisabled}</li> 14624 * <li>{@link #getCameraDisabled}</li> 14625 * <li>{@link #setAccountManagementDisabled(ComponentName, String, boolean)}</li> 14626 * <li>{@link #setPermittedInputMethods}</li> 14627 * <li>{@link #getPermittedInputMethods}</li> 14628 * <li>{@link #wipeData}</li> 14629 * </ul> 14630 * 14631 * @param admin Which {@link DeviceAdminReceiver} this request is associated with or 14632 * {@code null} if the caller is not a profile owner. 14633 * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile. 14634 * @throws SecurityException if the current user is not a managed profile. 14635 */ getParentProfileInstance(@ullable ComponentName admin)14636 public @NonNull DevicePolicyManager getParentProfileInstance(@Nullable ComponentName admin) { 14637 throwIfParentInstance("getParentProfileInstance"); 14638 UserManager um = mContext.getSystemService(UserManager.class); 14639 if (!um.isManagedProfile()) { 14640 throw new SecurityException("The current user does not have a parent profile."); 14641 } 14642 return new DevicePolicyManager(mContext, mService, true); 14643 } 14644 14645 /** 14646 * Called by device owner or a profile owner of an organization-owned managed profile to 14647 * control the security logging feature. 14648 * 14649 * <p> Security logs contain various information intended for security auditing purposes. 14650 * When security logging is enabled by any app other than the device owner, certain security 14651 * logs are not visible (for example personal app launch events) or they will be redacted 14652 * (for example, details of the physical volume mount events). 14653 * Please see {@link SecurityEvent} for details. 14654 * 14655 * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there 14656 * are unaffiliated secondary users or profiles on the device, regardless of whether the 14657 * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for 14658 * all users to become affiliated. Therefore it's recommended that affiliation ids are set for 14659 * new users as soon as possible after provisioning via {@link #setAffiliationIds}. Non device 14660 * owners are not subject to this restriction since all 14661 * privacy-sensitive events happening outside the managed profile would have been redacted 14662 * already. 14663 * 14664 * Starting from {@link Build.VERSION_CODES#VANILLA_ICE_CREAM}, after the security logging 14665 * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 14666 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 14667 * successfully set or not. This callback will contain: 14668 * <ul> 14669 * <li> The policy identifier {@link DevicePolicyIdentifiers#SECURITY_LOGGING_POLICY} 14670 * <li> The {@link TargetUser} that this policy relates to 14671 * <li> The {@link PolicyUpdateResult}, which will be 14672 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 14673 * reason the policy failed to be set 14674 * e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 14675 * </ul> 14676 * If there has been a change to the policy, 14677 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 14678 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 14679 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 14680 * will contain the reason why the policy changed. 14681 * 14682 * @param admin Which device admin this request is associated with, or {@code null} 14683 * if called by a delegated app. 14684 * @param enabled whether security logging should be enabled or not. 14685 * @throws SecurityException if the caller is not permitted to control security logging. 14686 * @see #setAffiliationIds 14687 * @see #retrieveSecurityLogs 14688 */ 14689 @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true) 14690 @SupportsCoexistence setSecurityLoggingEnabled(@ullable ComponentName admin, boolean enabled)14691 public void setSecurityLoggingEnabled(@Nullable ComponentName admin, boolean enabled) { 14692 throwIfParentInstance("setSecurityLoggingEnabled"); 14693 try { 14694 mService.setSecurityLoggingEnabled(admin, mContext.getPackageName(), enabled); 14695 } catch (RemoteException re) { 14696 throw re.rethrowFromSystemServer(); 14697 } 14698 } 14699 14700 /** 14701 * Return whether security logging is enabled or not by the admin. 14702 * 14703 * <p>Can only be called by the device owner or a profile owner of an organization-owned 14704 * managed profile, otherwise a {@link SecurityException} will be thrown. 14705 * 14706 * @param admin Which device admin this request is associated with. Null if the caller is not 14707 * a device admin 14708 * @return {@code true} if security logging is enabled, {@code false} otherwise. 14709 * @throws SecurityException if the caller is not allowed to control security logging. 14710 */ 14711 @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true) isSecurityLoggingEnabled(@ullable ComponentName admin)14712 public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) { 14713 throwIfParentInstance("isSecurityLoggingEnabled"); 14714 try { 14715 return mService.isSecurityLoggingEnabled(admin, mContext.getPackageName()); 14716 } catch (RemoteException re) { 14717 throw re.rethrowFromSystemServer(); 14718 } 14719 } 14720 14721 /** 14722 * Controls whether audit logging is enabled. 14723 * 14724 * @hide 14725 */ 14726 @SystemApi 14727 @RequiresPermission(permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING) setAuditLogEnabled(boolean enabled)14728 public void setAuditLogEnabled(boolean enabled) { 14729 throwIfParentInstance("setAuditLogEnabled"); 14730 try { 14731 mService.setAuditLogEnabled(mContext.getPackageName(), enabled); 14732 } catch (RemoteException re) { 14733 re.rethrowFromSystemServer(); 14734 } 14735 } 14736 14737 /** 14738 * @return Whether audit logging is enabled. 14739 * 14740 * @hide 14741 */ 14742 @SystemApi 14743 @RequiresPermission(permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING) isAuditLogEnabled()14744 public boolean isAuditLogEnabled() { 14745 throwIfParentInstance("isAuditLogEnabled"); 14746 try { 14747 return mService.isAuditLogEnabled(mContext.getPackageName()); 14748 } catch (RemoteException re) { 14749 throw re.rethrowFromSystemServer(); 14750 } 14751 } 14752 14753 /** 14754 * Sets audit log event callback. Only one callback per UID is active at any time, when a new 14755 * callback is set, the previous one is forgotten. Should only be called when audit log policy 14756 * is enforced by the caller. Disabling the policy clears the callback. Each time a new callback 14757 * is set, it will first be invoked with all the audit log events available at the time. 14758 * 14759 * @param callback The callback to invoke when new audit log events become available. 14760 * @param executor The executor through which the callback should be invoked. 14761 * @hide 14762 */ 14763 @SystemApi 14764 @RequiresPermission(permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING) setAuditLogEventCallback( @onNull @allbackExecutor Executor executor, @NonNull Consumer<List<SecurityEvent>> callback)14765 public void setAuditLogEventCallback( 14766 @NonNull @CallbackExecutor Executor executor, 14767 @NonNull Consumer<List<SecurityEvent>> callback) { 14768 throwIfParentInstance("setAuditLogEventCallback"); 14769 final IAuditLogEventsCallback wrappedCallback = 14770 new IAuditLogEventsCallback.Stub() { 14771 @Override 14772 public void onNewAuditLogEvents(List<SecurityEvent> events) { 14773 executor.execute(() -> callback.accept(events)); 14774 } 14775 }; 14776 try { 14777 mService.setAuditLogEventsCallback(mContext.getPackageName(), wrappedCallback); 14778 } catch (RemoteException re) { 14779 throw re.rethrowFromSystemServer(); 14780 } 14781 } 14782 14783 /** 14784 * Clears audit log event callback. If a callback was set previously, it may still get invoked 14785 * after this call returns if it was already scheduled. 14786 * 14787 * @hide 14788 */ 14789 @SystemApi 14790 @RequiresPermission(permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING) clearAuditLogEventCallback()14791 public void clearAuditLogEventCallback() { 14792 throwIfParentInstance("clearAuditLogEventCallback"); 14793 try { 14794 mService.setAuditLogEventsCallback(mContext.getPackageName(), null); 14795 } catch (RemoteException re) { 14796 throw re.rethrowFromSystemServer(); 14797 } 14798 } 14799 14800 /** 14801 * Called by device owner or profile owner of an organization-owned managed profile to retrieve 14802 * all new security logging entries since the last call to this API after device boots. 14803 * 14804 * <p> Access to the logs is rate limited and it will only return new logs after the admin has 14805 * been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}. 14806 * 14807 * <p> When called by a device owner, if there is any other user or profile on the device, 14808 * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown. 14809 * See {@link #isAffiliatedUser}. 14810 * 14811 * @param admin Which device admin this request is associated with, or {@code null} 14812 * if called by a delegated app. 14813 * @return the new batch of security logs which is a list of {@link SecurityEvent}, 14814 * or {@code null} if rate limitation is exceeded or if logging is currently disabled. 14815 * @throws SecurityException if the caller is not allowed to access security logging, 14816 * or there is at least one profile or secondary user that is not affiliated with the device. 14817 * @see #isAffiliatedUser 14818 * @see DeviceAdminReceiver#onSecurityLogsAvailable 14819 */ 14820 @SuppressLint("NullableCollection") 14821 @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true) retrieveSecurityLogs(@ullable ComponentName admin)14822 public @Nullable List<SecurityEvent> retrieveSecurityLogs(@Nullable ComponentName admin) { 14823 throwIfParentInstance("retrieveSecurityLogs"); 14824 try { 14825 ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs( 14826 admin, mContext.getPackageName()); 14827 if (list != null) { 14828 return list.getList(); 14829 } else { 14830 // Rate limit exceeded. 14831 return null; 14832 } 14833 } catch (RemoteException re) { 14834 throw re.rethrowFromSystemServer(); 14835 } 14836 } 14837 14838 /** 14839 * Makes all accumulated network logs available to DPC in a new batch. 14840 * If throttled, returns time to wait in milliseconds, otherwise 0. 14841 * @hide 14842 */ 14843 @TestApi 14844 @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS) forceNetworkLogs()14845 public long forceNetworkLogs() { 14846 if (mService == null) { 14847 return -1; 14848 } 14849 try { 14850 return mService.forceNetworkLogs(); 14851 } catch (RemoteException re) { 14852 throw re.rethrowFromSystemServer(); 14853 } 14854 } 14855 14856 /** 14857 * Forces a batch of security logs to be fetched from logd and makes it available for DPC. 14858 * If throttled, returns time to wait in milliseconds, otherwise 0. 14859 * @hide 14860 */ 14861 @TestApi 14862 @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS) forceSecurityLogs()14863 public long forceSecurityLogs() { 14864 if (mService == null) { 14865 return 0; 14866 } 14867 try { 14868 return mService.forceSecurityLogs(); 14869 } catch (RemoteException re) { 14870 throw re.rethrowFromSystemServer(); 14871 } 14872 } 14873 14874 /** 14875 * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent 14876 * profile. 14877 * 14878 * @hide 14879 */ getParentProfileInstance(UserInfo uInfo)14880 public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) { 14881 mContext.checkSelfPermission( 14882 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 14883 if (!uInfo.isManagedProfile()) { 14884 throw new SecurityException("The user " + uInfo.id 14885 + " does not have a parent profile."); 14886 } 14887 return new DevicePolicyManager(mContext, mService, true); 14888 } 14889 14890 /** 14891 * Called by a device or profile owner to restrict packages from using metered data. 14892 * 14893 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 14894 * @param packageNames the list of package names to be restricted. 14895 * @return a list of package names which could not be restricted. 14896 * @throws SecurityException if {@code admin} is not a device or profile owner. 14897 */ setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)14898 public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin, 14899 @NonNull List<String> packageNames) { 14900 throwIfParentInstance("setMeteredDataDisabled"); 14901 if (mService != null) { 14902 try { 14903 return mService.setMeteredDataDisabledPackages(admin, packageNames); 14904 } catch (RemoteException re) { 14905 throw re.rethrowFromSystemServer(); 14906 } 14907 } 14908 return packageNames; 14909 } 14910 14911 /** 14912 * Called by a device or profile owner to retrieve the list of packages which are restricted 14913 * by the admin from using metered data. 14914 * 14915 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 14916 * @return the list of restricted package names. 14917 * @throws SecurityException if {@code admin} is not a device or profile owner. 14918 */ getMeteredDataDisabledPackages(@onNull ComponentName admin)14919 public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) { 14920 throwIfParentInstance("getMeteredDataDisabled"); 14921 if (mService != null) { 14922 try { 14923 return mService.getMeteredDataDisabledPackages(admin); 14924 } catch (RemoteException re) { 14925 throw re.rethrowFromSystemServer(); 14926 } 14927 } 14928 return new ArrayList<>(); 14929 } 14930 14931 /** 14932 * Called by the system to check if a package is restricted from using metered data 14933 * by {@param admin}. 14934 * 14935 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 14936 * @param packageName the package whose restricted status is needed. 14937 * @param userId the user to which {@param packageName} belongs. 14938 * @return {@code true} if the package is restricted by admin, otherwise {@code false} 14939 * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID} 14940 * @hide 14941 */ isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)14942 public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin, 14943 String packageName, @UserIdInt int userId) { 14944 throwIfParentInstance("getMeteredDataDisabledForUser"); 14945 if (mService != null) { 14946 try { 14947 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId); 14948 } catch (RemoteException re) { 14949 throw re.rethrowFromSystemServer(); 14950 } 14951 } 14952 return false; 14953 } 14954 14955 /** 14956 * Called by device owner or profile owner of an organization-owned managed profile to retrieve 14957 * device logs from before the device's last reboot. 14958 * <p> 14959 * <strong> This API is not supported on all devices. Calling this API on unsupported devices 14960 * will result in {@code null} being returned. The device logs are retrieved from a RAM region 14961 * which is not guaranteed to be corruption-free during power cycles, as a result be cautious 14962 * about data corruption when parsing. </strong> 14963 * 14964 * <p> When called by a device owner, if there is any other user or profile on the device, 14965 * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown. 14966 * See {@link #isAffiliatedUser}. 14967 * 14968 * @param admin Which device admin this request is associated with, or {@code null} 14969 * if called by a delegated app. 14970 * @return Device logs from before the latest reboot of the system, or {@code null} if this API 14971 * is not supported on the device. 14972 * @throws SecurityException if the caller is not allowed to access security logging, or 14973 * there is at least one profile or secondary user that is not affiliated with the device. 14974 * @see #isAffiliatedUser 14975 * @see #retrieveSecurityLogs 14976 */ 14977 @SuppressLint("NullableCollection") 14978 @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true) retrievePreRebootSecurityLogs( @ullable ComponentName admin)14979 public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs( 14980 @Nullable ComponentName admin) { 14981 throwIfParentInstance("retrievePreRebootSecurityLogs"); 14982 try { 14983 ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs( 14984 admin, mContext.getPackageName()); 14985 if (list != null) { 14986 return list.getList(); 14987 } else { 14988 return null; 14989 } 14990 } catch (RemoteException re) { 14991 throw re.rethrowFromSystemServer(); 14992 } 14993 } 14994 14995 /** 14996 * Called by a profile owner of a managed profile to set the color used for customization. This 14997 * color is used as background color of the confirm credentials screen for that user. The 14998 * default color is teal (#00796B). 14999 * <p> 15000 * The confirm credentials screen can be created using 15001 * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}. 15002 * <p> 15003 * Starting from Android R, the organization color will no longer be used as the background 15004 * color of the confirm credentials screen. 15005 * 15006 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 15007 * @param color The 24bit (0xRRGGBB) representation of the color to be used. 15008 * @throws SecurityException if {@code admin} is not a profile owner. 15009 * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never 15010 * used as the background color of the confirm credentials screen. 15011 */ 15012 @Deprecated setOrganizationColor(@onNull ComponentName admin, int color)15013 public void setOrganizationColor(@NonNull ComponentName admin, int color) { 15014 throwIfParentInstance("setOrganizationColor"); 15015 try { 15016 // always enforce alpha channel to have 100% opacity 15017 color |= 0xFF000000; 15018 mService.setOrganizationColor(admin, color); 15019 } catch (RemoteException re) { 15020 throw re.rethrowFromSystemServer(); 15021 } 15022 } 15023 15024 /** 15025 * @hide 15026 * 15027 * Sets the color used for customization. 15028 * 15029 * @param color The 24bit (0xRRGGBB) representation of the color to be used. 15030 * @param userId which user to set the color to. 15031 * @RequiresPermission(allOf = { 15032 * Manifest.permission.MANAGE_USERS, 15033 * Manifest.permission.INTERACT_ACROSS_USERS_FULL}) 15034 * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never 15035 * used as the background color of the confirm credentials screen. 15036 */ 15037 @Deprecated setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)15038 public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) { 15039 try { 15040 // always enforce alpha channel to have 100% opacity 15041 color |= 0xFF000000; 15042 mService.setOrganizationColorForUser(color, userId); 15043 } catch (RemoteException re) { 15044 throw re.rethrowFromSystemServer(); 15045 } 15046 } 15047 15048 /** 15049 * Called by a profile owner of a managed profile to retrieve the color used for customization. 15050 * This color is used as background color of the confirm credentials screen for that user. 15051 * 15052 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 15053 * @return The 24bit (0xRRGGBB) representation of the color to be used. 15054 * @throws SecurityException if {@code admin} is not a profile owner. 15055 * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never 15056 * used as the background color of the confirm credentials screen. 15057 */ 15058 @Deprecated getOrganizationColor(@onNull ComponentName admin)15059 public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) { 15060 throwIfParentInstance("getOrganizationColor"); 15061 try { 15062 return mService.getOrganizationColor(admin); 15063 } catch (RemoteException re) { 15064 throw re.rethrowFromSystemServer(); 15065 } 15066 } 15067 15068 /** 15069 * @hide 15070 * Retrieve the customization color for a given user. 15071 * 15072 * @param userHandle The user id of the user we're interested in. 15073 * @return The 24bit (0xRRGGBB) representation of the color to be used. 15074 * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never 15075 * used as the background color of the confirm credentials screen. 15076 */ 15077 @Deprecated getOrganizationColorForUser(int userHandle)15078 public @ColorInt int getOrganizationColorForUser(int userHandle) { 15079 try { 15080 return mService.getOrganizationColorForUser(userHandle); 15081 } catch (RemoteException re) { 15082 throw re.rethrowFromSystemServer(); 15083 } 15084 } 15085 15086 /** 15087 * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of 15088 * the organization under management. 15089 * 15090 * <p>If the organization name needs to be localized, it is the responsibility of the caller 15091 * to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set a new version of this 15092 * string accordingly. 15093 * 15094 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 15095 * caller is not a device admin. 15096 * @param title The organization name or {@code null} to clear a previously set name. 15097 * @throws SecurityException if {@code admin} is not a device or profile owner. 15098 */ 15099 @RequiresPermission(value = MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY, conditional = true) setOrganizationName(@ullable ComponentName admin, @Nullable CharSequence title)15100 public void setOrganizationName(@Nullable ComponentName admin, @Nullable CharSequence title) { 15101 throwIfParentInstance("setOrganizationName"); 15102 try { 15103 mService.setOrganizationName(admin, mContext.getPackageName(), title); 15104 } catch (RemoteException re) { 15105 throw re.rethrowFromSystemServer(); 15106 } 15107 } 15108 15109 /** 15110 * Called by the device owner (since API 26) or profile owner (since API 24) or holders of the 15111 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY 15112 * to retrieve the name of the organization under management. 15113 * 15114 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 15115 * caller is not a device admin. 15116 * @return The organization name or {@code null} if none is set. 15117 * @throws SecurityException if {@code admin} if {@code admin} is not a device or profile 15118 * owner or holder of the 15119 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY}. 15120 */ 15121 @RequiresPermission(value = MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY, conditional = true) getOrganizationName(@ullable ComponentName admin)15122 public @Nullable CharSequence getOrganizationName(@Nullable ComponentName admin) { 15123 throwIfParentInstance("getOrganizationName"); 15124 try { 15125 return mService.getOrganizationName(admin, mContext.getPackageName()); 15126 } catch (RemoteException re) { 15127 throw re.rethrowFromSystemServer(); 15128 } 15129 } 15130 15131 private final IpcDataCache<Void, CharSequence> mGetDeviceOwnerOrganizationNameCache = 15132 new IpcDataCache(sDpmCaches.child("getDeviceOwnerOrganizationName"), 15133 (query) -> getService().getDeviceOwnerOrganizationName()); 15134 15135 /** 15136 * Called by the system to retrieve the name of the organization managing the device. 15137 * 15138 * @return The organization name or {@code null} if none is set. 15139 * @throws SecurityException if the caller is not the device owner, does not hold the 15140 * MANAGE_USERS permission and is not the system. 15141 * 15142 * @hide 15143 */ 15144 @SystemApi 15145 @SuppressLint("RequiresPermission") getDeviceOwnerOrganizationName()15146 public @Nullable CharSequence getDeviceOwnerOrganizationName() { 15147 return mGetDeviceOwnerOrganizationNameCache.query(null); 15148 } 15149 15150 private final IpcDataCache<Integer, CharSequence> mGetOrganizationNameForUserCache = 15151 new IpcDataCache<>(sDpmCaches.child("getOrganizationNameForUser"), 15152 (query) -> getService().getOrganizationNameForUser(query)); 15153 15154 /** 15155 * Retrieve the default title message used in the confirm credentials screen for a given user. 15156 * 15157 * @param userHandle The user id of the user we're interested in. 15158 * @return The organization name or {@code null} if none is set. 15159 * 15160 * @hide 15161 */ getOrganizationNameForUser(int userHandle)15162 public @Nullable CharSequence getOrganizationNameForUser(int userHandle) { 15163 return mGetOrganizationNameForUserCache.query(userHandle); 15164 } 15165 15166 /** 15167 * @return the {@link UserProvisioningState} for the current user - for unmanaged users will 15168 * return {@link #STATE_USER_UNMANAGED} 15169 * @hide 15170 */ 15171 @SystemApi 15172 @RequiresPermission(anyOf = { 15173 android.Manifest.permission.MANAGE_USERS, 15174 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS 15175 }) 15176 @UserProvisioningState 15177 @UserHandleAware( 15178 enabledSinceTargetSdkVersion = UPSIDE_DOWN_CAKE, 15179 requiresPermissionIfNotCaller = INTERACT_ACROSS_USERS) getUserProvisioningState()15180 public int getUserProvisioningState() { 15181 throwIfParentInstance("getUserProvisioningState"); 15182 if (mService != null) { 15183 try { 15184 return mService.getUserProvisioningState(mContext.getUserId()); 15185 } catch (RemoteException e) { 15186 throw e.rethrowFromSystemServer(); 15187 } 15188 } 15189 return STATE_USER_UNMANAGED; 15190 } 15191 15192 /** 15193 * Set the {@link UserProvisioningState} for the supplied user, if they are managed. 15194 * 15195 * @param state to store 15196 * @param userHandle for user 15197 * 15198 * @hide 15199 */ 15200 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) setUserProvisioningState(@serProvisioningState int state, int userHandle)15201 public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) { 15202 if (mService != null) { 15203 try { 15204 mService.setUserProvisioningState(state, userHandle); 15205 } catch (RemoteException e) { 15206 throw e.rethrowFromSystemServer(); 15207 } 15208 } 15209 } 15210 15211 /** 15212 * Set the {@link UserProvisioningState} for the supplied user. The supplied user has to be 15213 * manged, otherwise it will throw an {@link IllegalStateException}. 15214 * 15215 * <p> For managed users/profiles/devices, only the following state changes are allowed: 15216 * <ul> 15217 * <li>{@link #STATE_USER_UNMANAGED} can change to any other state except itself 15218 * <li>{@link #STATE_USER_SETUP_INCOMPLETE} and {@link #STATE_USER_SETUP_COMPLETE} can only 15219 * change to {@link #STATE_USER_SETUP_FINALIZED}</li> 15220 * <li>{@link #STATE_USER_PROFILE_COMPLETE} can only change to 15221 * {@link #STATE_USER_PROFILE_FINALIZED}</li> 15222 * <li>{@link #STATE_USER_SETUP_FINALIZED} can't be changed to any other state</li> 15223 * <li>{@link #STATE_USER_PROFILE_FINALIZED} can only change to 15224 * {@link #STATE_USER_UNMANAGED}</li> 15225 * </ul> 15226 * @param state to store 15227 * @param userHandle for user 15228 * @throws IllegalStateException if called with an invalid state change. 15229 * 15230 * @hide 15231 */ 15232 @SystemApi 15233 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) setUserProvisioningState( @serProvisioningState int state, @NonNull UserHandle userHandle)15234 public void setUserProvisioningState( 15235 @UserProvisioningState int state, @NonNull UserHandle userHandle) { 15236 setUserProvisioningState(state, userHandle.getIdentifier()); 15237 } 15238 15239 /** 15240 * Indicates the entity that controls the device. Two users are 15241 * affiliated if the set of ids set by the device owner and the admin of the secondary user. 15242 * 15243 * <p>A user that is affiliated with the device owner user is considered to be 15244 * affiliated with the device. 15245 * 15246 * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging 15247 * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user 15248 * is created, until it becomes affiliated. Therefore it is recommended that the appropriate 15249 * affiliation ids are set by its owner as soon as possible after the user is 15250 * created. 15251 * <p> 15252 * Note: This method used to be available for affiliating device owner and profile 15253 * owner. However, since Android 11, this combination is not possible. This method is now 15254 * only useful for affiliating the primary user with managed secondary users. 15255 * 15256 * @param admin Which device owner, or owner of secondary user, this request is associated with. 15257 * @param ids A set of opaque non-empty affiliation ids. 15258 * 15259 * @throws IllegalArgumentException if {@code ids} is null or contains an empty string. 15260 * @see #isAffiliatedUser 15261 */ setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)15262 public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) { 15263 throwIfParentInstance("setAffiliationIds"); 15264 if (ids == null) { 15265 throw new IllegalArgumentException("ids must not be null"); 15266 } 15267 try { 15268 mService.setAffiliationIds(admin, new ArrayList<>(ids)); 15269 } catch (RemoteException e) { 15270 throw e.rethrowFromSystemServer(); 15271 } 15272 } 15273 15274 /** 15275 * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an 15276 * empty set if none have been set. 15277 */ getAffiliationIds(@onNull ComponentName admin)15278 public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) { 15279 throwIfParentInstance("getAffiliationIds"); 15280 try { 15281 return new ArraySet<>(mService.getAffiliationIds(admin)); 15282 } catch (RemoteException e) { 15283 throw e.rethrowFromSystemServer(); 15284 } 15285 } 15286 15287 /** 15288 * Returns whether this user is affiliated with the device. 15289 * <p> 15290 * By definition, the user that the device owner runs on is always affiliated with the device. 15291 * Any other user is considered affiliated with the device if the set specified by its 15292 * profile owner via {@link #setAffiliationIds} intersects with the device owner's. 15293 * @see #setAffiliationIds 15294 */ isAffiliatedUser()15295 public boolean isAffiliatedUser() { 15296 throwIfParentInstance("isAffiliatedUser"); 15297 try { 15298 return mService.isCallingUserAffiliated(); 15299 } catch (RemoteException e) { 15300 throw e.rethrowFromSystemServer(); 15301 } 15302 } 15303 15304 /** 15305 * @hide 15306 * Returns whether target user is affiliated with the device. 15307 */ isAffiliatedUser(@serIdInt int userId)15308 public boolean isAffiliatedUser(@UserIdInt int userId) { 15309 try { 15310 return mService.isAffiliatedUser(userId); 15311 } catch (RemoteException e) { 15312 throw e.rethrowFromSystemServer(); 15313 } 15314 } 15315 15316 /** 15317 * @hide 15318 * Returns whether the uninstall for {@code packageName} for the current user is in queue 15319 * to be started 15320 * @param packageName the package to check for 15321 * @return whether the uninstall intent for {@code packageName} is pending 15322 */ isUninstallInQueue(String packageName)15323 public boolean isUninstallInQueue(String packageName) { 15324 try { 15325 return mService.isUninstallInQueue(packageName); 15326 } catch (RemoteException re) { 15327 throw re.rethrowFromSystemServer(); 15328 } 15329 } 15330 15331 /** 15332 * @hide 15333 * @param packageName the package containing active DAs to be uninstalled 15334 */ uninstallPackageWithActiveAdmins(String packageName)15335 public void uninstallPackageWithActiveAdmins(String packageName) { 15336 try { 15337 mService.uninstallPackageWithActiveAdmins(packageName); 15338 } catch (RemoteException re) { 15339 throw re.rethrowFromSystemServer(); 15340 } 15341 } 15342 15343 /** 15344 * @hide 15345 * Remove a test admin synchronously without sending it a broadcast about being removed. 15346 * If the admin is a profile owner or device owner it will still be removed. 15347 * 15348 * @param userHandle user id to remove the admin for. 15349 * @param admin The administration compononent to remove. 15350 * @throws SecurityException if the caller is not shell / root or the admin package 15351 * isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}. 15352 */ 15353 @TestApi 15354 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) forceRemoveActiveAdmin( @onNull ComponentName adminReceiver, @UserIdInt int userHandle)15355 public void forceRemoveActiveAdmin( 15356 @NonNull ComponentName adminReceiver, @UserIdInt int userHandle) { 15357 try { 15358 mService.forceRemoveActiveAdmin(adminReceiver, userHandle); 15359 } catch (RemoteException re) { 15360 throw re.rethrowFromSystemServer(); 15361 } 15362 } 15363 15364 /** 15365 * Returns whether the device has been provisioned. 15366 * 15367 * <p>Not for use by third-party applications. 15368 * 15369 * @hide 15370 */ 15371 @SystemApi 15372 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) isDeviceProvisioned()15373 public boolean isDeviceProvisioned() { 15374 try { 15375 return mService.isDeviceProvisioned(); 15376 } catch (RemoteException re) { 15377 throw re.rethrowFromSystemServer(); 15378 } 15379 } 15380 15381 /** 15382 * Writes that the provisioning configuration has been applied. 15383 * 15384 * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} 15385 * permission. 15386 * 15387 * <p>Not for use by third-party applications. 15388 * 15389 * @hide 15390 */ 15391 @SystemApi 15392 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) setDeviceProvisioningConfigApplied()15393 public void setDeviceProvisioningConfigApplied() { 15394 try { 15395 mService.setDeviceProvisioningConfigApplied(); 15396 } catch (RemoteException re) { 15397 throw re.rethrowFromSystemServer(); 15398 } 15399 } 15400 15401 /** 15402 * Returns whether the provisioning configuration has been applied. 15403 * 15404 * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission. 15405 * 15406 * <p>Not for use by third-party applications. 15407 * 15408 * @return whether the provisioning configuration has been applied. 15409 * 15410 * @hide 15411 */ 15412 @SystemApi 15413 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) isDeviceProvisioningConfigApplied()15414 public boolean isDeviceProvisioningConfigApplied() { 15415 try { 15416 return mService.isDeviceProvisioningConfigApplied(); 15417 } catch (RemoteException re) { 15418 throw re.rethrowFromSystemServer(); 15419 } 15420 } 15421 15422 /** 15423 * @hide 15424 * Force update user setup completed status for the given {@code userId}. 15425 * @throws {@link SecurityException} if the caller has no 15426 * {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS}. 15427 */ 15428 @TestApi forceUpdateUserSetupComplete(@serIdInt int userId)15429 public void forceUpdateUserSetupComplete(@UserIdInt int userId) { 15430 try { 15431 mService.forceUpdateUserSetupComplete(userId); 15432 } catch (RemoteException re) { 15433 throw re.rethrowFromSystemServer(); 15434 } 15435 } 15436 15437 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) throwIfParentInstance(String functionName)15438 private void throwIfParentInstance(String functionName) { 15439 if (mParentInstance) { 15440 throw new SecurityException(functionName + " cannot be called on the parent instance"); 15441 } 15442 } 15443 15444 /** 15445 * Allows the device owner or profile owner to enable or disable the backup service. 15446 * 15447 * <p> Each user has its own backup service which manages the backup and restore mechanisms in 15448 * that user. Disabling the backup service will prevent data from being backed up or restored. 15449 * 15450 * <p> Device owner calls this API to control backup services across all users on the device. 15451 * Profile owner can use this API to enable or disable the profile's backup service. However, 15452 * for a managed profile its backup functionality is only enabled if both the device owner 15453 * and the profile owner have enabled the backup service. 15454 * 15455 * <p> By default, backup service is disabled on a device with device owner, and within a 15456 * managed profile. 15457 * 15458 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 15459 * @param enabled {@code true} to enable the backup service, {@code false} to disable it. 15460 * @throws SecurityException if {@code admin} is not a device owner or a profile owner. 15461 */ setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)15462 public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) { 15463 throwIfParentInstance("setBackupServiceEnabled"); 15464 try { 15465 mService.setBackupServiceEnabled(admin, enabled); 15466 } catch (RemoteException re) { 15467 throw re.rethrowFromSystemServer(); 15468 } 15469 } 15470 15471 /** 15472 * Return whether the backup service is enabled by the device owner or profile owner for the 15473 * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}. 15474 * 15475 * <p> Whether the backup functionality is actually enabled or not depends on settings from both 15476 * the current user and the device owner, please see 15477 * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details. 15478 * 15479 * <p> Backup service manages all backup and restore mechanisms on the device. 15480 * 15481 * @return {@code true} if backup service is enabled, {@code false} otherwise. 15482 * @see #setBackupServiceEnabled 15483 */ isBackupServiceEnabled(@onNull ComponentName admin)15484 public boolean isBackupServiceEnabled(@NonNull ComponentName admin) { 15485 throwIfParentInstance("isBackupServiceEnabled"); 15486 try { 15487 return mService.isBackupServiceEnabled(admin); 15488 } catch (RemoteException re) { 15489 throw re.rethrowFromSystemServer(); 15490 } 15491 } 15492 15493 /** 15494 * Called by a device owner, profile owner of a managed profile or delegated app with 15495 * {@link #DELEGATION_NETWORK_LOGGING} to control the network logging feature. 15496 * 15497 * <p> Supported for a device owner from Android 8 and a delegated app granted by a device 15498 * owner from Android 10. Supported for a profile owner of a managed profile and a delegated 15499 * app granted by a profile owner from Android 12. When network logging is enabled by a 15500 * profile owner, the network logs will only include work profile network activity, not 15501 * activity on the personal profile. 15502 * 15503 * <p> Network logs contain DNS lookup and connect() library call events. The following library 15504 * functions are recorded while network logging is active: 15505 * <ul> 15506 * <li>{@code getaddrinfo()}</li> 15507 * <li>{@code gethostbyname()}</li> 15508 * <li>{@code connect()}</li> 15509 * </ul> 15510 * 15511 * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use 15512 * full system call logging; event reporting is enabled by default for all processes but not 15513 * strongly enforced. 15514 * Events from applications using alternative implementations of libc, making direct kernel 15515 * calls, or deliberately obfuscating traffic may not be recorded. 15516 * 15517 * <p> Some common network events may not be reported. For example: 15518 * <ul> 15519 * <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use 15520 * an alternative system for name resolution, and so avoid calling 15521 * {@code getaddrinfo()} or {@code gethostbyname}.</li> 15522 * <li>Applications may use datagram sockets for performance reasons, for example 15523 * for a game client. Calling {@code connect()} is unnecessary for this kind of 15524 * socket, so it will not trigger a network event.</li> 15525 * </ul> 15526 * 15527 * <p> It is possible to directly intercept layer 3 traffic leaving the device using an 15528 * always-on VPN service. 15529 * See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} 15530 * and {@link android.net.VpnService} for details. 15531 * 15532 * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there 15533 * are unaffiliated secondary users or profiles on the device, regardless of whether the 15534 * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for 15535 * all users to become affiliated. Therefore it's recommended that affiliation ids are set for 15536 * new users as soon as possible after provisioning via {@link #setAffiliationIds}. 15537 * 15538 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 15539 * {@code null} if called by a delegated app. 15540 * @param enabled whether network logging should be enabled or not. 15541 * @throws SecurityException if {@code admin} is not a device owner or profile owner. 15542 * @see #setAffiliationIds 15543 * @see #retrieveNetworkLogs 15544 */ setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)15545 public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) { 15546 throwIfParentInstance("setNetworkLoggingEnabled"); 15547 try { 15548 mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled); 15549 } catch (RemoteException re) { 15550 throw re.rethrowFromSystemServer(); 15551 } 15552 } 15553 15554 private IpcDataCache<ComponentName, Boolean> mIsNetworkLoggingEnabledCache = 15555 new IpcDataCache<>(sDpmCaches.child("isNetworkLoggingEnabled"), 15556 (admin) -> getService().isNetworkLoggingEnabled(admin, 15557 getContext().getPackageName())); 15558 15559 /** 15560 * Return whether network logging is enabled by a device owner or profile owner of 15561 * a managed profile. 15562 * 15563 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only 15564 * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING} 15565 * or has MANAGE_USERS permission. 15566 * @return {@code true} if network logging is enabled by device owner or profile owner, 15567 * {@code false} otherwise. 15568 * @throws SecurityException if {@code admin} is not a device owner or profile owner and 15569 * caller has no MANAGE_USERS permission 15570 */ isNetworkLoggingEnabled(@ullable ComponentName admin)15571 public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) { 15572 throwIfParentInstance("isNetworkLoggingEnabled"); 15573 return mIsNetworkLoggingEnabledCache.query(admin); 15574 } 15575 15576 /** 15577 * Called by device owner, profile owner of a managed profile or delegated app with 15578 * {@link #DELEGATION_NETWORK_LOGGING} to retrieve the most recent batch of 15579 * network logging events. 15580 * 15581 * <p> When network logging is enabled by a profile owner, the network logs will only include 15582 * work profile network activity, not activity on the personal profile. 15583 * 15584 * A device owner or profile owner has to provide a batchToken provided as part of 15585 * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the 15586 * token of the most recent available batch of logs, {@code null} will be returned. 15587 * 15588 * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}. 15589 * 15590 * <p> The list of network events is sorted chronologically, and contains at most 1200 events. 15591 * 15592 * <p> Access to the logs is rate limited and this method will only return a new batch of logs 15593 * after the device device owner has been notified via 15594 * {@link DeviceAdminReceiver#onNetworkLogsAvailable}. 15595 * 15596 * <p>If the caller is not a profile owner and a secondary user or profile is created, calling 15597 * this method will throw a {@link SecurityException} until all users become affiliated again. 15598 * It will also no longer be possible to retrieve the network logs batch with the most recent 15599 * batchToken provided by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. 15600 * See {@link DevicePolicyManager#setAffiliationIds}. 15601 * 15602 * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or 15603 * {@code null} if called by a delegated app. 15604 * @param batchToken A token of the batch to retrieve 15605 * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns 15606 * {@code null} if the batch represented by batchToken is no longer available or if 15607 * logging is disabled. 15608 * @throws SecurityException if {@code admin} is not a device owner, profile owner or if the 15609 * {@code admin} is not a profile owner and there is at least one profile or secondary user 15610 * that is not affiliated with the device. 15611 * @see #setAffiliationIds 15612 * @see DeviceAdminReceiver#onNetworkLogsAvailable 15613 */ retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)15614 public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin, 15615 long batchToken) { 15616 throwIfParentInstance("retrieveNetworkLogs"); 15617 try { 15618 return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken); 15619 } catch (RemoteException re) { 15620 throw re.rethrowFromSystemServer(); 15621 } 15622 } 15623 15624 /** 15625 * Called by a device owner to bind to a service from a secondary managed user or vice versa. 15626 * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a 15627 * device owner to bind to services of another managed user. 15628 * <p> 15629 * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}. 15630 * Note that the {@link Context} used to obtain this 15631 * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used 15632 * to bind to the {@link android.app.Service}. 15633 * <p> 15634 * Note: This method used to be available for communication between device owner and profile 15635 * owner. However, since Android 11, this combination is not possible. This method is now 15636 * only useful for communication between device owner and managed secondary users. 15637 * 15638 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 15639 * @param serviceIntent Identifies the service to connect to. The Intent must specify either an 15640 * explicit component name or a package name to match an 15641 * {@link IntentFilter} published by a service. 15642 * @param conn Receives information as the service is started and stopped in main thread. This 15643 * must be a valid {@link ServiceConnection} object; it must not be {@code null}. 15644 * @param flags Operation options for the binding operation. See 15645 * {@link Context#bindService(Intent, ServiceConnection, int)}. 15646 * @param targetUser Which user to bind to. Must be one of the users returned by 15647 * {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will 15648 * be thrown. 15649 * @return If you have successfully bound to the service, {@code true} is returned; 15650 * {@code false} is returned if the connection is not made and you will not 15651 * receive the service object. 15652 * 15653 * @see Context#bindService(Intent, ServiceConnection, int) 15654 * @see #getBindDeviceAdminTargetUsers(ComponentName) 15655 */ bindDeviceAdminServiceAsUser(@onNull ComponentName admin, @NonNull Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlagsBits int flags, @NonNull UserHandle targetUser)15656 public boolean bindDeviceAdminServiceAsUser(@NonNull ComponentName admin, 15657 @NonNull Intent serviceIntent, @NonNull ServiceConnection conn, 15658 @Context.BindServiceFlagsBits int flags, @NonNull UserHandle targetUser) { 15659 throwIfParentInstance("bindDeviceAdminServiceAsUser"); 15660 // Keep this in sync with ContextImpl.bindServiceCommon. 15661 try { 15662 final IServiceConnection sd = mContext.getServiceDispatcher( 15663 conn, mContext.getMainThreadHandler(), Integer.toUnsignedLong(flags)); 15664 serviceIntent.prepareToLeaveProcess(mContext); 15665 return mService.bindDeviceAdminServiceAsUser(admin, 15666 mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent, 15667 sd, Integer.toUnsignedLong(flags), targetUser.getIdentifier()); 15668 } catch (RemoteException re) { 15669 throw re.rethrowFromSystemServer(); 15670 } 15671 } 15672 15673 /** 15674 * See {@link #bindDeviceAdminServiceAsUser(ComponentName, Intent, ServiceConnection, int, 15675 * UserHandle)}. 15676 * Call {@link Context.BindServiceFlags#of(long)} to obtain a BindServiceFlags object. 15677 */ bindDeviceAdminServiceAsUser(@onNull ComponentName admin, @NonNull Intent serviceIntent, @NonNull ServiceConnection conn, @NonNull Context.BindServiceFlags flags, @NonNull UserHandle targetUser)15678 public boolean bindDeviceAdminServiceAsUser(@NonNull ComponentName admin, 15679 @NonNull Intent serviceIntent, @NonNull ServiceConnection conn, 15680 @NonNull Context.BindServiceFlags flags, @NonNull UserHandle targetUser) { 15681 throwIfParentInstance("bindDeviceAdminServiceAsUser"); 15682 // Keep this in sync with ContextImpl.bindServiceCommon. 15683 try { 15684 final IServiceConnection sd = mContext.getServiceDispatcher( 15685 conn, mContext.getMainThreadHandler(), flags.getValue()); 15686 serviceIntent.prepareToLeaveProcess(mContext); 15687 return mService.bindDeviceAdminServiceAsUser(admin, 15688 mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent, 15689 sd, flags.getValue(), targetUser.getIdentifier()); 15690 } catch (RemoteException re) { 15691 throw re.rethrowFromSystemServer(); 15692 } 15693 } 15694 15695 /** 15696 * Returns the list of target users that the calling device owner or owner of secondary user 15697 * can use when calling {@link #bindDeviceAdminServiceAsUser}. 15698 * <p> 15699 * A device owner can bind to a service from a secondary managed user and vice versa, provided 15700 * that both users are affiliated. See {@link #setAffiliationIds}. 15701 */ getBindDeviceAdminTargetUsers(@onNull ComponentName admin)15702 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 15703 throwIfParentInstance("getBindDeviceAdminTargetUsers"); 15704 try { 15705 return mService.getBindDeviceAdminTargetUsers(admin); 15706 } catch (RemoteException re) { 15707 throw re.rethrowFromSystemServer(); 15708 } 15709 } 15710 15711 /** 15712 * Called by the system to get the time at which the device owner last retrieved security 15713 * logging entries. 15714 * 15715 * @return the time at which the device owner most recently retrieved security logging entries, 15716 * in milliseconds since epoch; -1 if security logging entries were never retrieved. 15717 * @throws SecurityException if the caller is not the device owner, does not hold the 15718 * MANAGE_USERS permission and is not the system. 15719 * 15720 * @hide 15721 */ 15722 @TestApi getLastSecurityLogRetrievalTime()15723 public long getLastSecurityLogRetrievalTime() { 15724 try { 15725 return mService.getLastSecurityLogRetrievalTime(); 15726 } catch (RemoteException re) { 15727 throw re.rethrowFromSystemServer(); 15728 } 15729 } 15730 15731 /** 15732 * Called by the system to get the time at which the device owner last requested a bug report. 15733 * 15734 * @return the time at which the device owner most recently requested a bug report, in 15735 * milliseconds since epoch; -1 if a bug report was never requested. 15736 * @throws SecurityException if the caller is not the device owner, does not hold the 15737 * MANAGE_USERS permission and is not the system. 15738 * 15739 * @hide 15740 */ 15741 @TestApi getLastBugReportRequestTime()15742 public long getLastBugReportRequestTime() { 15743 try { 15744 return mService.getLastBugReportRequestTime(); 15745 } catch (RemoteException re) { 15746 throw re.rethrowFromSystemServer(); 15747 } 15748 } 15749 15750 /** 15751 * Called by the system to get the time at which the device owner or profile owner of a 15752 * managed profile last retrieved network logging events. 15753 * 15754 * @return the time at which the device owner or profile owner most recently retrieved network 15755 * logging events, in milliseconds since epoch; -1 if network logging events were 15756 * never retrieved. 15757 * @throws SecurityException if the caller is not the device owner, does not hold the 15758 * MANAGE_USERS permission and is not the system. 15759 * 15760 * @hide 15761 */ 15762 @TestApi getLastNetworkLogRetrievalTime()15763 public long getLastNetworkLogRetrievalTime() { 15764 try { 15765 return mService.getLastNetworkLogRetrievalTime(); 15766 } catch (RemoteException re) { 15767 throw re.rethrowFromSystemServer(); 15768 } 15769 } 15770 15771 /** 15772 * Returns true if the current user's IME was set by an admin. 15773 * 15774 * <p>Requires the caller to be the system server, a device owner or profile owner, or a holder 15775 * of the QUERY_ADMIN_POLICY permission. 15776 * 15777 * @throws SecurityException if the caller is not authorized 15778 * 15779 * @hide 15780 */ 15781 @TestApi isCurrentInputMethodSetByOwner()15782 public boolean isCurrentInputMethodSetByOwner() { 15783 try { 15784 return mService.isCurrentInputMethodSetByOwner(); 15785 } catch (RemoteException re) { 15786 throw re.rethrowFromSystemServer(); 15787 } 15788 } 15789 15790 /** 15791 * Called by the system to get a list of CA certificates that were installed by the device or 15792 * profile owner. 15793 * 15794 * <p> The caller must be the target user's device owner/profile Owner or hold the 15795 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission. 15796 * 15797 * @param user The user for whom to retrieve information. 15798 * @return list of aliases identifying CA certificates installed by the device or profile owner 15799 * @throws SecurityException if the caller does not have permission to retrieve information 15800 * about the given user's CA certificates. 15801 * 15802 * @hide 15803 */ 15804 @TestApi getOwnerInstalledCaCerts(@onNull UserHandle user)15805 public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) { 15806 try { 15807 return mService.getOwnerInstalledCaCerts(user).getList(); 15808 } catch (RemoteException re) { 15809 throw re.rethrowFromSystemServer(); 15810 } 15811 } 15812 15813 /** 15814 * Returns whether factory reset protection policy is supported on the device. 15815 * 15816 * @return {@code true} if the device support factory reset protection policy. 15817 * 15818 * @hide 15819 */ 15820 @TestApi isFactoryResetProtectionPolicySupported()15821 public boolean isFactoryResetProtectionPolicySupported() { 15822 try { 15823 return mService.isFactoryResetProtectionPolicySupported(); 15824 } catch (RemoteException re) { 15825 throw re.rethrowFromSystemServer(); 15826 } 15827 } 15828 15829 /** 15830 * Called by the device owner or profile owner to clear application user data of a given 15831 * package. The behaviour of this is equivalent to the target application calling 15832 * {@link android.app.ActivityManager#clearApplicationUserData()}. 15833 * 15834 * <p><strong>Note:</strong> an application can store data outside of its application data, e.g. 15835 * external storage or user dictionary. This data will not be wiped by calling this API. 15836 * 15837 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 15838 * @param packageName The name of the package which will have its user data wiped. 15839 * @param executor The executor through which the listener should be invoked. 15840 * @param listener A callback object that will inform the caller when the clearing is done. 15841 * @throws SecurityException if the caller is not the device owner/profile owner. 15842 */ clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)15843 public void clearApplicationUserData(@NonNull ComponentName admin, 15844 @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, 15845 @NonNull OnClearApplicationUserDataListener listener) { 15846 throwIfParentInstance("clearAppData"); 15847 Objects.requireNonNull(executor); 15848 Objects.requireNonNull(listener); 15849 try { 15850 mService.clearApplicationUserData(admin, packageName, 15851 new IPackageDataObserver.Stub() { 15852 public void onRemoveCompleted(String pkg, boolean succeeded) { 15853 executor.execute(() -> 15854 listener.onApplicationUserDataCleared(pkg, succeeded)); 15855 } 15856 }); 15857 } catch (RemoteException re) { 15858 throw re.rethrowFromSystemServer(); 15859 } 15860 } 15861 15862 /** 15863 * Called by a device owner to specify whether logout is enabled for all secondary users. The 15864 * system may show a logout button that stops the user and switches back to the primary user. 15865 * 15866 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 15867 * @param enabled whether logout should be enabled or not. 15868 * @throws SecurityException if {@code admin} is not a device owner. 15869 */ setLogoutEnabled(@onNull ComponentName admin, boolean enabled)15870 public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) { 15871 throwIfParentInstance("setLogoutEnabled"); 15872 try { 15873 mService.setLogoutEnabled(admin, enabled); 15874 } catch (RemoteException re) { 15875 throw re.rethrowFromSystemServer(); 15876 } 15877 } 15878 15879 /** 15880 * Returns whether logout is enabled by a device owner. 15881 * 15882 * @return {@code true} if logout is enabled by device owner, {@code false} otherwise. 15883 */ isLogoutEnabled()15884 public boolean isLogoutEnabled() { 15885 throwIfParentInstance("isLogoutEnabled"); 15886 try { 15887 return mService.isLogoutEnabled(); 15888 } catch (RemoteException re) { 15889 throw re.rethrowFromSystemServer(); 15890 } 15891 } 15892 15893 /** 15894 * Callback used in {@link #clearApplicationUserData} 15895 * to indicate that the clearing of an application's user data is done. 15896 */ 15897 public interface OnClearApplicationUserDataListener { 15898 /** 15899 * Method invoked when clearing the application user data has completed. 15900 * 15901 * @param packageName The name of the package which had its user data cleared. 15902 * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator 15903 * apps and protected system packages. 15904 */ onApplicationUserDataCleared(String packageName, boolean succeeded)15905 void onApplicationUserDataCleared(String packageName, boolean succeeded); 15906 } 15907 15908 /** 15909 * Returns set of system apps that should be removed during provisioning. 15910 * 15911 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. 15912 * @param userId ID of the user to be provisioned. 15913 * @param provisioningAction action indicating type of provisioning, should be one of 15914 * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or 15915 * {@link #ACTION_PROVISION_MANAGED_USER}. 15916 * 15917 * @hide 15918 */ 15919 @TestApi getDisallowedSystemApps(@onNull ComponentName admin, @UserIdInt int userId, @NonNull String provisioningAction)15920 public @NonNull Set<String> getDisallowedSystemApps(@NonNull ComponentName admin, 15921 @UserIdInt int userId, @NonNull String provisioningAction) { 15922 try { 15923 return new ArraySet<>( 15924 mService.getDisallowedSystemApps(admin, userId, provisioningAction)); 15925 } catch (RemoteException re) { 15926 throw re.rethrowFromSystemServer(); 15927 } 15928 } 15929 15930 /** 15931 * Changes the current administrator to another one. All policies from the current 15932 * administrator are migrated to the new administrator. The whole operation is atomic - 15933 * the transfer is either complete or not done at all. 15934 * 15935 * <p>Depending on the current administrator (device owner, profile owner), you have the 15936 * following expected behaviour: 15937 * <ul> 15938 * <li>A device owner can only be transferred to a new device owner</li> 15939 * <li>A profile owner can only be transferred to a new profile owner</li> 15940 * </ul> 15941 * 15942 * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data 15943 * will be received in the 15944 * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)} 15945 * callback of the new administrator. 15946 * 15947 * <p>The transfer has failed if the original administrator is still the corresponding owner 15948 * after calling this method. 15949 * 15950 * <p>The incoming target administrator must have the 15951 * <code><support-transfer-ownership /></code> tag inside the 15952 * <code><device-admin></device-admin></code> tags in the xml file referenced by 15953 * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an 15954 * {@link IllegalArgumentException} will be thrown. 15955 * 15956 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 15957 * @param target which {@link DeviceAdminReceiver} we want the new administrator to be. 15958 * @param bundle data to be sent to the new administrator. 15959 * @throws SecurityException if {@code admin} is not a device owner nor a profile owner. 15960 * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they 15961 * are components in the same package or {@code target} is not an active admin. 15962 */ transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)15963 public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target, 15964 @Nullable PersistableBundle bundle) { 15965 throwIfParentInstance("transferOwnership"); 15966 try { 15967 mService.transferOwnership(admin, target, bundle); 15968 } catch (RemoteException re) { 15969 throw re.rethrowFromSystemServer(); 15970 } 15971 } 15972 15973 /** 15974 * Called by a device owner to specify the user session start message. This may be displayed 15975 * during a user switch. 15976 * <p> 15977 * The message should be limited to a short statement or it may be truncated. 15978 * <p> 15979 * If the message needs to be localized, it is the responsibility of the 15980 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast 15981 * and set a new version of this message accordingly. 15982 * 15983 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 15984 * @param startUserSessionMessage message for starting user session, or {@code null} to use 15985 * system default message. 15986 * @throws SecurityException if {@code admin} is not a device owner. 15987 */ setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)15988 public void setStartUserSessionMessage( 15989 @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) { 15990 throwIfParentInstance("setStartUserSessionMessage"); 15991 try { 15992 mService.setStartUserSessionMessage(admin, startUserSessionMessage); 15993 } catch (RemoteException re) { 15994 throw re.rethrowFromSystemServer(); 15995 } 15996 } 15997 15998 /** 15999 * Called by a device owner to specify the user session end message. This may be displayed 16000 * during a user switch. 16001 * <p> 16002 * The message should be limited to a short statement or it may be truncated. 16003 * <p> 16004 * If the message needs to be localized, it is the responsibility of the 16005 * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast 16006 * and set a new version of this message accordingly. 16007 * 16008 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 16009 * @param endUserSessionMessage message for ending user session, or {@code null} to use system 16010 * default message. 16011 * @throws SecurityException if {@code admin} is not a device owner. 16012 */ setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)16013 public void setEndUserSessionMessage( 16014 @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) { 16015 throwIfParentInstance("setEndUserSessionMessage"); 16016 try { 16017 mService.setEndUserSessionMessage(admin, endUserSessionMessage); 16018 } catch (RemoteException re) { 16019 throw re.rethrowFromSystemServer(); 16020 } 16021 } 16022 16023 /** 16024 * Returns the user session start message. 16025 * 16026 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 16027 * @throws SecurityException if {@code admin} is not a device owner. 16028 */ getStartUserSessionMessage(@onNull ComponentName admin)16029 public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) { 16030 throwIfParentInstance("getStartUserSessionMessage"); 16031 try { 16032 return mService.getStartUserSessionMessage(admin); 16033 } catch (RemoteException re) { 16034 throw re.rethrowFromSystemServer(); 16035 } 16036 } 16037 16038 /** 16039 * Returns the user session end message. 16040 * 16041 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 16042 * @throws SecurityException if {@code admin} is not a device owner. 16043 */ getEndUserSessionMessage(@onNull ComponentName admin)16044 public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) { 16045 throwIfParentInstance("getEndUserSessionMessage"); 16046 try { 16047 return mService.getEndUserSessionMessage(admin); 16048 } catch (RemoteException re) { 16049 throw re.rethrowFromSystemServer(); 16050 } 16051 } 16052 16053 /** 16054 * Called by device owner or managed profile owner to add an override APN. 16055 * 16056 * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing 16057 * override APN. Update the existing conflicted APN with 16058 * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry. 16059 * <p>Two override APNs are considered to conflict when all the following APIs return 16060 * the same values on both override APNs: 16061 * <ul> 16062 * <li>{@link ApnSetting#getOperatorNumeric()}</li> 16063 * <li>{@link ApnSetting#getApnName()}</li> 16064 * <li>{@link ApnSetting#getProxyAddressAsString()}</li> 16065 * <li>{@link ApnSetting#getProxyPort()}</li> 16066 * <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li> 16067 * <li>{@link ApnSetting#getMmsProxyPort()}</li> 16068 * <li>{@link ApnSetting#getMmsc()}</li> 16069 * <li>{@link ApnSetting#isEnabled()}</li> 16070 * <li>{@link ApnSetting#getMvnoType()}</li> 16071 * <li>{@link ApnSetting#getProtocol()}</li> 16072 * <li>{@link ApnSetting#getRoamingProtocol()}</li> 16073 * </ul> 16074 * 16075 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 16076 * Only device owners can add APNs. 16077 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 16078 * Both device owners and managed profile owners can add enterprise APNs 16079 * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can add other type of APNs. 16080 * Enterprise APNs are specific to the managed profile and do not override any user-configured 16081 * VPNs. They are prerequisites for enabling preferential network service on the managed 16082 * profile on 4G networks ({@link #setPreferentialNetworkServiceConfigs}). 16083 * 16084 * @param admin which {@link DeviceAdminReceiver} this request is associated with 16085 * @param apnSetting the override APN to insert 16086 * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into 16087 * the database. 16088 * @throws SecurityException If request is for enterprise APN {@code admin} is either device 16089 * owner or profile owner and in all other types of APN if {@code admin} is not a device owner. 16090 * 16091 * @see #setOverrideApnsEnabled(ComponentName, boolean) 16092 */ addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)16093 public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) { 16094 throwIfParentInstance("addOverrideApn"); 16095 if (mService != null) { 16096 try { 16097 return mService.addOverrideApn(admin, apnSetting); 16098 } catch (RemoteException e) { 16099 throw e.rethrowFromSystemServer(); 16100 } 16101 } 16102 return -1; 16103 } 16104 16105 /** 16106 * Called by device owner or managed profile owner to update an override APN. 16107 * 16108 * <p>This method may returns {@code false} if there is no override APN with the given 16109 * {@code apnId}. 16110 * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an 16111 * existing override APN. Update the existing conflicted APN instead. 16112 * <p>See {@link #addOverrideApn} for the definition of conflict. 16113 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 16114 * Only device owners can update APNs. 16115 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 16116 * Both device owners and managed profile owners can update enterprise APNs 16117 * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can update other type of APNs. 16118 * 16119 * @param admin which {@link DeviceAdminReceiver} this request is associated with 16120 * @param apnId the {@code id} of the override APN to update 16121 * @param apnSetting the override APN to update 16122 * @return {@code true} if the required override APN is successfully updated, 16123 * {@code false} otherwise. 16124 * @throws SecurityException If request is for enterprise APN {@code admin} is either device 16125 * owner or profile owner and in all other types of APN if {@code admin} is not a device owner. 16126 * 16127 * @see #setOverrideApnsEnabled(ComponentName, boolean) 16128 */ updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)16129 public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId, 16130 @NonNull ApnSetting apnSetting) { 16131 throwIfParentInstance("updateOverrideApn"); 16132 if (mService != null) { 16133 try { 16134 return mService.updateOverrideApn(admin, apnId, apnSetting); 16135 } catch (RemoteException e) { 16136 throw e.rethrowFromSystemServer(); 16137 } 16138 } 16139 return false; 16140 } 16141 16142 /** 16143 * Called by device owner or managed profile owner to remove an override APN. 16144 * 16145 * <p>This method may returns {@code false} if there is no override APN with the given 16146 * {@code apnId}. 16147 * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 16148 * Only device owners can remove APNs. 16149 * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}: 16150 * Both device owners and managed profile owners can remove enterprise APNs 16151 * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can remove other type of APNs. 16152 * 16153 * @param admin which {@link DeviceAdminReceiver} this request is associated with 16154 * @param apnId the {@code id} of the override APN to remove 16155 * @return {@code true} if the required override APN is successfully removed, {@code false} 16156 * otherwise. 16157 * @throws SecurityException If request is for enterprise APN {@code admin} is either device 16158 * owner or profile owner and in all other types of APN if {@code admin} is not a device owner. 16159 * 16160 * @see #setOverrideApnsEnabled(ComponentName, boolean) 16161 */ removeOverrideApn(@onNull ComponentName admin, int apnId)16162 public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) { 16163 throwIfParentInstance("removeOverrideApn"); 16164 if (mService != null) { 16165 try { 16166 return mService.removeOverrideApn(admin, apnId); 16167 } catch (RemoteException e) { 16168 throw e.rethrowFromSystemServer(); 16169 } 16170 } 16171 return false; 16172 } 16173 16174 /** 16175 * Called by device owner or managed profile owner to get all override APNs inserted by 16176 * device owner or managed profile owner previously using {@link #addOverrideApn}. 16177 * 16178 * @param admin which {@link DeviceAdminReceiver} this request is associated with 16179 * @return A list of override APNs inserted by device owner. 16180 * @throws SecurityException if {@code admin} is not a device owner. 16181 * 16182 * @see #setOverrideApnsEnabled(ComponentName, boolean) 16183 */ getOverrideApns(@onNull ComponentName admin)16184 public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) { 16185 throwIfParentInstance("getOverrideApns"); 16186 if (mService != null) { 16187 try { 16188 return mService.getOverrideApns(admin); 16189 } catch (RemoteException e) { 16190 throw e.rethrowFromSystemServer(); 16191 } 16192 } 16193 return Collections.emptyList(); 16194 } 16195 16196 /** 16197 * Called by device owner to set if override APNs should be enabled. 16198 * <p> Override APNs are separated from other APNs on the device, and can only be inserted or 16199 * modified by the device owner. When enabled, only override APNs are in use, any other APNs 16200 * are ignored. 16201 * <p>Note: Enterprise APNs added by managed profile owners do not need to be enabled by 16202 * this API. They are part of the preferential network service config and is controlled by 16203 * {@link #setPreferentialNetworkServiceConfigs}. 16204 * 16205 * @param admin which {@link DeviceAdminReceiver} this request is associated with 16206 * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise 16207 * @throws SecurityException if {@code admin} is not a device owner. 16208 */ setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)16209 public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) { 16210 throwIfParentInstance("setOverrideApnEnabled"); 16211 if (mService != null) { 16212 try { 16213 mService.setOverrideApnsEnabled(admin, enabled); 16214 } catch (RemoteException e) { 16215 throw e.rethrowFromSystemServer(); 16216 } 16217 } 16218 } 16219 16220 /** 16221 * Called by device owner to check if override APNs are currently enabled. 16222 * 16223 * @param admin which {@link DeviceAdminReceiver} this request is associated with 16224 * @return {@code true} if override APNs are currently enabled, {@code false} otherwise. 16225 * @throws SecurityException if {@code admin} is not a device owner. 16226 * 16227 * @see #setOverrideApnsEnabled(ComponentName, boolean) 16228 */ isOverrideApnEnabled(@onNull ComponentName admin)16229 public boolean isOverrideApnEnabled(@NonNull ComponentName admin) { 16230 throwIfParentInstance("isOverrideApnEnabled"); 16231 if (mService != null) { 16232 try { 16233 return mService.isOverrideApnEnabled(admin); 16234 } catch (RemoteException e) { 16235 throw e.rethrowFromSystemServer(); 16236 } 16237 } 16238 return false; 16239 } 16240 16241 /** 16242 * Returns the data passed from the current administrator to the new administrator during an 16243 * ownership transfer. This is the same {@code bundle} passed in 16244 * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is 16245 * persisted until the profile owner or device owner is removed. 16246 * 16247 * <p>This is the same <code>bundle</code> received in the 16248 * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}. 16249 * Use this method to retrieve it after the transfer as long as the new administrator is the 16250 * active device or profile owner. 16251 * 16252 * <p>Returns <code>null</code> if no ownership transfer was started for the calling user. 16253 * 16254 * @see #transferOwnership 16255 * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle) 16256 * @throws SecurityException if the caller is not a device or profile owner. 16257 */ 16258 @Nullable getTransferOwnershipBundle()16259 public PersistableBundle getTransferOwnershipBundle() { 16260 throwIfParentInstance("getTransferOwnershipBundle"); 16261 try { 16262 return mService.getTransferOwnershipBundle(); 16263 } catch (RemoteException re) { 16264 throw re.rethrowFromSystemServer(); 16265 } 16266 } 16267 16268 /** 16269 * Sets the global Private DNS mode to opportunistic. 16270 * May only be called by the device owner. 16271 * 16272 * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied 16273 * resolver prior to attempting name resolution in cleartext. 16274 * 16275 * <p>Note: The device owner won't be able to set the global private DNS mode if there are 16276 * unaffiliated secondary users or profiles on the device. It's recommended that affiliation 16277 * ids are set for new users as soon as possible after provisioning via 16278 * {@link #setAffiliationIds}. 16279 * 16280 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 16281 * 16282 * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or 16283 * {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set. 16284 * 16285 * @throws SecurityException if the caller is not the device owner. 16286 */ setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)16287 public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic( 16288 @NonNull ComponentName admin) { 16289 throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic"); 16290 16291 if (mService == null) { 16292 return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING; 16293 } 16294 16295 try { 16296 return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null); 16297 } catch (RemoteException re) { 16298 throw re.rethrowFromSystemServer(); 16299 } 16300 } 16301 16302 /** 16303 * Sets the global Private DNS host to be used. 16304 * May only be called by the device owner. 16305 * 16306 * <p>Note that the method is blocking as it will perform a connectivity check to the resolver, 16307 * to ensure it is valid. Because of that, the method should not be called on any thread that 16308 * relates to user interaction, such as the UI thread. 16309 * 16310 * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver 16311 * must be reachable both from within and outside the VPN. Otherwise, the device may lose 16312 * the ability to resolve hostnames as system traffic to the resolver may not go through the 16313 * VPN. 16314 * 16315 * <p>Note: The device owner won't be able to set the global private DNS mode if there are 16316 * unaffiliated secondary users or profiles on the device. It's recommended that affiliation 16317 * ids are set for new users as soon as possible after provisioning via 16318 * {@link #setAffiliationIds}. 16319 * 16320 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 16321 * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858). 16322 * 16323 * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, 16324 * {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or 16325 * {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not 16326 * implement RFC7858. 16327 * 16328 * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname. 16329 * 16330 * @throws SecurityException if the caller is not the device owner. 16331 */ setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)16332 @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost( 16333 @NonNull ComponentName admin, @NonNull String privateDnsHost) { 16334 throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost"); 16335 Objects.requireNonNull(privateDnsHost, "dns resolver is null"); 16336 16337 if (mService == null) { 16338 return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING; 16339 } 16340 16341 if (NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) { 16342 if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) { 16343 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING; 16344 } 16345 } 16346 16347 try { 16348 return mService.setGlobalPrivateDns( 16349 admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost); 16350 } catch (RemoteException re) { 16351 throw re.rethrowFromSystemServer(); 16352 } 16353 } 16354 16355 /** 16356 * Called by device owner or profile owner of an organization-owned managed profile to install 16357 * a system update from the given file. The device will be 16358 * rebooted in order to finish installing the update. Note that if the device is rebooted, this 16359 * doesn't necessarily mean that the update has been applied successfully. The caller should 16360 * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link 16361 * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot, 16362 * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have 16363 * sufficient battery level, the installation will fail with error {@link 16364 * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}. 16365 * 16366 * @param admin The {@link DeviceAdminReceiver} that this request is associated with. Null if 16367 * the caller is not a device admin 16368 * @param updateFilePath A Uri of the file that contains the update. The file should be 16369 * readable by the calling app. 16370 * @param executor The executor through which the callback should be invoked. 16371 * @param callback A callback object that will inform the caller when installing an update 16372 * fails. 16373 */ 16374 @RequiresPermission(value = MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, conditional = true) installSystemUpdate( @ullable ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)16375 public void installSystemUpdate( 16376 @Nullable ComponentName admin, @NonNull Uri updateFilePath, 16377 @NonNull @CallbackExecutor Executor executor, 16378 @NonNull InstallSystemUpdateCallback callback) { 16379 throwIfParentInstance("installUpdate"); 16380 if (mService == null) { 16381 return; 16382 } 16383 try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver() 16384 .openFileDescriptor(updateFilePath, "r")) { 16385 mService.installUpdateFromFile( 16386 admin, mContext.getPackageName(), fileDescriptor, 16387 new StartInstallingUpdateCallback.Stub() { 16388 @Override 16389 public void onStartInstallingUpdateError( 16390 int errorCode, String errorMessage) { 16391 executeCallback(errorCode, errorMessage, executor, callback); 16392 } 16393 }); 16394 } catch (RemoteException e) { 16395 throw e.rethrowFromSystemServer(); 16396 } catch (FileNotFoundException e) { 16397 Log.w(TAG, e); 16398 executeCallback( 16399 InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND, 16400 Log.getStackTraceString(e), 16401 executor, callback); 16402 } catch (IOException e) { 16403 Log.w(TAG, e); 16404 executeCallback( 16405 InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e), 16406 executor, callback); 16407 } 16408 } 16409 executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)16410 private void executeCallback(int errorCode, String errorMessage, 16411 @NonNull @CallbackExecutor Executor executor, 16412 @NonNull InstallSystemUpdateCallback callback) { 16413 executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage)); 16414 } 16415 16416 /** 16417 * Returns the system-wide Private DNS mode. 16418 * 16419 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 16420 * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC}, 16421 * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}. 16422 * @throws SecurityException if the caller is not the device owner. 16423 */ getGlobalPrivateDnsMode(@onNull ComponentName admin)16424 public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) { 16425 throwIfParentInstance("setGlobalPrivateDns"); 16426 if (mService == null) { 16427 return PRIVATE_DNS_MODE_UNKNOWN; 16428 } 16429 16430 try { 16431 return mService.getGlobalPrivateDnsMode(admin); 16432 } catch (RemoteException re) { 16433 throw re.rethrowFromSystemServer(); 16434 } 16435 } 16436 16437 /** 16438 * Returns the system-wide Private DNS host. 16439 * 16440 * @param admin which {@link DeviceAdminReceiver} this request is associated with. 16441 * @return The hostname used for Private DNS queries, null if none is set. 16442 * @throws SecurityException if the caller is not the device owner. 16443 */ getGlobalPrivateDnsHost(@onNull ComponentName admin)16444 public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) { 16445 throwIfParentInstance("setGlobalPrivateDns"); 16446 if (mService == null) { 16447 return null; 16448 } 16449 16450 try { 16451 return mService.getGlobalPrivateDnsHost(admin); 16452 } catch (RemoteException re) { 16453 throw re.rethrowFromSystemServer(); 16454 } 16455 } 16456 16457 /** 16458 * Deprecated. Use {@code markProfileOwnerOnOrganizationOwnedDevice} instead. 16459 * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#Q} or 16460 * below, will behave the same as {@link #setProfileOwnerOnOrganizationOwnedDevice}. 16461 * 16462 * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#R} 16463 * or above, will throw an UnsupportedOperationException when called. 16464 * 16465 * @deprecated Use {@link #setProfileOwnerOnOrganizationOwnedDevice} instead. 16466 * 16467 * @hide 16468 */ 16469 @Deprecated 16470 @SystemApi 16471 @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS, 16472 conditional = true) setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)16473 public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) { 16474 ApplicationInfo ai = mContext.getApplicationInfo(); 16475 if (ai.targetSdkVersion > Build.VERSION_CODES.Q) { 16476 throw new UnsupportedOperationException( 16477 "This method is deprecated. use markProfileOwnerOnOrganizationOwnedDevice" 16478 + " instead."); 16479 } else { 16480 setProfileOwnerOnOrganizationOwnedDevice(who, true); 16481 } 16482 } 16483 16484 /** 16485 * Sets whether the profile owner of the given user as managing an organization-owned device. 16486 * Managing an organization-owned device will give it access to device identifiers (such as 16487 * serial number, IMEI and MEID) as well as other privileges. 16488 * 16489 * @hide 16490 */ 16491 @TestApi 16492 @RequiresPermission(anyOf = { 16493 android.Manifest.permission.MARK_DEVICE_ORGANIZATION_OWNED, 16494 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS 16495 }, conditional = true) setProfileOwnerOnOrganizationOwnedDevice(@onNull ComponentName who, boolean isProfileOwnerOnOrganizationOwnedDevice)16496 public void setProfileOwnerOnOrganizationOwnedDevice(@NonNull ComponentName who, 16497 boolean isProfileOwnerOnOrganizationOwnedDevice) { 16498 if (mService == null) { 16499 return; 16500 } 16501 try { 16502 mService.setProfileOwnerOnOrganizationOwnedDevice(who, myUserId(), 16503 isProfileOwnerOnOrganizationOwnedDevice); 16504 } catch (RemoteException re) { 16505 throw re.rethrowFromSystemServer(); 16506 } 16507 } 16508 16509 /** 16510 * Allows a set of packages to access cross-profile calendar APIs. 16511 * 16512 * <p>Called by a profile owner of a managed profile. 16513 * 16514 * <p>Calling with a {@code null} value for the set disables the restriction so that all 16515 * packages are allowed to access cross-profile calendar APIs. Calling with an empty set 16516 * disallows all packages from accessing cross-profile calendar APIs. If this method isn't 16517 * called, no package is allowed to access cross-profile calendar APIs by default. 16518 * 16519 * @param admin which {@link DeviceAdminReceiver} this request is associated with 16520 * @param packageNames set of packages to be allowlisted 16521 * @throws SecurityException if {@code admin} is not a profile owner 16522 * 16523 * @see #getCrossProfileCalendarPackages(ComponentName) 16524 * @deprecated Use {@link #setCrossProfilePackages(ComponentName, Set)}. 16525 */ 16526 @Deprecated setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)16527 public void setCrossProfileCalendarPackages(@NonNull ComponentName admin, 16528 @Nullable Set<String> packageNames) { 16529 throwIfParentInstance("setCrossProfileCalendarPackages"); 16530 if (mService != null) { 16531 try { 16532 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null 16533 : new ArrayList<>(packageNames)); 16534 } catch (RemoteException e) { 16535 throw e.rethrowFromSystemServer(); 16536 } 16537 } 16538 } 16539 16540 /** 16541 * Gets a set of package names that are allowed to access cross-profile calendar APIs. 16542 * 16543 * <p>Called by a profile owner of a managed profile. 16544 * 16545 * @param admin which {@link DeviceAdminReceiver} this request is associated with 16546 * @return the set of names of packages that were previously allowed via 16547 * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an 16548 * empty set if none have been allowed 16549 * @throws SecurityException if {@code admin} is not a profile owner 16550 * 16551 * @see #setCrossProfileCalendarPackages(ComponentName, Set) 16552 * @deprecated Use {@link #setCrossProfilePackages(ComponentName, Set)}. 16553 */ 16554 @Deprecated getCrossProfileCalendarPackages(@onNull ComponentName admin)16555 public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) { 16556 throwIfParentInstance("getCrossProfileCalendarPackages"); 16557 if (mService != null) { 16558 try { 16559 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin); 16560 return packageNames == null ? null : new ArraySet<>(packageNames); 16561 } catch (RemoteException e) { 16562 throw e.rethrowFromSystemServer(); 16563 } 16564 } 16565 return Collections.emptySet(); 16566 } 16567 16568 /** 16569 * Returns if a package is allowed to access cross-profile calendar APIs. 16570 * 16571 * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by 16572 * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and 16573 * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED} 16574 * is turned on in the managed profile. 16575 * 16576 * <p>To query for a specific user, use 16577 * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for 16578 * that user, and get a {@link DevicePolicyManager} from this context. 16579 * 16580 * @param packageName the name of the package 16581 * @return {@code true} if the package is allowed to access cross-profile calendar APIs, 16582 * {@code false} otherwise 16583 * 16584 * @see #setCrossProfileCalendarPackages(ComponentName, Set) 16585 * @see #getCrossProfileCalendarPackages(ComponentName) 16586 * @hide 16587 */ 16588 @RequiresPermission(anyOf = { 16589 INTERACT_ACROSS_USERS_FULL, 16590 permission.INTERACT_ACROSS_USERS 16591 }, conditional = true) isPackageAllowedToAccessCalendar(@onNull String packageName)16592 public boolean isPackageAllowedToAccessCalendar(@NonNull String packageName) { 16593 throwIfParentInstance("isPackageAllowedToAccessCalendar"); 16594 if (mService != null) { 16595 try { 16596 return mService.isPackageAllowedToAccessCalendarForUser(packageName, 16597 myUserId()); 16598 } catch (RemoteException e) { 16599 throw e.rethrowFromSystemServer(); 16600 } 16601 } 16602 return false; 16603 } 16604 16605 /** 16606 * Gets a set of package names that are allowed to access cross-profile calendar APIs. 16607 * 16608 * <p>To query for a specific user, use 16609 * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for 16610 * that user, and get a {@link DevicePolicyManager} from this context. 16611 * 16612 * @return the set of names of packages that were previously allowed via 16613 * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an 16614 * empty set if none have been allowed 16615 * 16616 * @see #setCrossProfileCalendarPackages(ComponentName, Set) 16617 * @see #getCrossProfileCalendarPackages(ComponentName) 16618 * @hide 16619 */ 16620 @RequiresPermission(anyOf = { 16621 INTERACT_ACROSS_USERS_FULL, 16622 permission.INTERACT_ACROSS_USERS 16623 }) getCrossProfileCalendarPackages()16624 public @Nullable Set<String> getCrossProfileCalendarPackages() { 16625 throwIfParentInstance("getCrossProfileCalendarPackages"); 16626 if (mService != null) { 16627 try { 16628 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser( 16629 myUserId()); 16630 return packageNames == null ? null : new ArraySet<>(packageNames); 16631 } catch (RemoteException e) { 16632 throw e.rethrowFromSystemServer(); 16633 } 16634 } 16635 return Collections.emptySet(); 16636 } 16637 16638 /** 16639 * Sets the set of admin-allowlisted package names that are allowed to request user consent for 16640 * cross-profile communication. 16641 * 16642 * <p>Assumes that the caller is a profile owner and is the given {@code admin}. 16643 * 16644 * <p>Previous calls are overridden by each subsequent call to this method. 16645 * 16646 * <p>Note that other apps may be able to request user consent for cross-profile communication 16647 * if they have been explicitly allowlisted by the OEM. 16648 * 16649 * <p>When previously-set cross-profile packages are missing from {@code packageNames}, the 16650 * app-op for {@code INTERACT_ACROSS_PROFILES} will be reset for those packages. This will not 16651 * occur for packages that are allowlisted by the OEM. 16652 * 16653 * @param admin the {@link DeviceAdminReceiver} this request is associated with 16654 * @param packageNames the new cross-profile package names 16655 */ setCrossProfilePackages( @onNull ComponentName admin, @NonNull Set<String> packageNames)16656 public void setCrossProfilePackages( 16657 @NonNull ComponentName admin, @NonNull Set<String> packageNames) { 16658 throwIfParentInstance("setCrossProfilePackages"); 16659 if (mService != null) { 16660 try { 16661 mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames)); 16662 } catch (RemoteException e) { 16663 throw e.rethrowFromSystemServer(); 16664 } 16665 } 16666 } 16667 16668 /** 16669 * Returns the set of package names that the admin has previously set as allowed to request user 16670 * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName, 16671 * Set)}. 16672 * 16673 * <p>Assumes that the caller is a profile owner and is the given {@code admin}. 16674 * 16675 * <p>Note that other apps not included in the returned set may be able to request user consent 16676 * for cross-profile communication if they have been explicitly allowlisted by the OEM. 16677 * 16678 * @param admin the {@link DeviceAdminReceiver} this request is associated with 16679 * @return the set of package names the admin has previously set as allowed to request user 16680 * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName, 16681 * Set)} 16682 */ getCrossProfilePackages(@onNull ComponentName admin)16683 public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) { 16684 throwIfParentInstance("getCrossProfilePackages"); 16685 if (mService != null) { 16686 try { 16687 return new ArraySet<>(mService.getCrossProfilePackages(admin)); 16688 } catch (RemoteException e) { 16689 throw e.rethrowFromSystemServer(); 16690 } 16691 } 16692 return Collections.emptySet(); 16693 } 16694 16695 /** 16696 * Returns the combined set of the following: 16697 * <ul> 16698 * <li>The package names that the admin has previously set as allowed to request user consent 16699 * for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName, 16700 * Set)}.</li> 16701 * <li>The default package names set by the OEM that are allowed to request user consent for 16702 * cross-profile communication without being explicitly enabled by the admin, via {@link 16703 * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array 16704 * #vendor_cross_profile_apps}.</li> 16705 * </ul> 16706 * 16707 * @return the combined set of allowlisted package names set via 16708 * {@link #setCrossProfilePackages(ComponentName, Set)}, {@link com.android.internal.R.array 16709 * #cross_profile_apps}, and {@link com.android.internal.R.array#vendor_cross_profile_apps}. 16710 * 16711 * @hide 16712 */ 16713 @RequiresPermission(anyOf = { 16714 INTERACT_ACROSS_USERS_FULL, 16715 permission.INTERACT_ACROSS_USERS, 16716 permission.INTERACT_ACROSS_PROFILES 16717 }) getAllCrossProfilePackages()16718 public @NonNull Set<String> getAllCrossProfilePackages() { 16719 throwIfParentInstance("getAllCrossProfilePackages"); 16720 if (mService != null) { 16721 try { 16722 return new ArraySet<>(mService.getAllCrossProfilePackages(mContext.getUserId())); 16723 } catch (RemoteException e) { 16724 throw e.rethrowFromSystemServer(); 16725 } 16726 } 16727 return Collections.emptySet(); 16728 } 16729 16730 /** 16731 * Returns the default package names set by the OEM that are allowed to communicate 16732 * cross-profile without being explicitly enabled by the admin, via {@link 16733 * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array 16734 * #vendor_cross_profile_apps}. 16735 * 16736 * @hide 16737 */ 16738 @TestApi getDefaultCrossProfilePackages()16739 public @NonNull Set<String> getDefaultCrossProfilePackages() { 16740 throwIfParentInstance("getDefaultCrossProfilePackages"); 16741 if (mService != null) { 16742 try { 16743 return new ArraySet<>(mService.getDefaultCrossProfilePackages()); 16744 } catch (RemoteException e) { 16745 throw e.rethrowFromSystemServer(); 16746 } 16747 } 16748 return Collections.emptySet(); 16749 } 16750 16751 /** 16752 * Returns whether the device is being used as a managed kiosk. These requirements are as 16753 * follows: 16754 * <ul> 16755 * <li>The device is in Lock Task (therefore there is also a Device Owner app on the 16756 * device)</li> 16757 * <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is 16758 * not enabled, so the system info in the status bar is not visible</li> 16759 * <li>The device does not have a secure lock screen (e.g. it has no lock screen or has 16760 * swipe-to-unlock)</li> 16761 * <li>The device is not in the middle of an ephemeral user session</li> 16762 * </ul> 16763 * 16764 * <p>Publicly-accessible dedicated devices don't have the same privacy model as 16765 * personally-used devices. In particular, user consent popups don't make sense as a barrier to 16766 * accessing persistent data on these devices since the user giving consent and the user whose 16767 * data is on the device are unlikely to be the same. These consent popups prevent the true 16768 * remote management of these devices. 16769 * 16770 * <p>This condition is not sufficient to cover APIs that would access data that only lives for 16771 * the duration of the user's session, since the user has an expectation of privacy in these 16772 * conditions that more closely resembles use of a personal device. In those cases, see {@link 16773 * #isUnattendedManagedKiosk()}. 16774 * 16775 * @hide 16776 */ 16777 @SystemApi 16778 @RequiresPermission(anyOf = { 16779 android.Manifest.permission.MANAGE_USERS, 16780 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS 16781 }) isManagedKiosk()16782 public boolean isManagedKiosk() { 16783 throwIfParentInstance("isManagedKiosk"); 16784 if (mService != null) { 16785 try { 16786 return mService.isManagedKiosk(); 16787 } catch (RemoteException e) { 16788 throw e.rethrowFromSystemServer(); 16789 } 16790 } 16791 return false; 16792 } 16793 16794 /** 16795 * Returns whether the device is being used as an unattended managed kiosk. These requirements 16796 * are as follows: 16797 * <ul> 16798 * <li>The device is being used as a managed kiosk, as defined at {@link 16799 * #isManagedKiosk()}</li> 16800 * <li>The device has not received user input for at least 30 minutes</li> 16801 * </ul> 16802 * 16803 * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also 16804 * ensures that the device hasn't been interacted with recently, making it an appropriate check 16805 * for privacy-sensitive APIs that wouldn't be appropriate during an active user session. 16806 * 16807 * @hide 16808 */ 16809 @SystemApi 16810 @RequiresPermission(anyOf = { 16811 android.Manifest.permission.MANAGE_USERS, 16812 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS 16813 }) isUnattendedManagedKiosk()16814 public boolean isUnattendedManagedKiosk() { 16815 throwIfParentInstance("isUnattendedManagedKiosk"); 16816 if (mService != null) { 16817 try { 16818 return mService.isUnattendedManagedKiosk(); 16819 } catch (RemoteException e) { 16820 throw e.rethrowFromSystemServer(); 16821 } 16822 } 16823 return false; 16824 } 16825 16826 /** 16827 * Starts an activity to view calendar events in the managed profile. 16828 * 16829 * @param eventId the id of the event to be viewed 16830 * @param start the start time of the event 16831 * @param end the end time of the event 16832 * @param allDay if the event is an all-day event 16833 * @param flags flags to be set for the intent 16834 * @return {@code true} if the activity is started successfully, {@code false} otherwise 16835 * 16836 * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long, 16837 * long, boolean, int) 16838 * 16839 * @hide 16840 */ startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)16841 public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end, 16842 boolean allDay, int flags) { 16843 throwIfParentInstance("startViewCalendarEventInManagedProfile"); 16844 if (mService != null) { 16845 try { 16846 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(), 16847 eventId, start, end, allDay, flags); 16848 } catch (RemoteException e) { 16849 throw e.rethrowFromSystemServer(); 16850 } 16851 } 16852 return false; 16853 } 16854 16855 /** 16856 * Service-specific error code used in {@link #setApplicationExemptions(String, Set)} and 16857 * {@link #getApplicationExemptions(String)}. 16858 * @hide 16859 */ 16860 public static final int ERROR_PACKAGE_NAME_NOT_FOUND = 1; 16861 16862 /** 16863 * Called by an application with the 16864 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS} permission, to 16865 * grant platform restriction exemptions to a given application. 16866 * 16867 * @param packageName The package name of the application to be exempt. 16868 * @param exemptions The set of exemptions to be applied. 16869 * @throws SecurityException If the caller does not have 16870 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS} 16871 * @throws NameNotFoundException If either the package is not installed or the package is not 16872 * visible to the caller. 16873 * @hide 16874 */ 16875 @SystemApi 16876 @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS) setApplicationExemptions(@onNull String packageName, @NonNull @ApplicationExemptionConstants Set<Integer> exemptions)16877 public void setApplicationExemptions(@NonNull String packageName, 16878 @NonNull @ApplicationExemptionConstants Set<Integer> exemptions) 16879 throws NameNotFoundException { 16880 throwIfParentInstance("setApplicationExemptions"); 16881 if (mService != null) { 16882 try { 16883 mService.setApplicationExemptions(mContext.getPackageName(), packageName, 16884 ArrayUtils.convertToIntArray(new ArraySet<>(exemptions))); 16885 } catch (ServiceSpecificException e) { 16886 switch (e.errorCode) { 16887 case ERROR_PACKAGE_NAME_NOT_FOUND: 16888 throw new NameNotFoundException(e.getMessage()); 16889 default: 16890 throw new RuntimeException( 16891 "Unknown error setting application exemptions: " + e.errorCode, e); 16892 } 16893 } catch (RemoteException e) { 16894 throw e.rethrowFromSystemServer(); 16895 } 16896 } 16897 } 16898 16899 /** 16900 * Returns all the platform restriction exemptions currently applied to an application. Called 16901 * by an application with the 16902 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS} permission. 16903 * 16904 * @param packageName The package name to check. 16905 * @return A set of platform restrictions an application is exempt from. 16906 * @throws SecurityException If the caller does not have 16907 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS} 16908 * @throws NameNotFoundException If either the package is not installed or the package is not 16909 * visible to the caller. 16910 * @hide 16911 */ 16912 @NonNull 16913 @SystemApi 16914 @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS) getApplicationExemptions(@onNull String packageName)16915 public Set<Integer> getApplicationExemptions(@NonNull String packageName) 16916 throws NameNotFoundException { 16917 throwIfParentInstance("getApplicationExemptions"); 16918 if (mService == null) { 16919 return Collections.emptySet(); 16920 } 16921 try { 16922 return intArrayToSet(mService.getApplicationExemptions(packageName)); 16923 } catch (ServiceSpecificException e) { 16924 switch (e.errorCode) { 16925 case ERROR_PACKAGE_NAME_NOT_FOUND: 16926 throw new NameNotFoundException(e.getMessage()); 16927 default: 16928 throw new RuntimeException( 16929 "Unknown error getting application exemptions: " + e.errorCode, e); 16930 } 16931 } catch (RemoteException e) { 16932 throw e.rethrowFromSystemServer(); 16933 } 16934 } 16935 intArrayToSet(int[] array)16936 private Set<Integer> intArrayToSet(int[] array) { 16937 Set<Integer> set = new ArraySet<>(); 16938 for (int item : array) { 16939 set.add(item); 16940 } 16941 return set; 16942 } 16943 16944 /** 16945 * Called by a device owner or a profile owner or holder of the permission 16946 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL} to disable user 16947 * control over apps. User will not be able to clear app data or force-stop packages. When 16948 * called by a device owner, applies to all users on the device. Packages with user control 16949 * disabled are exempted from App Standby Buckets. 16950 * <p> 16951 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the user control disabled 16952 * packages policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 16953 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 16954 * successfully set or not. This callback will contain: 16955 * <ul> 16956 * <li> The policy identifier 16957 * {@link DevicePolicyIdentifiers#USER_CONTROL_DISABLED_PACKAGES_POLICY} 16958 * <li> The {@link TargetUser} that this policy relates to 16959 * <li> The {@link PolicyUpdateResult}, which will be 16960 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 16961 * reason the policy failed to be set 16962 * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 16963 * </ul> 16964 * If there has been a change to the policy, 16965 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 16966 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 16967 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 16968 * will contain the reason why the policy changed. 16969 * 16970 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 16971 * caller is not a device admin. 16972 * @param packages The package names for the apps. 16973 * @throws SecurityException if {@code admin} is not a device owner or a profile owner or 16974 * holder of the permission 16975 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}. 16976 */ 16977 @RequiresPermission(value = MANAGE_DEVICE_POLICY_APPS_CONTROL, conditional = true) 16978 @SupportsCoexistence setUserControlDisabledPackages(@ullable ComponentName admin, @NonNull List<String> packages)16979 public void setUserControlDisabledPackages(@Nullable ComponentName admin, 16980 @NonNull List<String> packages) { 16981 throwIfParentInstance("setUserControlDisabledPackages"); 16982 if (mService != null) { 16983 try { 16984 mService.setUserControlDisabledPackages(admin, mContext.getPackageName(), packages); 16985 } catch (RemoteException re) { 16986 throw re.rethrowFromSystemServer(); 16987 } 16988 } 16989 } 16990 16991 /** 16992 * Returns the list of packages over which user control is disabled by a device or profile 16993 * owner or holders of the permission 16994 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}. 16995 * <p> 16996 * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the 16997 * current resolved policy rather than the policy set by the calling admin. 16998 * 16999 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 17000 * caller is not a device admin. 17001 * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the 17002 * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}. 17003 */ 17004 @RequiresPermission(value = MANAGE_DEVICE_POLICY_APPS_CONTROL, conditional = true) 17005 @NonNull getUserControlDisabledPackages(@ullable ComponentName admin)17006 public List<String> getUserControlDisabledPackages(@Nullable ComponentName admin) { 17007 throwIfParentInstance("getUserControlDisabledPackages"); 17008 if (mService != null) { 17009 try { 17010 return mService.getUserControlDisabledPackages(admin, mContext.getPackageName()); 17011 } catch (RemoteException re) { 17012 throw re.rethrowFromSystemServer(); 17013 } 17014 } 17015 return Collections.emptyList(); 17016 } 17017 17018 /** 17019 * Called by device owner or profile owner of an organization-owned managed profile to toggle 17020 * Common Criteria mode for the device. When the device is in Common Criteria mode, 17021 * certain device functionalities are tuned to meet the higher 17022 * security level required by Common Criteria certification. For example: 17023 * <ul> 17024 * <li> Bluetooth long term key material is additionally integrity-protected with AES-GCM. </li> 17025 * <li> WiFi configuration store is additionally integrity-protected with AES-GCM. </li> 17026 * </ul> 17027 * Common Criteria mode is disabled by default. 17028 * 17029 * <p><em>Note:</em> if Common Critera mode is turned off after being enabled previously, 17030 * all existing WiFi configurations will be lost. 17031 * 17032 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 17033 * caller is not a device admin. 17034 * @param enabled whether Common Criteria mode should be enabled or not. 17035 */ 17036 @RequiresPermission(value = MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE, conditional = true) setCommonCriteriaModeEnabled(@ullable ComponentName admin, boolean enabled)17037 public void setCommonCriteriaModeEnabled(@Nullable ComponentName admin, boolean enabled) { 17038 throwIfParentInstance("setCommonCriteriaModeEnabled"); 17039 if (mService != null) { 17040 try { 17041 mService.setCommonCriteriaModeEnabled(admin, mContext.getPackageName(), enabled); 17042 } catch (RemoteException e) { 17043 throw e.rethrowFromSystemServer(); 17044 } 17045 } 17046 } 17047 17048 /** 17049 * Returns whether Common Criteria mode is currently enabled. Device owner and profile owner of 17050 * an organization-owned managed profile can query its own Common Criteria mode setting by 17051 * calling this method with its admin {@link ComponentName}. Any caller can obtain the 17052 * aggregated device-wide Common Criteria mode state by passing {@code null} as the 17053 * {@code admin} argument. 17054 * 17055 * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the 17056 * caller is not a device admin. 17057 * @return {@code true} if Common Criteria mode is enabled, {@code false} otherwise. 17058 */ isCommonCriteriaModeEnabled(@ullable ComponentName admin)17059 public boolean isCommonCriteriaModeEnabled(@Nullable ComponentName admin) { 17060 throwIfParentInstance("isCommonCriteriaModeEnabled"); 17061 if (mService != null) { 17062 try { 17063 return mService.isCommonCriteriaModeEnabled(admin); 17064 } catch (RemoteException e) { 17065 throw e.rethrowFromSystemServer(); 17066 } 17067 } 17068 return false; 17069 } 17070 17071 /** 17072 * Called by profile owner of an organization-owned managed profile to check whether 17073 * personal apps are suspended. 17074 * 17075 * @return a bitmask of reasons for personal apps suspension or 17076 * {@link #PERSONAL_APPS_NOT_SUSPENDED} if apps are not suspended. 17077 * @see #setPersonalAppsSuspended 17078 */ getPersonalAppsSuspendedReasons( @onNull ComponentName admin)17079 public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons( 17080 @NonNull ComponentName admin) { 17081 throwIfParentInstance("getPersonalAppsSuspendedReasons"); 17082 if (mService != null) { 17083 try { 17084 return mService.getPersonalAppsSuspendedReasons(admin); 17085 } catch (RemoteException re) { 17086 throw re.rethrowFromSystemServer(); 17087 } 17088 } 17089 return 0; 17090 } 17091 17092 /** 17093 * Called by a profile owner of an organization-owned managed profile to suspend personal 17094 * apps on the device. When personal apps are suspended the device can only be used for calls. 17095 * 17096 * @param admin Which {@link DeviceAdminReceiver} this request is associated with 17097 * @param suspended Whether personal apps should be suspended. 17098 * @throws IllegalStateException if the profile owner doesn't have an activity that handles 17099 * {@link #ACTION_CHECK_POLICY_COMPLIANCE} 17100 */ setPersonalAppsSuspended(@onNull ComponentName admin, boolean suspended)17101 public void setPersonalAppsSuspended(@NonNull ComponentName admin, boolean suspended) { 17102 throwIfParentInstance("setPersonalAppsSuspended"); 17103 if (mService != null) { 17104 try { 17105 mService.setPersonalAppsSuspended(admin, suspended); 17106 } catch (RemoteException re) { 17107 throw re.rethrowFromSystemServer(); 17108 } 17109 } 17110 } 17111 17112 /** 17113 * Called by a profile owner of an organization-owned managed profile to set maximum time 17114 * the profile is allowed to be turned off. If the profile is turned off for longer, personal 17115 * apps are suspended on the device. 17116 * 17117 * <p>When personal apps are suspended, an ongoing notification about that is shown to the user. 17118 * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE} 17119 * in the profile owner package. Profile owner implementation that uses personal apps suspension 17120 * must handle this intent. 17121 * 17122 * @param admin Which {@link DeviceAdminReceiver} this request is associated with 17123 * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if 17124 * not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a 17125 * smaller non-zero vaulue, 72 hours will be set instead. 17126 * @throws IllegalStateException if the profile owner doesn't have an activity that handles 17127 * {@link #ACTION_CHECK_POLICY_COMPLIANCE} 17128 * @see #setPersonalAppsSuspended 17129 */ setManagedProfileMaximumTimeOff(@onNull ComponentName admin, long timeoutMillis)17130 public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) { 17131 throwIfParentInstance("setManagedProfileMaximumTimeOff"); 17132 if (mService != null) { 17133 try { 17134 mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis); 17135 } catch (RemoteException re) { 17136 throw re.rethrowFromSystemServer(); 17137 } 17138 } 17139 } 17140 17141 /** 17142 * Called by a profile owner of an organization-owned managed profile to get maximum time 17143 * the profile is allowed to be turned off. 17144 * 17145 * @param admin Which {@link DeviceAdminReceiver} this request is associated with 17146 * @return Maximum time the profile is allowed to be off in milliseconds or 0 if not limited. 17147 * @see #setPersonalAppsSuspended 17148 */ getManagedProfileMaximumTimeOff(@onNull ComponentName admin)17149 public long getManagedProfileMaximumTimeOff(@NonNull ComponentName admin) { 17150 throwIfParentInstance("getManagedProfileMaximumTimeOff"); 17151 if (mService != null) { 17152 try { 17153 return mService.getManagedProfileMaximumTimeOff(admin); 17154 } catch (RemoteException re) { 17155 throw re.rethrowFromSystemServer(); 17156 } 17157 } 17158 return 0; 17159 } 17160 17161 /** 17162 * Called by a profile owner of an organization-owned managed profile to acknowledge that the 17163 * device is compliant and the user can turn the profile off if needed according to the maximum 17164 * time off policy. 17165 * 17166 * This method should be called when the device is deemed compliant after getting 17167 * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback in 17168 * case it is overridden. Before this method is called the user is still free to turn the 17169 * profile off, but the timer won't be reset, so personal apps will be suspended sooner. 17170 * 17171 * DPCs only need acknowledging device compliance if they override 17172 * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)}, otherwise 17173 * compliance is acknowledged automatically. 17174 * 17175 * @throws IllegalStateException if the user isn't unlocked 17176 * @see #isComplianceAcknowledgementRequired() 17177 * @see #setManagedProfileMaximumTimeOff(ComponentName, long) 17178 * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent) 17179 */ acknowledgeDeviceCompliant()17180 public void acknowledgeDeviceCompliant() { 17181 throwIfParentInstance("acknowledgeDeviceCompliant"); 17182 if (mService != null) { 17183 try { 17184 mService.acknowledgeDeviceCompliant(); 17185 } catch (RemoteException re) { 17186 throw re.rethrowFromSystemServer(); 17187 } 17188 } 17189 } 17190 17191 /** 17192 * Called by a profile owner of an organization-owned managed profile to query whether it needs 17193 * to acknowledge device compliance to allow the user to turn the profile off if needed 17194 * according to the maximum profile time off policy. 17195 * 17196 * Normally when acknowledgement is needed the DPC gets a 17197 * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback. 17198 * But if the callback was not delivered or handled for some reason, this method can be used to 17199 * verify if acknowledgement is needed. 17200 * 17201 * @throws IllegalStateException if the user isn't unlocked 17202 * @see #acknowledgeDeviceCompliant() 17203 * @see #setManagedProfileMaximumTimeOff(ComponentName, long) 17204 * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent) 17205 */ isComplianceAcknowledgementRequired()17206 public boolean isComplianceAcknowledgementRequired() { 17207 throwIfParentInstance("isComplianceAcknowledgementRequired"); 17208 if (mService != null) { 17209 try { 17210 return mService.isComplianceAcknowledgementRequired(); 17211 } catch (RemoteException re) { 17212 throw re.rethrowFromSystemServer(); 17213 } 17214 } 17215 return false; 17216 } 17217 17218 /** 17219 * Returns {@code true} when {@code userId} has a profile owner that is capable of resetting 17220 * password in RUNNING_LOCKED state. For that it should have at least one direct boot aware 17221 * component and have an active password reset token. Can only be called by the system. 17222 * @hide 17223 */ canProfileOwnerResetPasswordWhenLocked(int userId)17224 public boolean canProfileOwnerResetPasswordWhenLocked(int userId) { 17225 if (mService != null) { 17226 try { 17227 return mService.canProfileOwnerResetPasswordWhenLocked(userId); 17228 } catch (RemoteException re) { 17229 throw re.rethrowFromSystemServer(); 17230 } 17231 } 17232 return false; 17233 } 17234 17235 /** 17236 * Used by CTS to set the result of the next safety operation check. 17237 * 17238 * @hide 17239 */ 17240 @TestApi 17241 @RequiresPermission(MANAGE_DEVICE_ADMINS) setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)17242 public void setNextOperationSafety(@DevicePolicyOperation int operation, 17243 @OperationSafetyReason int reason) { 17244 if (mService != null) { 17245 try { 17246 mService.setNextOperationSafety(operation, reason); 17247 } catch (RemoteException re) { 17248 throw re.rethrowFromSystemServer(); 17249 } 17250 } 17251 } 17252 17253 /** 17254 * Returns an enrollment-specific identifier of this device, which is guaranteed to be the same 17255 * value for the same device, enrolled into the same organization by the same managing app. 17256 * This identifier is high-entropy, useful for uniquely identifying individual devices within 17257 * the same organisation. 17258 * It is available both in a work profile and on a fully-managed device. 17259 * The identifier would be consistent even if the work profile is removed and enrolled again 17260 * (to the same organization), or the device is factory reset and re-enrolled. 17261 * 17262 * Can only be called by the Profile Owner and Device Owner, and starting from Android 17263 * {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, holders of the permission 17264 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES}. 17265 * If {@link #setOrganizationId(String)} was not called, then the returned value will be an 17266 * empty string. 17267 * 17268 * <p>Note about access to device identifiers: a device owner, a profile owner of an 17269 * organization-owned device or the delegated certificate installer (holding the 17270 * {@link #DELEGATION_CERT_INSTALL} delegation) on such a device can still obtain hardware 17271 * identifiers by calling e.g. {@link android.os.Build#getSerial()}, in addition to using 17272 * this method. However, a profile owner on a personal (non organization-owned) device, or the 17273 * delegated certificate installer on such a device, cannot obtain hardware identifiers anymore 17274 * and must switch to using this method. 17275 * 17276 * @return A stable, enrollment-specific identifier. 17277 * @throws SecurityException if the caller is not a profile owner, device owner or holding the 17278 * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission 17279 */ 17280 @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true) 17281 @SuppressLint("RequiresPermission") getEnrollmentSpecificId()17282 @NonNull public String getEnrollmentSpecificId() { 17283 throwIfParentInstance("getEnrollmentSpecificId"); 17284 if (mService == null) { 17285 return ""; 17286 } 17287 17288 try { 17289 return mService.getEnrollmentSpecificId(mContext.getPackageName()); 17290 } catch (RemoteException re) { 17291 throw re.rethrowFromSystemServer(); 17292 } 17293 } 17294 17295 /** 17296 * Sets the Enterprise ID for the work profile or managed device. This is a requirement for 17297 * generating an enrollment-specific ID for the device, see {@link #getEnrollmentSpecificId()}. 17298 * 17299 * It is recommended that the Enterprise ID is at least 6 characters long, and no more than 17300 * 64 characters. 17301 * 17302 * @param enterpriseId An identifier of the organization this work profile or device is 17303 * enrolled into. 17304 */ setOrganizationId(@onNull String enterpriseId)17305 public void setOrganizationId(@NonNull String enterpriseId) { 17306 throwIfParentInstance("setOrganizationId"); 17307 setOrganizationIdForUser(mContext.getPackageName(), enterpriseId, myUserId()); 17308 } 17309 17310 /** 17311 * Sets the Enterprise ID for the work profile or managed device. This is a requirement for 17312 * generating an enrollment-specific ID for the device, see 17313 * {@link #getEnrollmentSpecificId()}. 17314 * 17315 * @hide 17316 */ setOrganizationIdForUser(@onNull String packageName, @NonNull String enterpriseId, @UserIdInt int userId)17317 public void setOrganizationIdForUser(@NonNull String packageName, 17318 @NonNull String enterpriseId, @UserIdInt int userId) { 17319 if (mService == null) { 17320 return; 17321 } 17322 try { 17323 mService.setOrganizationIdForUser(packageName, enterpriseId, userId); 17324 } catch (RemoteException re) { 17325 throw re.rethrowFromSystemServer(); 17326 } 17327 } 17328 17329 /** 17330 * Clears organization ID set by the DPC and resets the precomputed enrollment specific ID. 17331 * @hide 17332 */ 17333 @TestApi 17334 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) clearOrganizationId()17335 public void clearOrganizationId() { 17336 if (mService == null) { 17337 return; 17338 } 17339 try { 17340 mService.clearOrganizationIdForUser(myUserId()); 17341 } catch (RemoteException re) { 17342 throw re.rethrowFromSystemServer(); 17343 } 17344 } 17345 17346 /** 17347 * Creates and provisions a managed profile and sets the 17348 * {@link ManagedProfileProvisioningParams#getProfileAdminComponentName()} as the profile 17349 * owner. 17350 * 17351 * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK} 17352 * before calling this method. 17353 * 17354 * @param provisioningParams Params required to provision a managed profile, 17355 * see {@link ManagedProfileProvisioningParams}. 17356 * @return The {@link UserHandle} of the created profile or {@code null} if the service is 17357 * not available. 17358 * @throws SecurityException if the caller does not hold 17359 * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}. 17360 * @throws ProvisioningException if an error occurred during provisioning. 17361 * @deprecated Use {@link #createManagedProfile} and {@link #finalizeCreateManagedProfile} 17362 * @hide 17363 */ 17364 @Nullable 17365 @SystemApi 17366 @Deprecated 17367 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) 17368 @FlaggedApi(FLAG_SPLIT_CREATE_MANAGED_PROFILE_ENABLED) createAndProvisionManagedProfile( @onNull ManagedProfileProvisioningParams provisioningParams)17369 public UserHandle createAndProvisionManagedProfile( 17370 @NonNull ManagedProfileProvisioningParams provisioningParams) 17371 throws ProvisioningException { 17372 if (mService == null) { 17373 return null; 17374 } 17375 try { 17376 return mService.createAndProvisionManagedProfile( 17377 provisioningParams, mContext.getPackageName()); 17378 } catch (ServiceSpecificException e) { 17379 throw new ProvisioningException(e, e.errorCode, getErrorMessage(e)); 17380 } catch (RemoteException e) { 17381 throw e.rethrowFromSystemServer(); 17382 } 17383 } 17384 17385 /** 17386 * Creates a managed profile and sets the 17387 * {@link ManagedProfileProvisioningParams#getProfileAdminComponentName()} as the profile 17388 * owner. The method {@link #finalizeCreateManagedProfile} must be called after to finalize the 17389 * creation of the managed profile. 17390 * 17391 * <p>The method {@link #checkProvisioningPrecondition} must return {@link #STATUS_OK} 17392 * before calling this method. If it doesn't, a ProvisioningException will be thrown. 17393 * 17394 * @param provisioningParams Params required to provision a managed profile, 17395 * see {@link ManagedProfileProvisioningParams}. 17396 * @return The {@link UserHandle} of the created profile or {@code null} if the service is 17397 * not available. 17398 * @throws ProvisioningException if an error occurred during provisioning. 17399 * @hide 17400 */ 17401 @Nullable 17402 @SystemApi 17403 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) 17404 @FlaggedApi(FLAG_SPLIT_CREATE_MANAGED_PROFILE_ENABLED) createManagedProfile( @onNull ManagedProfileProvisioningParams provisioningParams)17405 public UserHandle createManagedProfile( 17406 @NonNull ManagedProfileProvisioningParams provisioningParams) 17407 throws ProvisioningException { 17408 if (mService == null) { 17409 return null; 17410 } 17411 try { 17412 return mService.createManagedProfile(provisioningParams, mContext.getPackageName()); 17413 } catch (ServiceSpecificException e) { 17414 throw new ProvisioningException(e, e.errorCode, getErrorMessage(e)); 17415 } catch (RemoteException e) { 17416 throw e.rethrowFromSystemServer(); 17417 } 17418 } 17419 17420 /** 17421 * Finalizes the creation of a managed profile by informing the necessary components that 17422 * the managed profile is ready. 17423 * 17424 * @param provisioningParams Params required to provision a managed profile, 17425 * see {@link ManagedProfileProvisioningParams}. 17426 * @param managedProfileUser The recently created managed profile. 17427 * @throws ProvisioningException if an error occurred during provisioning. 17428 * @hide 17429 */ 17430 @SuppressLint("UserHandle") 17431 @SystemApi 17432 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) 17433 @FlaggedApi(FLAG_SPLIT_CREATE_MANAGED_PROFILE_ENABLED) finalizeCreateManagedProfile( @onNull ManagedProfileProvisioningParams provisioningParams, @NonNull UserHandle managedProfileUser)17434 public void finalizeCreateManagedProfile( 17435 @NonNull ManagedProfileProvisioningParams provisioningParams, 17436 @NonNull UserHandle managedProfileUser) 17437 throws ProvisioningException { 17438 if (mService == null) { 17439 return; 17440 } 17441 try { 17442 mService.finalizeCreateManagedProfile(provisioningParams, managedProfileUser); 17443 } catch (RemoteException e) { 17444 throw e.rethrowFromSystemServer(); 17445 } 17446 } 17447 17448 /** 17449 * Removes a managed profile from the device. 17450 * 17451 * <p> 17452 * Removes the managed profile which is specified by the context user 17453 * ({@code Context.createContextAsUser()}). 17454 * <p> 17455 * 17456 * @return {@code true} when removal of managed profile was successful, {@code false} when 17457 * removal was unsuccessful or throws IllegalArgumentException when specified user was not a 17458 * managed profile 17459 * 17460 * @hide 17461 */ 17462 @SystemApi 17463 @UserHandleAware 17464 @FlaggedApi(FLAG_REMOVE_MANAGED_PROFILE_ENABLED) 17465 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) removeManagedProfile()17466 public boolean removeManagedProfile() { 17467 if (mService == null) { 17468 throw new IllegalStateException("Could not find DevicePolicyManagerService"); 17469 } 17470 try { 17471 return mService.removeManagedProfile(myUserId()); 17472 } catch (RemoteException e) { 17473 throw e.rethrowFromSystemServer(); 17474 } 17475 } 17476 17477 /** 17478 * Called when a managed profile has been provisioned. 17479 * 17480 * @throws SecurityException if the caller does not hold 17481 * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}. 17482 * @hide 17483 */ 17484 @SystemApi 17485 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) finalizeWorkProfileProvisioning( @onNull UserHandle managedProfileUser, @Nullable Account migratedAccount)17486 public void finalizeWorkProfileProvisioning( 17487 @NonNull UserHandle managedProfileUser, @Nullable Account migratedAccount) { 17488 Objects.requireNonNull(managedProfileUser, "managedProfileUser can't be null"); 17489 if (mService == null) { 17490 throw new IllegalStateException("Could not find DevicePolicyManagerService"); 17491 } 17492 try { 17493 mService.finalizeWorkProfileProvisioning(managedProfileUser, migratedAccount); 17494 } catch (RemoteException e) { 17495 throw e.rethrowFromSystemServer(); 17496 } 17497 } 17498 17499 /** 17500 * The localized error message to show to the end-user. If {@code null}, a generic error 17501 * message will be shown. 17502 */ getErrorMessage(ServiceSpecificException e)17503 private String getErrorMessage(ServiceSpecificException e) { 17504 return null; 17505 } 17506 17507 17508 /** 17509 * Provisions a managed device and sets the {@code deviceAdminComponentName} as the device 17510 * owner. 17511 * 17512 * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK} 17513 * before calling this method. 17514 * 17515 * <p>Holders of {@link android.Manifest.permission#PROVISION_DEMO_DEVICE} can call this API 17516 * only if {@link FullyManagedDeviceProvisioningParams#isDemoDevice()} is {@code true}. 17517 * 17518 * <p>If headless device is in {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER} 17519 * mode then it sets the device owner on the first secondary user.</p> 17520 * 17521 * @param provisioningParams Params required to provision a fully managed device, 17522 * see {@link FullyManagedDeviceProvisioningParams}. 17523 * 17524 * @throws ProvisioningException if an error occurred during provisioning. 17525 * 17526 * @hide 17527 */ 17528 @SystemApi 17529 @RequiresPermission(anyOf = { 17530 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, 17531 android.Manifest.permission.PROVISION_DEMO_DEVICE}) provisionFullyManagedDevice( @onNull FullyManagedDeviceProvisioningParams provisioningParams)17532 public void provisionFullyManagedDevice( 17533 @NonNull FullyManagedDeviceProvisioningParams provisioningParams) 17534 throws ProvisioningException { 17535 if (mService != null) { 17536 try { 17537 mService.provisionFullyManagedDevice(provisioningParams, mContext.getPackageName()); 17538 } catch (ServiceSpecificException e) { 17539 throw new ProvisioningException(e, e.errorCode, getErrorMessage(e)); 17540 } catch (RemoteException re) { 17541 throw re.rethrowFromSystemServer(); 17542 } 17543 } 17544 } 17545 17546 /** 17547 * Resets the default cross profile intent filters that were set during 17548 * {@link #createAndProvisionManagedProfile} between {@code userId} and all it's managed 17549 * profiles if any. 17550 * 17551 * @hide 17552 */ 17553 @TestApi 17554 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) resetDefaultCrossProfileIntentFilters(@serIdInt int userId)17555 public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) { 17556 if (mService != null) { 17557 try { 17558 mService.resetDefaultCrossProfileIntentFilters(userId); 17559 } catch (RemoteException re) { 17560 throw re.rethrowFromSystemServer(); 17561 } 17562 } 17563 } 17564 17565 /** 17566 * Returns true if the caller is running on a device where an admin can grant 17567 * permissions related to device sensors. 17568 * This is a signal that the device is a fully-managed device where personal usage is 17569 * discouraged. 17570 * The list of permissions is listed in 17571 * {@link #setPermissionGrantState(ComponentName, String, String, int)}. 17572 * 17573 * May be called by any app. 17574 * @return true if an admin can grant device sensors-related permissions, false otherwise. 17575 */ canAdminGrantSensorsPermissions()17576 public boolean canAdminGrantSensorsPermissions() { 17577 throwIfParentInstance("canAdminGrantSensorsPermissions"); 17578 if (mService == null) { 17579 return false; 17580 } 17581 try { 17582 return mService.canAdminGrantSensorsPermissions(); 17583 } catch (RemoteException re) { 17584 throw re.rethrowFromSystemServer(); 17585 } 17586 } 17587 17588 /** 17589 * Sets the device owner type for a managed device (e.g. financed device). 17590 * 17591 * @param admin The {@link DeviceAdminReceiver} that is the device owner. 17592 * @param deviceOwnerType The device owner type is set to. Use 17593 * {@link #DEVICE_OWNER_TYPE_DEFAULT} for the default device owner type. Use 17594 * {@link #DEVICE_OWNER_TYPE_FINANCED} for the financed device owner type. 17595 * 17596 * @throws IllegalStateException When admin is not the device owner, or there is no device 17597 * owner, or attempting to set the device owner type again for the same admin. 17598 * @throws SecurityException If the caller does not have the permission 17599 * {@link permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}. 17600 * 17601 * @hide 17602 */ 17603 @TestApi setDeviceOwnerType(@onNull ComponentName admin, @DeviceOwnerType int deviceOwnerType)17604 public void setDeviceOwnerType(@NonNull ComponentName admin, 17605 @DeviceOwnerType int deviceOwnerType) { 17606 throwIfParentInstance("setDeviceOwnerType"); 17607 if (mService != null) { 17608 try { 17609 mService.setDeviceOwnerType(admin, deviceOwnerType); 17610 } catch (RemoteException re) { 17611 throw re.rethrowFromSystemServer(); 17612 } 17613 } 17614 } 17615 17616 /** 17617 * Returns the device owner type for the admin used in 17618 * {@link #setDeviceOwnerType(ComponentName, int)}. {@link #DEVICE_OWNER_TYPE_DEFAULT} 17619 * would be returned when the device owner type is not set for the device owner admin. 17620 * 17621 * @param admin The {@link DeviceAdminReceiver} that is the device owner. 17622 * 17623 * @throws IllegalStateException When admin is not the device owner or there is no device owner. 17624 * 17625 * @deprecated Use type-specific APIs (e.g. {@link #isFinancedDevice}). 17626 * @hide 17627 */ 17628 @TestApi 17629 @DeviceOwnerType 17630 @Deprecated 17631 // TODO(b/259908270): remove getDeviceOwnerType(@onNull ComponentName admin)17632 public int getDeviceOwnerType(@NonNull ComponentName admin) { 17633 throwIfParentInstance("getDeviceOwnerType"); 17634 if (mService != null) { 17635 try { 17636 return mService.getDeviceOwnerType(admin); 17637 } catch (RemoteException re) { 17638 throw re.rethrowFromSystemServer(); 17639 } 17640 } 17641 return DEVICE_OWNER_TYPE_DEFAULT; 17642 } 17643 17644 /** 17645 * {@code true} if this device is financed. 17646 * @hide 17647 */ 17648 @RequiresPermission(anyOf = { 17649 android.Manifest.permission.MANAGE_USERS, 17650 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS 17651 }) isFinancedDevice()17652 public boolean isFinancedDevice() { 17653 try { 17654 return isDeviceManaged() 17655 && getDeviceOwnerType(getDeviceOwnerComponentOnAnyUser()) 17656 == DEVICE_OWNER_TYPE_FINANCED; 17657 } catch (IllegalStateException e) { 17658 // getDeviceOwnerType() will throw IllegalStateException if the device does not have a 17659 // DO. This can happen under a race condition when the DO is removed after 17660 // isDeviceManaged() (so it still returns true) but before getDeviceOwnerType(). 17661 // In this case, the device should not be considered a financed device. 17662 return false; 17663 } 17664 } 17665 17666 // TODO(b/315298076): revert ag/25574027 and update the doc 17667 /** 17668 * Called by a device owner or profile owner of an organization-owned managed profile to enable 17669 * or disable USB data signaling for the device. When disabled, USB data connections 17670 * (except from charging functions) are prohibited. 17671 * 17672 * <p> This API is not supported on all devices, the caller should call 17673 * {@link #canUsbDataSignalingBeDisabled()} to check whether enabling or disabling USB data 17674 * signaling is supported on the device. 17675 * 17676 * Starting from Android 15, after the USB data signaling 17677 * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, 17678 * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was 17679 * successfully set or not. This callback will contain: 17680 * <ul> 17681 * <li> The {@link TargetUser} that this policy relates to 17682 * <li> The {@link PolicyUpdateResult}, which will be 17683 * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the 17684 * reason the policy failed to be set 17685 * e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY}) 17686 * </ul> 17687 * If there has been a change to the policy, 17688 * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser, 17689 * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the 17690 * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult} 17691 * will contain the reason why the policy changed. 17692 * 17693 * @param enabled whether USB data signaling should be enabled or not. 17694 * @throws SecurityException if the caller is not permitted to set this policy 17695 * @throws IllegalStateException if disabling USB data signaling is not supported or 17696 * if USB data signaling fails to be enabled/disabled. 17697 */ 17698 @RequiresPermission(value = MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING, conditional = true) 17699 @SupportsCoexistence setUsbDataSignalingEnabled(boolean enabled)17700 public void setUsbDataSignalingEnabled(boolean enabled) { 17701 throwIfParentInstance("setUsbDataSignalingEnabled"); 17702 if (mService != null) { 17703 try { 17704 mService.setUsbDataSignalingEnabled(mContext.getPackageName(), enabled); 17705 } catch (RemoteException e) { 17706 throw e.rethrowFromSystemServer(); 17707 } 17708 } 17709 } 17710 17711 /** 17712 * Returns whether USB data signaling is currently enabled. 17713 * 17714 * <p> When called by a device owner or profile owner of an organization-owned managed profile, 17715 * this API returns whether USB data signaling is currently enabled by that admin. When called 17716 * by any other app, returns whether USB data signaling is currently enabled on the device. 17717 * 17718 * @return {@code true} if USB data signaling is enabled, {@code false} otherwise. 17719 */ isUsbDataSignalingEnabled()17720 public boolean isUsbDataSignalingEnabled() { 17721 throwIfParentInstance("isUsbDataSignalingEnabled"); 17722 if (mService != null) { 17723 try { 17724 return mService.isUsbDataSignalingEnabled(mContext.getPackageName()); 17725 } catch (RemoteException e) { 17726 throw e.rethrowFromSystemServer(); 17727 } 17728 } 17729 return true; 17730 } 17731 17732 /** 17733 * Returns whether enabling or disabling USB data signaling is supported on the device. 17734 * 17735 * @return {@code true} if the device supports enabling and disabling USB data signaling. 17736 */ canUsbDataSignalingBeDisabled()17737 public boolean canUsbDataSignalingBeDisabled() { 17738 throwIfParentInstance("canUsbDataSignalingBeDisabled"); 17739 if (mService != null) { 17740 try { 17741 return mService.canUsbDataSignalingBeDisabled(); 17742 } catch (RemoteException re) { 17743 throw re.rethrowFromSystemServer(); 17744 } 17745 } 17746 return false; 17747 } 17748 17749 /** 17750 * Gets the list of {@link #isAffiliatedUser() affiliated} users running on foreground. 17751 * 17752 * @return list of {@link #isAffiliatedUser() affiliated} users running on foreground. 17753 * 17754 * @throws SecurityException if the calling application is not a device owner 17755 */ 17756 @NonNull listForegroundAffiliatedUsers()17757 public List<UserHandle> listForegroundAffiliatedUsers() { 17758 if (mService == null) return Collections.emptyList(); 17759 17760 try { 17761 return mService.listForegroundAffiliatedUsers(); 17762 } catch (RemoteException re) { 17763 throw re.rethrowFromSystemServer(); 17764 } 17765 } 17766 17767 /** 17768 * Lists apps that are exempt from policies (such as 17769 * {@link #setPackagesSuspended(ComponentName, String[], boolean)}). 17770 * 17771 * @hide 17772 */ 17773 @TestApi 17774 @RequiresPermission(value = MANAGE_DEVICE_ADMINS) getPolicyExemptApps()17775 public @NonNull Set<String> getPolicyExemptApps() { 17776 if (mService == null) return Collections.emptySet(); 17777 17778 try { 17779 return new HashSet<>(mService.listPolicyExemptApps()); 17780 } catch (RemoteException e) { 17781 throw e.rethrowFromSystemServer(); 17782 } 17783 } 17784 17785 /** 17786 * Creates a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent 17787 * from the provided {@code nfcIntent}. 17788 * 17789 * <p>Prerequisites to create the provisioning intent: 17790 * 17791 * <ul> 17792 * <li>{@code nfcIntent}'s action is {@link NfcAdapter#ACTION_NDEF_DISCOVERED}</li> 17793 * <li>{@code nfcIntent}'s NFC properties contain either 17794 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} or 17795 * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} </li> 17796 * </ul> 17797 * 17798 * This method returns {@code null} if the prerequisites are not met or if an error occurs 17799 * when reading the NFC properties. 17800 * 17801 * @param nfcIntent the nfc intent generated from scanning a NFC tag 17802 * @return a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent with 17803 * intent extras as read by {@code nfcIntent}'s NFC properties or {@code null} if the 17804 * prerequisites are not met or if an error occurs when reading the NFC properties. 17805 * 17806 * @hide 17807 */ 17808 @Nullable 17809 @SystemApi createProvisioningIntentFromNfcIntent(@onNull Intent nfcIntent)17810 public Intent createProvisioningIntentFromNfcIntent(@NonNull Intent nfcIntent) { 17811 return ProvisioningIntentHelper.createProvisioningIntentFromNfcIntent(nfcIntent); 17812 } 17813 17814 /** 17815 * Called by device owner or profile owner of an organization-owned managed profile to 17816 * specify the minimum security level required for Wi-Fi networks. 17817 * The device may not connect to networks that do not meet the minimum security level. 17818 * If the current network does not meet the minimum security level set, it will be disconnected. 17819 * 17820 * The following shows the Wi-Fi security levels from the lowest to the highest security level: 17821 * {@link #WIFI_SECURITY_OPEN} 17822 * {@link #WIFI_SECURITY_PERSONAL} 17823 * {@link #WIFI_SECURITY_ENTERPRISE_EAP} 17824 * {@link #WIFI_SECURITY_ENTERPRISE_192} 17825 * 17826 * @param level minimum security level 17827 * @throws SecurityException if the caller is not permitted to set this policy 17828 */ 17829 @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true) setMinimumRequiredWifiSecurityLevel(@ifiSecurity int level)17830 public void setMinimumRequiredWifiSecurityLevel(@WifiSecurity int level) { 17831 throwIfParentInstance("setMinimumRequiredWifiSecurityLevel"); 17832 if (mService != null) { 17833 try { 17834 mService.setMinimumRequiredWifiSecurityLevel(mContext.getPackageName(), level); 17835 } catch (RemoteException e) { 17836 throw e.rethrowFromSystemServer(); 17837 } 17838 } 17839 } 17840 17841 /** 17842 * Returns the current Wi-Fi minimum security level. 17843 * 17844 * @see #setMinimumRequiredWifiSecurityLevel(int) 17845 */ getMinimumRequiredWifiSecurityLevel()17846 public @WifiSecurity int getMinimumRequiredWifiSecurityLevel() { 17847 throwIfParentInstance("getMinimumRequiredWifiSecurityLevel"); 17848 if (mService == null) { 17849 return WIFI_SECURITY_OPEN; 17850 } 17851 try { 17852 return mService.getMinimumRequiredWifiSecurityLevel(); 17853 } catch (RemoteException e) { 17854 throw e.rethrowFromSystemServer(); 17855 } 17856 } 17857 17858 /** 17859 * Called by device owner or profile owner of an organization-owned managed profile to 17860 * specify the Wi-Fi SSID policy ({@link WifiSsidPolicy}). 17861 * Wi-Fi SSID policy specifies the SSID restriction the network must satisfy 17862 * in order to be eligible for a connection. Providing a null policy results in the 17863 * deactivation of the SSID restriction 17864 * 17865 * @param policy Wi-Fi SSID policy 17866 * @throws SecurityException if the caller is not permitted to manage wifi policy 17867 */ 17868 @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true) setWifiSsidPolicy(@ullable WifiSsidPolicy policy)17869 public void setWifiSsidPolicy(@Nullable WifiSsidPolicy policy) { 17870 throwIfParentInstance("setWifiSsidPolicy"); 17871 if (mService == null) { 17872 return; 17873 } 17874 try { 17875 mService.setWifiSsidPolicy(mContext.getPackageName(), policy); 17876 } catch (RemoteException e) { 17877 throw e.rethrowFromSystemServer(); 17878 } 17879 17880 } 17881 17882 /** 17883 * Returns the current Wi-Fi SSID policy. 17884 * If the policy has not been set, it will return NULL. 17885 * 17886 * @see #setWifiSsidPolicy(WifiSsidPolicy) 17887 * @throws SecurityException if the caller is not a device owner or a profile owner on 17888 * an organization-owned managed profile. 17889 */ 17890 @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true) 17891 @Nullable getWifiSsidPolicy()17892 public WifiSsidPolicy getWifiSsidPolicy() { 17893 throwIfParentInstance("getWifiSsidPolicy"); 17894 if (mService == null) { 17895 return null; 17896 } 17897 try { 17898 return mService.getWifiSsidPolicy(mContext.getPackageName()); 17899 } catch (RemoteException e) { 17900 throw e.rethrowFromSystemServer(); 17901 } 17902 } 17903 17904 /** 17905 * 17906 * Returns whether the device considers itself to be potentially stolen. 17907 * @hide 17908 */ 17909 @SystemApi 17910 @RequiresPermission(value = QUERY_DEVICE_STOLEN_STATE) 17911 @FlaggedApi(FLAG_DEVICE_THEFT_API_ENABLED) isDevicePotentiallyStolen()17912 public boolean isDevicePotentiallyStolen() { 17913 throwIfParentInstance("isDevicePotentiallyStolen"); 17914 if (mService == null) { 17915 return false; 17916 } 17917 try { 17918 return mService.isDevicePotentiallyStolen(mContext.getPackageName()); 17919 } catch (RemoteException e) { 17920 throw e.rethrowFromSystemServer(); 17921 } 17922 } 17923 17924 /** 17925 * Returns a {@link DevicePolicyResourcesManager} containing the required APIs to set, reset, 17926 * and get device policy related resources. 17927 */ 17928 @NonNull getResources()17929 public DevicePolicyResourcesManager getResources() { 17930 return mResourcesManager; 17931 } 17932 17933 /** 17934 * Returns a boolean for whether the DPC 17935 * (Device Policy Controller, the agent responsible for enforcing policy) 17936 * has been downloaded during provisioning. 17937 * 17938 * <p>If true is returned, then any attempts to begin setup again should result in factory reset 17939 * 17940 * @hide 17941 */ 17942 @SystemApi 17943 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) isDpcDownloaded()17944 public boolean isDpcDownloaded() { 17945 throwIfParentInstance("isDpcDownloaded"); 17946 if (mService != null) { 17947 try { 17948 return mService.isDpcDownloaded(); 17949 } catch (RemoteException e) { 17950 throw e.rethrowFromSystemServer(); 17951 } 17952 } 17953 return false; 17954 } 17955 17956 /** 17957 * Indicates that the DPC (Device Policy Controller, the agent responsible for enforcing policy) 17958 * has or has not been downloaded during provisioning. 17959 * 17960 * @param downloaded {@code true} if the dpc has been downloaded during provisioning. 17961 * {@code false} otherwise. 17962 * 17963 * @hide 17964 */ 17965 @SystemApi 17966 @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) setDpcDownloaded(boolean downloaded)17967 public void setDpcDownloaded(boolean downloaded) { 17968 throwIfParentInstance("setDpcDownloaded"); 17969 if (mService != null) { 17970 try { 17971 mService.setDpcDownloaded(downloaded); 17972 } catch (RemoteException e) { 17973 throw e.rethrowFromSystemServer(); 17974 } 17975 } 17976 } 17977 17978 /** 17979 * Returns the package name of the device policy management role holder. 17980 * 17981 * <p>If the device policy management role holder is not configured for this device, returns 17982 * {@code null}. 17983 */ 17984 @Nullable getDevicePolicyManagementRoleHolderPackage()17985 public String getDevicePolicyManagementRoleHolderPackage() { 17986 String devicePolicyManagementConfig = mContext.getString( 17987 com.android.internal.R.string.config_devicePolicyManagement); 17988 return extractPackageNameFromDeviceManagerConfig(devicePolicyManagementConfig); 17989 } 17990 17991 /** 17992 * Returns the package name of the device policy management role holder updater. 17993 * 17994 * <p>If the device policy management role holder updater is not configured for this device, 17995 * returns {@code null}. 17996 * 17997 * @hide 17998 */ 17999 @Nullable 18000 @TestApi getDevicePolicyManagementRoleHolderUpdaterPackage()18001 public String getDevicePolicyManagementRoleHolderUpdaterPackage() { 18002 String devicePolicyManagementUpdaterConfig = mContext.getString( 18003 com.android.internal.R.string.config_devicePolicyManagementUpdater); 18004 if (TextUtils.isEmpty(devicePolicyManagementUpdaterConfig)) { 18005 return null; 18006 } 18007 return devicePolicyManagementUpdaterConfig; 18008 } 18009 18010 /** 18011 * Returns a {@link List} of managed profiles managed by some profile owner within the profile 18012 * group of the given user, or an empty {@link List} if there is not one. 18013 * 18014 * @param user the user whose profile group to look within to return managed profiles 18015 * 18016 * @hide 18017 */ 18018 @SystemApi 18019 @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) 18020 @NonNull getPolicyManagedProfiles(@onNull UserHandle user)18021 public List<UserHandle> getPolicyManagedProfiles(@NonNull UserHandle user) { 18022 Objects.requireNonNull(user); 18023 if (mService != null) { 18024 try { 18025 return mService.getPolicyManagedProfiles(user); 18026 } catch (RemoteException e) { 18027 throw e.rethrowFromSystemServer(); 18028 } 18029 } 18030 return Collections.emptyList(); 18031 } 18032 18033 /** 18034 * Retrieves the package name for a given {@code deviceManagerConfig}. 18035 * 18036 * <p>Valid configs look like: 18037 * <ul> 18038 * <li>{@code com.package.name}</li> 18039 * <li>{@code com.package.name:<SHA256 checksum>}</li> 18040 * </ul> 18041 * 18042 * <p>If the supplied {@code deviceManagerConfig} is {@code null} or empty, returns 18043 * {@code null}. 18044 */ 18045 @Nullable extractPackageNameFromDeviceManagerConfig( @ullable String deviceManagerConfig)18046 private String extractPackageNameFromDeviceManagerConfig( 18047 @Nullable String deviceManagerConfig) { 18048 if (TextUtils.isEmpty(deviceManagerConfig)) { 18049 return null; 18050 } 18051 if (deviceManagerConfig.contains(":")) { 18052 return deviceManagerConfig.split(":")[0]; 18053 } 18054 return deviceManagerConfig; 18055 } 18056 18057 /** 18058 * Reset cache for {@link #shouldAllowBypassingDevicePolicyManagementRoleQualification}. 18059 * 18060 * @hide 18061 */ 18062 @TestApi 18063 @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS) resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState()18064 public void resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState() { 18065 if (mService != null) { 18066 try { 18067 mService.resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState(); 18068 } catch (RemoteException e) { 18069 throw e.rethrowFromSystemServer(); 18070 } 18071 } 18072 } 18073 18074 /** 18075 * Recalculate the incompatible accounts cache. 18076 * 18077 * @hide 18078 */ 18079 @TestApi 18080 @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) calculateHasIncompatibleAccounts()18081 public void calculateHasIncompatibleAccounts() { 18082 if (mService != null) { 18083 try { 18084 mService.calculateHasIncompatibleAccounts(); 18085 } catch (RemoteException e) { 18086 throw e.rethrowFromSystemServer(); 18087 } 18088 } 18089 } 18090 18091 /** 18092 * @return {@code true} if bypassing the device policy management role qualification is allowed 18093 * with the current state of the device. 18094 * 18095 * @hide 18096 */ 18097 @SystemApi 18098 @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS) shouldAllowBypassingDevicePolicyManagementRoleQualification()18099 public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() { 18100 if (mService != null) { 18101 try { 18102 return mService.shouldAllowBypassingDevicePolicyManagementRoleQualification(); 18103 } catch (RemoteException e) { 18104 throw e.rethrowFromSystemServer(); 18105 } 18106 } 18107 return false; 18108 } 18109 18110 /** 18111 * Returns a {@link DevicePolicyState} object containing information about the current state 18112 * of device policies (e.g. values set by different admins, info about the enforcing admins, 18113 * resolved policy, etc). 18114 * 18115 * @hide 18116 */ 18117 @SystemApi 18118 @NonNull 18119 @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) getDevicePolicyState()18120 public DevicePolicyState getDevicePolicyState() { 18121 if (mService != null) { 18122 try { 18123 return mService.getDevicePolicyState(); 18124 } catch (RemoteException e) { 18125 throw e.rethrowFromSystemServer(); 18126 } 18127 } 18128 return null; 18129 } 18130 18131 /** 18132 * Triggers the data migration of device policies for existing DPCs to the Device Policy Engine. 18133 * If {@code forceMigration} is set to {@code true} it skips the prerequisite checks before 18134 * triggering the migration. 18135 * 18136 * <p>Returns {@code true} if migration was completed successfully, {@code false} otherwise. 18137 * 18138 * @hide 18139 */ 18140 @TestApi 18141 @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) triggerDevicePolicyEngineMigration(boolean forceMigration)18142 public boolean triggerDevicePolicyEngineMigration(boolean forceMigration) { 18143 if (mService != null) { 18144 try { 18145 return mService.triggerDevicePolicyEngineMigration(forceMigration); 18146 } catch (RemoteException e) { 18147 throw e.rethrowFromSystemServer(); 18148 } 18149 } 18150 return false; 18151 } 18152 18153 /** 18154 * Returns {@code true} if this device is marked as a financed device. 18155 * 18156 * <p>A financed device can be entered into lock task mode (see {@link #setLockTaskPackages}) 18157 * by the holder of the role {@code android.app.role.RoleManager#ROLE_FINANCED_DEVICE_KIOSK}. 18158 * If this occurs, Device Owners and Profile Owners that have set lock task packages or 18159 * features, or that attempt to set lock task packages or features, will receive a callback 18160 * indicating that it could not be set. See {@link PolicyUpdateReceiver#onPolicyChanged} and 18161 * {@link PolicyUpdateReceiver#onPolicySetResult}. 18162 * 18163 * <p>To be informed of changes to this status you can subscribe to the broadcast 18164 * {@link #ACTION_DEVICE_FINANCING_STATE_CHANGED}. 18165 * 18166 * @throws SecurityException if the caller is not a device owner, profile owner of an 18167 * organization-owned managed profile, profile owner on the primary user or holder of one of the 18168 * following roles: {@code android.app.role.RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT}, 18169 * {@code android.app.role.RoleManager.ROLE_SYSTEM_SUPERVISION}. 18170 */ isDeviceFinanced()18171 public boolean isDeviceFinanced() { 18172 throwIfParentInstance("isDeviceFinanced"); 18173 if (mService != null) { 18174 try { 18175 return mService.isDeviceFinanced(mContext.getPackageName()); 18176 } catch (RemoteException e) { 18177 throw e.rethrowFromSystemServer(); 18178 } 18179 } 18180 return false; 18181 } 18182 18183 /** 18184 * Returns the package name of the application holding the role: 18185 * {@link android.app.role.RoleManager#ROLE_FINANCED_DEVICE_KIOSK}. 18186 * 18187 * @return the package name of the application holding the role or {@code null} if the role is 18188 * not held by any applications. 18189 * @hide 18190 */ 18191 @SystemApi 18192 @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) 18193 @Nullable getFinancedDeviceKioskRoleHolder()18194 public String getFinancedDeviceKioskRoleHolder() { 18195 if (mService != null) { 18196 try { 18197 return mService.getFinancedDeviceKioskRoleHolder(mContext.getPackageName()); 18198 } catch (RemoteException e) { 18199 throw e.rethrowFromSystemServer(); 18200 } 18201 } 18202 return null; 18203 } 18204 18205 // TODO(b/308755220): Remove once the build is finalised. 18206 /** 18207 * Returns true if the flag for the onboarding bugreport V2 is enabled. 18208 * 18209 * @hide 18210 */ 18211 @UnsupportedAppUsage isOnboardingBugreportV2FlagEnabled()18212 public boolean isOnboardingBugreportV2FlagEnabled() { 18213 return onboardingBugreportV2Enabled(); 18214 } 18215 18216 // TODO(b/308755220): Remove once the build is finalised. 18217 /** 18218 * Returns true if the flag for consentless bugreports is enabled. 18219 * 18220 * @hide 18221 */ 18222 @UnsupportedAppUsage isOnboardingConsentlessBugreportFlagEnabled()18223 public boolean isOnboardingConsentlessBugreportFlagEnabled() { 18224 return onboardingConsentlessBugreports(); 18225 } 18226 18227 /** 18228 * Returns the subscription ids of all subscriptions which were downloaded by the calling 18229 * admin. 18230 * 18231 * <p> This returns only the subscriptions which were downloaded by the calling admin via 18232 * {@link android.telephony.euicc.EuiccManager#downloadSubscription}. 18233 * If a subscription is returned by this method then in it subject to management controls 18234 * and cannot be removed by users. 18235 * 18236 * <p> Callable by device owners and profile owners. 18237 * 18238 * @throws SecurityException if the caller is not authorized to call this method. 18239 * @return ids of all managed subscriptions currently downloaded by an admin on the device. 18240 */ 18241 @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS) 18242 @NonNull getSubscriptionIds()18243 public Set<Integer> getSubscriptionIds() { 18244 throwIfParentInstance("getSubscriptionIds"); 18245 if (mService != null) { 18246 try { 18247 return intArrayToSet(mService.getSubscriptionIds(mContext.getPackageName())); 18248 } catch (RemoteException e) { 18249 throw e.rethrowFromSystemServer(); 18250 } 18251 } 18252 return new HashSet<>(); 18253 } 18254 18255 /** 18256 * Controls the maximum storage size allowed for policies associated with an admin. 18257 * Setting a limit of -1 effectively removes any storage restrictions. 18258 * 18259 * @param storageLimit Maximum storage allowed in bytes. Use -1 to disable limits. 18260 * 18261 * @hide 18262 */ 18263 @SystemApi 18264 @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) setMaxPolicyStorageLimit(int storageLimit)18265 public void setMaxPolicyStorageLimit(int storageLimit) { 18266 if (mService != null) { 18267 try { 18268 mService.setMaxPolicyStorageLimit(mContext.getPackageName(), storageLimit); 18269 } catch (RemoteException e) { 18270 throw e.rethrowFromSystemServer(); 18271 } 18272 } 18273 } 18274 18275 /** 18276 * Retrieves the current maximum storage limit for policies associated with an admin. 18277 * 18278 * @return The maximum storage limit in bytes, or -1 if no limit is enforced. 18279 * 18280 * @hide 18281 */ 18282 @SystemApi 18283 @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) getMaxPolicyStorageLimit()18284 public int getMaxPolicyStorageLimit() { 18285 if (mService != null) { 18286 try { 18287 return mService.getMaxPolicyStorageLimit(mContext.getPackageName()); 18288 } catch (RemoteException e) { 18289 throw e.rethrowFromSystemServer(); 18290 } 18291 } 18292 return -1; 18293 } 18294 18295 /** 18296 * Force sets the maximum storage size allowed for policies associated with an admin regardless 18297 * of the default value set in the system, unlike {@link #setMaxPolicyStorageLimit} which can 18298 * only set it to a value higher than the default value set by the system.Setting a limit of -1 18299 * effectively removes any storage restrictions. 18300 * 18301 * @param storageLimit Maximum storage allowed in bytes. Use -1 to disable limits. 18302 * 18303 * @hide 18304 */ 18305 @TestApi 18306 @RequiresPermission(permission.MANAGE_DEVICE_POLICY_STORAGE_LIMIT) forceSetMaxPolicyStorageLimit(int storageLimit)18307 public void forceSetMaxPolicyStorageLimit(int storageLimit) { 18308 if (mService != null) { 18309 try { 18310 mService.forceSetMaxPolicyStorageLimit(mContext.getPackageName(), storageLimit); 18311 } catch (RemoteException e) { 18312 throw e.rethrowFromSystemServer(); 18313 } 18314 } 18315 } 18316 18317 /** 18318 * Retrieves the size of the current policies set by the {@code admin}. 18319 * 18320 * @hide 18321 */ 18322 @TestApi 18323 @RequiresPermission(permission.MANAGE_DEVICE_POLICY_STORAGE_LIMIT) getPolicySizeForAdmin(@onNull EnforcingAdmin admin)18324 public int getPolicySizeForAdmin(@NonNull EnforcingAdmin admin) { 18325 if (mService != null) { 18326 try { 18327 return mService.getPolicySizeForAdmin(mContext.getPackageName(), admin); 18328 } catch (RemoteException e) { 18329 throw e.rethrowFromSystemServer(); 18330 } 18331 } 18332 return -1; 18333 } 18334 18335 /** 18336 * @return The headless device owner mode for the current set DO, returns 18337 * {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED} if no DO is set. 18338 * 18339 * @hide 18340 */ 18341 @TestApi 18342 @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) 18343 @DeviceAdminInfo.HeadlessDeviceOwnerMode getHeadlessDeviceOwnerMode()18344 public int getHeadlessDeviceOwnerMode() { 18345 if (mService != null) { 18346 try { 18347 return mService.getHeadlessDeviceOwnerMode(mContext.getPackageName()); 18348 } catch (RemoteException e) { 18349 throw e.rethrowFromSystemServer(); 18350 } 18351 } 18352 return HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED; 18353 } 18354 } 18355