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 se aplican exclusivamente a las apps orientadas a Android 14 (nivel de API 34) o versiones posteriores. Si tu app está segmentada para 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 en el 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 del permiso BLUETOOTH_CONNECT en BluetoothAdapter

Android 14 aplica el permiso BLUETOOTH_CONNECT cuando se llama al método BluetoothAdapter getProfileConnectionState() para apps orientadas a Android 14 (nivel de API 34) o versiones posteriores.

Este método ya requería el permiso BLUETOOTH_CONNECT, pero no se aplicaba. Asegúrate de que tu app declare BLUETOOTH_CONNECT en el archivo AndroidManifest.xml, como se muestra en el siguiente fragmento, y verifica que un usuario haya otorgado el permiso antes de llamar a 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 la devolución de llamada y la red

Since its introduction, JobScheduler expects your app to return from onStartJob or onStopJob within a few seconds. Prior to Android 14, if a job runs too long, the job is stopped and fails silently. If your app targets Android 14 (API level 34) or higher and exceeds the granted time on the main thread, the app triggers an ANR with the error message "No response to onStartJob" or "No response to onStopJob".

This ANR may be a result of 2 scenarios: 1. There is work blocking the main thread, preventing the callbacks onStartJob or onStopJob from executing and completing within the expected time limit. 2. The developer is running blocking work within the JobScheduler callback onStartJob or onStopJob, preventing the callback from completing within the expected time limit.

To address #1, you will need to further debug what is blocking the main thread when the ANR occurs, you can do this using ApplicationExitInfo#getTraceInputStream() to get the tombstone trace when the ANR occurs. If you're able to manually reproduce the ANR, you can record a system trace and inspect the trace using either Android Studio or Perfetto to better understand what is running on the main thread when the ANR occurs. Note that this can happen when using JobScheduler API directly or using the androidx library WorkManager.

To address #2, consider migrating to WorkManager, which provides support for wrapping any processing in onStartJob or onStopJob in an asynchronous thread.

JobScheduler also introduces a requirement to declare the ACCESS_NETWORK_STATE permission if using setRequiredNetworkType or setRequiredNetwork constraint. If your app does not declare the ACCESS_NETWORK_STATE permission when scheduling the job and is targeting Android 14 or higher, it will result in a SecurityException.

API de lanzamiento de Tiles

En el caso de las apps orientadas a 14 y versiones posteriores, TileService#startActivityAndCollapse(Intent) dejó de estar disponible y ahora arroja una excepción cuando se la llama. Si tu app inicia actividades desde tarjetas, usa TileService#startActivityAndCollapse(PendingIntent) en su lugar.

Privacidad

Acceso parcial a fotos y videos

Android 14 introduces Selected Photos Access, which allows users to grant apps access to specific images and videos in their library, rather than granting access to all media of a given type.

This change is only enabled if your app targets Android 14 (API level 34) or higher. If you don't use the photo picker yet, we recommend implementing it in your app to provide a consistent experience for selecting images and videos that also enhances user privacy without having to request any storage permissions.

If you maintain your own gallery picker using storage permissions and need to maintain full control over your implementation, adapt your implementation to use the new READ_MEDIA_VISUAL_USER_SELECTED permission. If your app doesn't use the new permission, the system runs your app in a compatibility mode.

Experiencia del usuario

Notificaciones de intent de pantalla completa seguras

With Android 11 (API level 30), it was possible for any app to use Notification.Builder.setFullScreenIntent to send full-screen intents while the phone is locked. You could auto-grant this on app install by declaring USE_FULL_SCREEN_INTENT permission in the AndroidManifest.

Full-screen intent notifications are designed for extremely high-priority notifications demanding the user's immediate attention, such as an incoming phone call or alarm clock settings configured by the user. For apps targeting Android 14 (API level 34) or higher, apps that are allowed to use this permission are limited to those that provide calling and alarms only. The Google Play Store revokes default USE_FULL_SCREEN_INTENT permissions for any apps that don't fit this profile. The deadline for these policy changes is May 31, 2024.

This permission remains enabled for apps installed on the phone before the user updates to Android 14. Users can turn this permission on and off.

