Cambios en el comportamiento: apps orientadas a Android 14 o versiones posteriores

Al igual que las versiones anteriores, Android 14 incluye cambios de comportamiento que podrían afectar tu app. Los siguientes cambios de comportamiento se aplican exclusivamente a las apps orientadas a Android 14 (nivel de API 34) o versiones posteriores. Si tu app está orientada a Android 14 o versiones posteriores, debes modificarla para que admita estos comportamientos correctamente, cuando corresponda.

Asegúrate de revisar también la lista de cambios de comportamiento que afectan a todas las apps que se ejecutan en Android 14, independientemente de targetSdkVersion de la app.

Funcionalidad principal

Los tipos de servicio en primer plano son obligatorios

如果您的应用以 Android 14(API 级别 34)或更高版本为目标平台,则必须为应用中的每个前台服务至少指定一项前台服务类型。您应选择一个能代表应用用例的前台服务类型。系统需要特定类型的前台服务满足特定用例。

如果应用中的用例与这些类型均不相关,强烈建议您迁移逻辑以使用 WorkManager用户发起的数据传输作业

Aplicación forzosa del permiso BLUETOOTH_CONNECT en BluetoothAdapter

对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,Android 14 会在调用 BluetoothAdapter getProfileConnectionState() 方法时强制执行 BLUETOOTH_CONNECT 权限。

此方法已要求 BLUETOOTH_CONNECT 权限,但未强制执行。确保您的应用在应用的 AndroidManifest.xml 文件中声明 BLUETOOTH_CONNECT,如以下代码段所示,并在调用 getProfileConnectionState 之前检查用户是否已授予相应权限

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

Actualizaciones de OpenJDK 17

Android 14 continúa la tarea de actualizar las bibliotecas principales de Android para alinearlas con las funciones de las versiones más recientes de LTS de OpenJDK, lo que incluye las actualizaciones de bibliotecas y la compatibilidad con el lenguaje Java 17 para desarrolladores de apps y plataformas.

Algunos de estos cambios pueden afectar la compatibilidad de la app:

  • Cambios en las expresiones regulares: Ahora no se permite que las referencias de grupo no válidas sigan la semántica de OpenJDK. Es posible que veas casos nuevos en los que la clase java.util.regex.Matcher arroje IllegalArgumentException, así que asegúrate de probar tu app para detectar áreas que usen expresiones regulares. Para habilitar o inhabilitar este cambio durante las pruebas, activa o desactiva la marca DISALLOW_INVALID_GROUP_REFERENCE con las herramientas del marco de compatibilidad.
  • Manejo de UUID: El método java.util.UUID.fromString() ahora realiza verificaciones más estrictas cuando se valida el argumento de entrada, por lo que es posible que veas una IllegalArgumentException durante deserialización. Para habilitar o inhabilitar este cambio durante las pruebas, activa o desactiva la marca ENABLE_STRICT_VALIDATION con las herramientas del marco de compatibilidad.
  • Problemas de ProGuard: En algunos casos, la adición de la clase java.lang.ClassValue genera un problema si intentas reducir, ofuscar y optimizar la app con ProGuard. El problema se origina en una biblioteca de Kotlin que cambia el comportamiento del tiempo de ejecución en función de si Class.forName("java.lang.ClassValue") muestra una clase o no. Si tu app se desarrolló en una versión anterior del tiempo de ejecución sin la clase java.lang.ClassValue disponible, estas optimizaciones podrían quitar el método computeValue de las clases derivadas de java.lang.ClassValue.

JobScheduler refuerza el comportamiento de devolución de llamada y de red

自从引入后,JobScheduler 期望您的应用从 onStartJobonStopJob。在 Android 14 之前,如果作业运行时间过长,系统会停止作业并静默失败。如果您的应用以 Android 14(API 级别 34)或更高版本为目标平台, 超过在主线程上授予的时间,应用会触发 ANR 显示“没有响应 onStartJob”错误消息或 “onStopJob没有回复”。

此 ANR 可能是由以下 2 种情况造成的: 1.有工作阻塞主线程,阻止回调 onStartJob 或者onStopJob在预期时间内执行并完成。 2. 开发者在 JobScheduler 中运行阻塞工作 回调 onStartJobonStopJob,阻止从 在预期的时限内完成

要解决第 1 个问题,您需要进一步调试阻塞主线程的因素 您可以使用以下代码 ApplicationExitInfo#getTraceInputStream(),用于获取 Tombstone ANR 发生时的跟踪信息如果您能够手动重现 ANR 问题 您可以录制系统轨迹,并使用 Android StudioPerfetto,以便更好地了解应用上运行的 在发生 ANR 时调用主线程 请注意,直接使用 JobScheduler API 或使用 androidx 库 WorkManager 时可能会发生这种情况。

