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 que se segmentan para 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
If your app targets Android 14 (API level 34) or higher, it must specify at least one foreground service type for each foreground service within your app. You should choose a foreground service type that represents your app's use case. The system expects foreground services that have a particular type to satisfy a particular use case.
If a use case in your app isn't associated with any of these types, it's strongly recommended that you migrate your logic to use WorkManager or user-initiated data transfer jobs.
Aplicación del permiso BLUETOOTH_CONNECT en BluetoothAdapter
En Android 14, se 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 la app declare BLUETOOTH_CONNECT en su 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.MatcherarrojeIllegalArgumentException, 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 marcaDISALLOW_INVALID_GROUP_REFERENCEcon 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 unaIllegalArgumentExceptiondurante deserialización. Para habilitar o inhabilitar este cambio durante las pruebas, activa o desactiva la marcaENABLE_STRICT_VALIDATIONcon las herramientas del marco de compatibilidad. - Problemas de ProGuard: En algunos casos, la adición de la clase
java.lang.ClassValuegenera 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 siClass.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 clasejava.lang.ClassValuedisponible, estas optimizaciones podrían quitar el métodocomputeValuede las clases derivadas dejava.lang.ClassValue.
JobScheduler refuerza el comportamiento de las devoluciones 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
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 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
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
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
Las apps y los servicios que se orientan a Android 14 (nivel de API 34) o versiones posteriores y usan receptores registrados en el contexto deben especificar una marca para indicar si el receptor se debe exportar a todas las otras apps en el dispositivo: RECEIVER_EXPORTED o RECEIVER_NOT_EXPORTED, respectivamente.
Este requisito ayuda a proteger las apps de las vulnerabilidades de seguridad aprovechando las funciones de estos receptores que se introdujeron en Android 13.
Excepción para receptores que solo reciben transmisiones del sistema
Si tu app registra un receptor solo para las transmisiones del sistema a través de métodos Context#registerReceiver, como Context#registerReceiver(), no debería especificar una marca cuando registra el receptor.
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
For apps targeting Android 14 (API level 34) or higher, the system further restricts when apps are allowed to start activities from the background:
- When an app sends a
PendingIntentusingPendingIntent#send()or similar methods, the app must opt in if it wants to grant its own background activity launch privileges to start the pending intent. To opt in, the app should pass anActivityOptionsbundle withsetPendingIntentBackgroundActivityStartMode(MODE_BACKGROUND_ACTIVITY_START_ALLOWED). - When a visible app binds a service of another app that's in the background
using the
bindService()method, the visible app must now opt in if it wants to grant its own background activity launch privileges to the bound service. To opt in, the app should include theBIND_ALLOW_ACTIVITY_STARTSflag when calling thebindService()method.
These changes expand the existing set of restrictions to protect users by preventing malicious apps from abusing APIs to start disruptive activities from the background.
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().
Se requiere el consentimiento del usuario para cada sesión de captura de MediaProjection
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 caches the
Intentthat is returned fromMediaProjectionManager#createScreenCaptureIntent, and passes it multiple times toMediaProjectionManager#getMediaProjection. - Your app invokes
MediaProjection#createVirtualDisplaymultiple times on the sameMediaProjectioninstance.
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:
- Invoke
VirtualDisplay#resizewith the new width and height. - Provide a new
Surfacewith the new width and height toVirtualDisplay#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.
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.