You can use the new API NotificationManager.canUseFullScreenIntent to check if your app has the permission; if not, your app can use the new intent ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT to launch the settings page where users can grant the permission.

Seguridad

Restricciones a intents implícitos y pendientes

En el caso de las apps que se orientan a Android 14 (nivel de API 34) o versiones posteriores, Android restringe el envío de intents implícitos a los componentes internos de las apps de las siguientes maneras:

  • Los intents implícitos solo se entregan a los componentes exportados. Las apps deben usar un intent explícito para entregar componentes no exportados o marcar el componente como exportado.
  • Si una app crea un intent pendiente mutable con un intent que no especifica ningún componente ni paquete, el sistema arroja una excepción.

Estos cambios evitan que las apps maliciosas intercepten intents implícitos destinados a que los usen los componentes internos de una app.

Por ejemplo, el siguiente es un filtro de intents que podría declararse en el archivo de manifiesto de tu app:

<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>

Si tu app intenta iniciar esta actividad con un intent implícito, se arrojará una excepción ActivityNotFoundException:

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"));

Para iniciar la actividad no exportada, tu app debe usar un intent explícito:

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

以 Android 14(API 级别 34)或更高版本为目标平台并使用上下文注册的接收器的应用和服务必须指定以下标志,以指明接收器是否应导出到设备上的所有其他应用:RECEIVER_EXPORTEDRECEIVER_NOT_EXPORTED。此要求有助于利用 Android 13 中引入的这些接收器的功能,来保护应用免受安全漏洞的影响。

仅接收系统广播的接收器的例外情况

如果您的应用仅通过 Context#registerReceiver 方法(例如 Context#registerReceiver())针对系统广播注册接收器,那么它在注册接收器时不应指定标志。

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().

For apps targeting Android 14 (API level 34) or higher, a SecurityException is thrown by MediaProjection#createVirtualDisplay in either of the following scenarios:

Your app must ask the user to give consent before each capture session. A single capture session is a single invocation on MediaProjection#createVirtualDisplay, and each MediaProjection instance must be used only once.

Handle configuration changes

If your app needs to invoke MediaProjection#createVirtualDisplay to handle configuration changes (such as the screen orientation or screen size changing), you can follow these steps to update the VirtualDisplay for the existing MediaProjection instance:

  1. Invoke VirtualDisplay#resize with the new width and height.
  2. Provide a new Surface with the new width and height to VirtualDisplay#setSurface.

Register a callback

Your app should register a callback to handle cases where the user doesn't grant consent to continue a capture session. To do this, implement Callback#onStop and have your app release any related resources (such as the VirtualDisplay and Surface).

If your app doesn't register this callback, MediaProjection#createVirtualDisplay throws an IllegalStateException when your app invokes it.

Actualización de restricciones que no pertenecen al SDK

Android 14 incluye listas actualizadas de este tipo de interfaces que están basadas en la colaboración con desarrolladores de Android y las pruebas internas más recientes. Siempre que sea posible, nos aseguramos de que las alternativas públicas estén disponibles antes de restringir las interfaces que no pertenecen al SDK.

Si tu app no está orientada a Android 14, es posible que algunos de estos cambios no te afecten de inmediato. Sin embargo, aunque actualmente puedes usar algunas interfaces que no pertenecen al SDK (según el nivel de API objetivo al que esté orientada la app), utilizar cualquier método o campo que no pertenezca al SDK siempre implica un gran riesgo de error para la app.

En caso de no saber con certeza si tu app usa este tipo de interfaces, puedes probarla para verificarlo. Si tu app depende de interfaces que no pertenezcan al SDK, deberías planificar una migración hacia otras alternativas que sí lo hagan. Sin embargo, sabemos que algunas apps tienen casos prácticos válidos para usarlas. Si no encuentras una alternativa al uso de una interfaz que no pertenece al SDK para una función de tu app, deberías solicitar una nueva API pública.

Para obtener más información sobre los cambios implementados en esta versión de Android, consulta Actualizaciones a las restricciones de interfaces que no pertenecen al SDK en Android 14. Para obtener más información sobre interfaces que no pertenecen al SDK en general, consulta Restricciones en interfaces que no pertenecen al SDK.