如需解决问题 2,请考虑迁移到 WorkManager,它支持将 onStartJobonStopJob 中的任何处理封装在异步线程中。

JobScheduler 还引入了一项要求,即如果使用 setRequiredNetworkTypesetRequiredNetwork 约束条件,则必须声明 ACCESS_NETWORK_STATE 权限。如果您的应用未声明 ACCESS_NETWORK_STATE 权限 Android 14 或更高版本,则会导致 SecurityException

API de lanzamiento de tarjetas

对于以 Android 14 及更高版本为目标平台的应用, TileService#startActivityAndCollapse(Intent) 已弃用,现在会抛出 调用时抛出异常。如果您的应用从功能块启动 activity,请使用 TileService#startActivityAndCollapse(PendingIntent)

Privacidad

Acceso parcial a fotos y videos

Android 14 presenta el Acceso a fotos seleccionadas, que permite a los usuarios otorgar a las apps acceso a imágenes y videos específicos de su biblioteca, en lugar de otorgar acceso a todo el contenido multimedia de un tipo determinado.

Este cambio solo se habilita si tu app se orienta a Android 14 (nivel de API 34) o versiones posteriores. Si aún no usas el selector de fotos, te recomendamos implementarlo en tu app para proporcionar una experiencia coherente para seleccionar imágenes y videos que también mejore la privacidad del usuario sin tener que solicitar ningún permiso de almacenamiento.

Si mantienes tu propio selector de galería con permisos de almacenamiento y necesitas mantener el control total sobre tu implementación, adapta tu implementación para usar el nuevo permiso READ_MEDIA_VISUAL_USER_SELECTED. Si tu app no usa el nuevo permiso, el sistema la ejecutará en un modo de compatibilidad.

Experiencia del usuario

Notificaciones de intent de pantalla completa seguras

Con Android 11 (nivel de API 30), cualquier app podía usar Notification.Builder.setFullScreenIntent para enviar intents de pantalla completa mientras el teléfono estaba bloqueado. Para otorgarlo de forma automática durante la instalación de la app, declara el permiso USE_FULL_SCREEN_INTENT en AndroidManifest.

Las notificaciones de los intents de pantalla completa están diseñadas para las notificaciones de prioridad extremadamente alta que requieren la atención inmediata del usuario, como una llamada entrante o la configuración de la alarma que establece el usuario. En el caso de las apps orientadas a Android 14 (nivel de API 34) y versiones posteriores, las apps que pueden usar este permiso se limitan a aquellas que solo proporcionan llamadas y alarmas. Google Play Store revoca los permisos USE_FULL_SCREEN_INTENT predeterminados para las apps que no se ajustan a este perfil. El plazo para estos cambios en las políticas es el 31 de mayo de 2024.

Este permiso permanece habilitado para las apps que se instalan en el teléfono antes de que el usuario actualice a Android 14. Los usuarios pueden activar o desactivar este permiso.

Puedes usar la nueva API de NotificationManager.canUseFullScreenIntent para verificar si tu app tiene el permiso. De lo contrario, la app puede usar el nuevo intent ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT para iniciar la página de configuración en la que los usuarios pueden otorgar el permiso.

Seguridad

Restricciones a intents implícitos y pendientes

For apps targeting Android 14 (API level 34) or higher, Android restricts apps from sending implicit intents to internal app components in the following ways:

  • Implicit intents are only delivered to exported components. Apps must either use an explicit intent to deliver to unexported components, or mark the component as exported.
  • If an app creates a mutable pending intent with an intent that doesn't specify a component or package, the system throws an exception.

These changes prevent malicious apps from intercepting implicit intents that are intended for use by an app's internal components.

For example, here is an intent filter that could be declared in your app's manifest file:

<activity
    android:name=".AppActivity"
    android:exported="false">
    <intent-filter>
        <action android:name="com.example.action.APP_ACTION" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

If your app tried to launch this activity using an implicit intent, an ActivityNotFoundException exception would be thrown:

Kotlin

// Throws an ActivityNotFoundException exception when targeting Android 14.
context.startActivity(Intent("com.example.action.APP_ACTION"))

Java

// Throws an ActivityNotFoundException exception when targeting Android 14.
context.startActivity(new Intent("com.example.action.APP_ACTION"));

To launch the non-exported activity, your app should use an explicit intent instead:

Kotlin

// This makes the intent explicit.
val explicitIntent =
        Intent("com.example.action.APP_ACTION")
explicitIntent.apply {
    package = context.packageName
}
context.startActivity(explicitIntent)

Java

// This makes the intent explicit.
Intent explicitIntent =
        new Intent("com.example.action.APP_ACTION")
explicitIntent.setPackage(context.getPackageName());
context.startActivity(explicitIntent);

Los receptores de transmisiones registradas en el tiempo de ejecución deben especificar el comportamiento de exportación

