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

Si tu app está orientada a Android 14 (nivel de API 34) o versiones posteriores, debe especificar mínimo un tipo de servicio en primer plano para cada servicio de este tipo. Debes elegir un tipo de servicio en primer plano que represente el caso de uso de tu app. El sistema espera que los servicios en primer plano que tengan un tipo particular satisfagan un caso de uso determinado.

Si un caso de uso en tu app no está asociado con ninguno de estos tipos, te recomendamos que migres la lógica para usar WorkManager o tareas de transferencia de datos que inicia el usuario..

Aplicación forzosa 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 devolución de llamada y de 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 tarjetas

For apps targeting 14 and higher, TileService#startActivityAndCollapse(Intent) is deprecated and now throws an exception when called. If your app launches activities from tiles, use TileService#startActivityAndCollapse(PendingIntent) instead.

Privacidad

Acceso parcial a fotos y videos

Android 14 引入了“已选照片访问权限”,让用户可以向应用授予对其媒体库中特定图片和视频的访问权限,而不是授予对给定类型的所有媒体的访问权限。

只有当您的应用以 Android 14(API 级别 34)或更高版本为目标平台时,此更改才会启用。如果您尚未使用照片选择器,我们建议您在应用中实现照片选择器,以提供一致的图片和视频选择体验,同时增强用户隐私保护,而无需请求任何存储权限。

如果您使用存储权限维护自己的图库选择器,并且需要对实现保持完全控制,请调整实现以使用新的 READ_MEDIA_VISUAL_USER_SELECTED 权限。如果您的应用不使用新权限,系统会以兼容模式运行您的应用。

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

对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,Android 会通过以下方式限制应用向内部应用组件发送隐式 intent:

  • 隐式 intent 只能传送到导出的组件。应用必须使用显式 intent 传送到未导出的组件,或将该组件标记为已导出。
  • 如果应用通过未指定组件或软件包的 intent 创建可变待处理 intent,系统会抛出异常。

这些变更可防止恶意应用拦截意在供应用内部组件使用的隐式 intent。

例如,下面是可以在应用的清单文件中声明的 intent 过滤器

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

如果应用尝试使用隐式 intent 启动此 activity,则系统会抛出 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"));

如需启动非导出的 activity,应用应改用显式 intent:

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

En el caso de las apps orientadas a Android 14 (nivel de API 34) y versiones posteriores, el sistema restringe aún más el momento en que las apps pueden iniciar actividades en segundo plano:

  • Cuando una app envía un objeto PendingIntent con PendingIntent#send() o métodos similares, esta ahora debe aceptar si desea otorgar sus propios privilegios de inicio de la actividad en segundo plano para iniciar el intent pendiente. Para hacerlo, la app debe pasar un paquete ActivityOptions con setPendingIntentBackgroundActivityStartMode(MODE_BACKGROUND_ACTIVITY_START_ALLOWED).
  • Cuando una app visible vincula un servicio de otra app que está en segundo plano con el método bindService(), esta ahora debe aceptar si desea otorgar sus propios privilegios de inicio de la actividad en segundo plano para el servicio vinculado. Para hacerlo, la app debe incluir la marca BIND_ALLOW_ACTIVITY_STARTS cuando llame al método bindService().

Estos cambios expanden el conjunto existente de restricciones para proteger a los usuarios, ya que evitan que las apps maliciosas abusen de las APIs para iniciar actividades disruptivas en segundo plano.

Salto de directorio del archivo ZIP

En el caso de las apps que se orientan a Android 14 (nivel de API 34) o versiones posteriores, Android evita la vulnerabilidad de salto de directorio del archivo ZIP de la siguiente manera: ZipFile(String) y ZipInputStream.getNextEntry() arroja una ZipException si los nombres de las entradas de los archivos ZIP contienen ".." o comienzan con "/".

Las apps pueden inhabilitar esta validación mediante una llamada a 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.

如需详细了解此 Android 版本中的变更,请参阅 Android 14 中有关限制非 SDK 接口的更新。如需全面了解有关非 SDK 接口的详细信息,请参阅对非 SDK 接口的限制