La plataforma de Android 17 incluye cambios de comportamiento que podrían afectar a tu app.
Los siguientes cambios se aplican a todas las apps cuando se ejecutan en Android 17,
independientemente de targetSdkVersion. Debes probar tu app y, luego, modificarla según corresponda para admitir estos cambios.
Asegúrate también de consultar la lista de cambios de comportamiento que solo afectan a las apps orientadas a Android 17.
Funcionalidad principal
Android 17 (nivel de API 37) incluye los siguientes cambios que modifican o expanden varias funciones principales del sistema Android.
Límites a la memoria de las apps
Android 17 incluye límites a la memoria de las apps según la RAM total del dispositivo para crear un entorno más estable y determinístico para tus apps y los usuarios de Android. Estos límites se enfocan en las fugas de memoria y otros valores atípicos antes de que activen la inestabilidad en todo el sistema, lo que genera interrupciones en la IU, un mayor agotamiento de la batería y el cierre de apps. Si bien anticipamos un impacto mínimo en la gran mayoría de las sesiones de la app, te recomendamos que sigas las prácticas recomendadas para la memoria, incluido el establecimiento de un modelo de referencia para la memoria.
Puedes determinar si la sesión de tu app se vio afectada llamando a getDescription en ApplicationExitInfo. Si tu app se vio afectada, el motivo de salida será REASON_OTHER y la descripción contendrá la cadena "MemoryLimiter:AnonSwap" junto con otra información. También puedes usar la creación de perfiles basada en activadores con
TRIGGER_TYPE_ANOMALY para obtener volcados de montón que se recopilan cuando se alcanza el
límite de memoria.
En la documentación de Administra la memoria de tu app, se proporciona información para ayudarte a diagnosticar los problemas de memoria de tu app y optimizar su consumo de recursos.
Prueba el comportamiento de tu app con las restricciones de memoria
Puedes usar Android Debug Bridge (adb) para ajustar o inhabilitar los límites de memoria en cualquier dispositivo que los imponga. El comando de shell am proporciona tres subcomandos para ajustar los límites de memoria. (Estos comandos no tienen efecto en un dispositivo que no impone límites de memoria).
am memory-limiter ignore <uid>|none|allam memory-limiter manual <pid> <limit>|max|noneam memory-limiter status
ignoreIndica al limitador de memoria que ignore algunos o todos los procesos. Pasar un UID (ID de usuario de Android) indica al limitador de memoria que ignore la aplicación de medidas en todos los procesos asociados con ese UID. También puedes pasar
all(ignorar todas las apps) onone(no ignorar ninguna app). Pasarnoneanula cualquier llamada anterior aam memory-limiter ignore.Si le indicas al limitador de memoria que ignore un UID, puedes aplicar un límite de memoria manual a un proceso dentro de la app llamando a
am memory-limiter manual.manualIndica al sistema que imponga una restricción de memoria en el proceso con el PID (ID de proceso) especificado. La restricción de memoria se especifica como un número entero de MB. Por ejemplo, si se pasa
30, se especifica que el proceso está limitado a 30 MB de memoria. Si pasasmax, se quitan todos los límites de memoria de ese proceso. Si pasasnone, se quitan los límites manuales establecidos en el proceso y se restablece el límite predeterminado del sistema (si corresponde).statusInforma el estado actual del limitador de memoria. El estado incluye los límites de memoria impuestos a los procesos visibles y no visibles.
Privacidad
Android 17 incluye los siguientes cambios para mejorar la privacidad del usuario.
Protección de OTP por SMS
从 Android 17 开始,Android 将扩大对包含动态密码 (OTP) 的短信的保护范围。
在之前的 Android 版本中,此保护机制主要针对 SMS Retriever 格式。对于大多数应用,包含短信检索器哈希的消息延迟了 3 小时才送达。不过,某些应用(例如默认短信处理程序)不受延迟影响,拥有哈希的应用也不受延迟影响。
从 Android 17 开始,此保护措施也适用于 WebOTP 格式的消息。如果应用有权读取短信,但不是 WebOTP 消息的预期接收者(由网域验证确定),则应用在收到消息 3 小时后才能访问该消息。此项变更旨在提高用户安全性,确保只有与消息中提及的网域相关联的应用才能以编程方式读取验证码。
在这 3 小时的延迟期间,SMS_RECEIVED_ACTION 广播会被扣留,短信提供程序数据库查询会被过滤。延迟后,这些应用便可收到短信。此项变更适用于所有应用,无论其目标 API 级别如何。
某些应用(例如默认短信助理应用、已连接设备的配套应用等)不受此延迟的影响。所有依赖读取短信来提取动态密码的应用都应改用 SMS Retriever 或 SMS User Consent API,以确保功能正常运行。
Seguridad
Android 17 incluye las siguientes mejoras en la seguridad de los dispositivos y las apps.
Plan de baja de usesClearTraffic
In a future release, we plan to deprecate the usesCleartextTraffic element.
Apps that need to make unencrypted (HTTP) connections should migrate to
using a network security configuration file, which lets you
specify which domains your app needs to make cleartext connections to.
Be aware that network security configuration files are only supported on API levels 24 and higher. If your app has a minimum API level lower than 24, you should do both of the following:
- Set the
usesCleartextTrafficattribute totrue - Use a network configuration file
If your app's minimum API level is 24 or higher, you can use a network
configuration file and you don't need to set usesCleartextTraffic.
Restringe los otorgamientos de URI implícitos
Currently, if an app launches an intent with a URI that has the action
ACTION_SEND, ACTION_SEND_MULTIPLE, or
ACTION_IMAGE_CAPTURE, the system automatically grants the read and
write URI permissions to the target app. Starting in Android 18, the system will
no longer automatically grant these permissions. For this reason, we recommend
that apps explicitly grant the
relevant URI permissions instead of relying on the system to grant them.
To detect the usage of these intents in your app, use StrictMode with
detectImplicitUriPermissionGrant() to trigger a violation:
Kotlin
val policy = StrictMode.VmPolicy.Builder() .detectImplicitUriPermissionGrant() .penaltyLog() .build() StrictMode.setVmPolicy(policy)
Java
StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder() .detectImplicitUriPermissionGrant() .penaltyLog() .build(); StrictMode.setVmPolicy(policy);
Alternatively, you can monitor for logged exceptions containing the message
Please set the grant explicitly in the app that appears when system implicitly
sets the grant. You can monitor for these logs
using the following adb command:
adb logcat | grep "Please set the grant explicitly in the app"
To explicitly grant the necessary permissions, add the
FLAG_GRANT_READ_URI_PERMISSION flag to ACTION_SEND and
ACTION_SEND_MULTIPLE intents:
Kotlin
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
Java
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Include both FLAG_GRANT_READ_URI_PERMISSION and
FLAG_GRANT_WRITE_URI_PERMISSION flags for
ACTION_IMAGE_CAPTURE intents:
Kotlin
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
Java
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Límites del almacén de claves por app
应用应避免在 Android 密钥库中创建过多密钥,因为密钥库是设备上所有应用的共享资源。从 Android 17 开始,系统会强制限制应用可以拥有的密钥数量。对于以 Android 17(API 级别 37)或更高版本为目标平台的非系统应用,此限制为 50,000 个键;对于所有其他应用,此限制为 200,000 个键。系统应用的密钥数量上限为 20 万,无论其目标 API 级别为何。
如果应用尝试创建超出限制的密钥,则创建会失败,并显示 KeyStoreException。异常的消息字符串包含有关键限制的信息。如果应用对异常调用 getNumericErrorCode(),则返回值取决于应用的目标 API 级别:
- 以 Android 17(API 级别 37)或更高版本为目标平台的应用:
getNumericErrorCode()会返回新的ERROR_TOO_MANY_KEYS值。 - 所有其他应用:
getNumericErrorCode()会返回ERROR_INCORRECT_USAGE。
Bloquea el tráfico de bucle invertido entre perfiles sincronizados
A partir de Android 17, ya no se permite el tráfico de bucle invertido entre perfiles de forma predeterminada. El tráfico de bucle invertido dentro del mismo perfil no se ve afectado. Este cambio se aplica a todas las apps que se ejecutan en Android 17 o versiones posteriores, independientemente del nivel de API al que se orienten.
Experiencia del usuario y la IU del sistema
Android 17 incluye los siguientes cambios que tienen como objetivo crear una experiencia del usuario más coherente e intuitiva.
Restablece la visibilidad predeterminada del IME después de la rotación
Beginning with Android 17, when the device's configuration changes (for example, through rotation), and this is not handled by the app itself, the previous IME visibility is not restored.
If your app undergoes a configuration change that it does not handle, and the app needs the keyboard to be visible after the change, you must explicitly request this. You can make this request in one of the following ways:
- Set the
android:windowSoftInputModeattribute tostateAlwaysVisible. - Programmatically request the soft keyboard in your activity's
onCreate()method, or add theonConfigurationChanged()method.
Intervención humana
Android 17 incluye los siguientes cambios que afectan la forma en que las apps interactúan con los dispositivos de entrada humana, como teclados y paneles táctiles.
Los paneles táctiles envían eventos relativos de forma predeterminada durante la captura del puntero
从 Android 17 开始,如果应用使用 View.requestPointerCapture() 请求指针捕获,并且用户使用触控板,系统会根据用户的轻触操作识别指针移动和滚动动作,并以与捕获的鼠标指针和滚轮移动相同的方式向应用报告这些动作。在大多数情况下,这使得支持捕获鼠标的应用无需为触摸板添加特殊处理逻辑。如需了解详情,请参阅 View.POINTER_CAPTURE_MODE_RELATIVE 的文档。
以前,系统不会尝试识别来自触控板的手势,而是以类似于触摸屏触摸的格式向应用提供原始的绝对手指位置。如果应用仍需要此绝对数据,则应改为使用 View.POINTER_CAPTURE_MODE_ABSOLUTE 调用新的 View.requestPointerCapture(int) 方法。
Medios
Android 17 incluye los siguientes cambios en el comportamiento de los medios.
Refuerzo del audio en segundo plano
从 Android 17 开始,音频框架会对后台音频互动(包括音频播放、音频焦点请求和音量更改 API)施加限制,以确保这些更改是由用户有意发起的。
如果应用在不处于有效生命周期时尝试调用音频 API,音频播放和音量更改 API 会静默失败,而不会抛出异常或提供失败消息。音频焦点 API 失败,结果代码为 AUDIOFOCUS_REQUEST_FAILED。
如需了解详情(包括缓解措施),请参阅后台音频安全加固。
Conectividad
Android 17 incluye los siguientes cambios para mejorar la conectividad de los dispositivos.
Vinculación autónoma para pérdidas de conexión Bluetooth
Android 17 introduces autonomous re-pairing, a system-level enhancement designed to automatically resolve Bluetooth bond loss.
Previously, if a bond was lost, users had to manually navigate to Settings to unpair and then re-pair the peripheral. This feature builds upon the security improvement of Android 16 by allowing the system to re-establish bonds in the background without requiring users to manually navigate to Settings to unpair and re-pair peripherals.
While most apps will not require code changes, developers should be aware of the following behavior changes in Bluetooth stack:
- New pairing context: The
ACTION_PAIRING_REQUESTnow includes theEXTRA_PAIRING_CONTEXTextra which allows apps to distinguish between a standard pairing request and an autonomous system-initiated re-pairing attempt. - Conditional key updates: Existing security keys will only be replaced if the re-pairing is successful and new connection meets or exceeds the security level of the previous bond.
- Modified intent timing: The
ACTION_KEY_MISSINGintent is now broadcast only if the autonomous re-pairing attempt fails. This reduces unnecessary error handling in the app if the system successfully recovers the bond in the background. - User notification: The system manages re-pairing via new UI notifications and dialogs. Users will be prompted to confirm the re-pairing attempt to ensure they are aware of the reconnection.
Peripheral device manufacturers and companion app developers should verify that hardware and app gracefully handle bond transitions. To test this behavior, simulate a remote bond loss using either of the following methods:
- Manually remove the bond information from the peripheral device
- Manually unpair the device in: Settings > Connected devices