Apps and services that target Android 14 (API level 34) or higher and use context-registered receivers are required to specify a flag to indicate whether or not the receiver should be exported to all other apps on the device: either RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED, respectively. This requirement helps protect apps from security vulnerabilities by leveraging the features for these receivers introduced in Android 13.

Exception for receivers that receive only system broadcasts

If your app is registering a receiver only for system broadcasts through Context#registerReceiver methods, such as Context#registerReceiver(), then it shouldn't specify a flag when registering the receiver.

Carga más segura del código dinámico

If your app targets Android 14 (API level 34) or higher and uses Dynamic Code Loading (DCL), all dynamically-loaded files must be marked as read-only. Otherwise, the system throws an exception. We recommend that apps avoid dynamically loading code whenever possible, as doing so greatly increases the risk that an app can be compromised by code injection or code tampering.

If you must dynamically load code, use the following approach to set the dynamically-loaded file (such as a DEX, JAR, or APK file) as read-only as soon as the file is opened and before any content is written:

Kotlin

val jar = File("DYNAMICALLY_LOADED_FILE.jar")
val os = FileOutputStream(jar)
os.use {
    // Set the file to read-only first to prevent race conditions
    jar.setReadOnly()
    // Then write the actual file content
}
val cl = PathClassLoader(jar, parentClassLoader)

Java

File jar = new File("DYNAMICALLY_LOADED_FILE.jar");
try (FileOutputStream os = new FileOutputStream(jar)) {
    // Set the file to read-only first to prevent race conditions
    jar.setReadOnly();
    // Then write the actual file content
} catch (IOException e) { ... }
PathClassLoader cl = new PathClassLoader(jar, parentClassLoader);

Handle dynamically-loaded files that already exist

To prevent exceptions from being thrown for existing dynamically-loaded files, we recommend deleting and recreating the files before you try to dynamically load them again in your app. As you recreate the files, follow the preceding guidance for marking the files read-only at write time. Alternatively, you can re-label the existing files as read-only, but in this case, we strongly recommend that you verify the integrity of the files first (for example, by checking the file's signature against a trusted value), to help protect your app from malicious actions.

Restricciones adicionales sobre el inicio de actividades en segundo plano

对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,系统会进一步限制允许应用在后台启动 activity 的时间:

这些更改扩大了一组现有限制条件的范围,目的是防止恶意应用滥用 API 以在后台启动干扰性活动,从而保护用户。

Salto de directorio del archivo ZIP

For apps targeting Android 14 (API level 34) or higher, Android prevents the Zip Path Traversal Vulnerability in the following way: ZipFile(String) and ZipInputStream.getNextEntry() throws a ZipException if zip file entry names contain ".." or start with "/".

Apps can opt-out from this validation by calling dalvik.system.ZipPathValidator.clearCallback().

对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,在以下任一情况下,MediaProjection#createVirtualDisplay 都会抛出 SecurityException

您的应用必须在每次捕获会话之前征求用户同意。单次捕获会话是对 MediaProjection#createVirtualDisplay 的单次调用,并且每个 MediaProjection 实例只能使用一次。

处理配置变更

如果您的应用需要调用 MediaProjection#createVirtualDisplay 来处理配置更改(例如屏幕方向或屏幕大小更改),您可以按照以下步骤更新现有 MediaProjection 实例的 VirtualDisplay

  1. 使用新的宽度和高度调用 VirtualDisplay#resize
  2. VirtualDisplay#setSurface 提供新的 Surface,并为其指定新的宽度和高度。

注册回调

您的应用应注册回调,以处理用户不同意继续拍摄会话的情况。为此,请实现 Callback#onStop,并让应用释放所有相关资源(例如 VirtualDisplaySurface)。

如果您的应用未注册此回调,当您的应用调用它时,MediaProjection#createVirtualDisplay 会抛出 IllegalStateException

Actualización de restricciones que no pertenecen al SDK

Android 14 includes updated lists of restricted non-SDK interfaces based on collaboration with Android developers and the latest internal testing. Whenever possible, we make sure that public alternatives are available before we restrict non-SDK interfaces.

If your app does not target Android 14, some of these changes might not immediately affect you. However, while you can currently use some non-SDK interfaces (depending on your app's target API level), using any non-SDK method or field always carries a high risk of breaking your app.

If you are unsure if your app uses non-SDK interfaces, you can test your app to find out. If your app relies on non-SDK interfaces, you should begin planning a migration to SDK alternatives. Nevertheless, we understand that some apps have valid use cases for using non-SDK interfaces. If you cannot find an alternative to using a non-SDK interface for a feature in your app, you should request a new public API.

To learn more about the changes in this release of Android, see Updates to non-SDK interface restrictions in Android 14. To learn more about non-SDK interfaces generally, see Restrictions on non-SDK interfaces.