Características y API

Android 16 incluye excelentes funciones y APIs para desarrolladores. En las siguientes secciones, se resumen estas funciones para ayudarte a comenzar a usar las APIs relacionadas.

Para obtener una lista detallada de las APIs nuevas, modificadas y quitadas, consulta el informe de diferencias de API. Para obtener detalles sobre las nuevas APIs, consulta la referencia de la API de Android. Las nuevas APIs están destacadas para que sea más fácil identificarlas.

También debes revisar las áreas en las que los cambios de la plataforma podrían afectar a tus apps. Para obtener más información, consulta las siguientes páginas:

Funcionalidad principal

Android incluye nuevas APIs que expanden las funciones principales del sistema Android.

Dos lanzamientos de la API de Android en 2025

  • This preview is for the next major release of Android with a planned launch in Q2 of 2025. This release is similar to all of our API releases in the past, where we can have planned behavior changes that are often tied to a targetSdkVersion.
  • We're planning the major release a quarter earlier (Q2 rather than Q3 in prior years) to better align with the schedule of device launches across our ecosystem, so more devices can get the major release of Android sooner. With the major release coming in Q2, you'll need to do your annual compatibility testing a few months earlier than in previous years to make sure your apps are ready.
  • We plan to have another release in Q4 of 2025 which also will include new developer APIs. The Q2 major release will be the only release in 2025 to include planned behavior changes that could affect apps.

In addition to new developer APIs, the Q4 minor release will pick up feature updates, optimizations, and bug fixes; it will not include any app-impacting behavior changes.

Timeline view of Android releases in 2025, noting that the 25Q2
       release is a major release and the 25Q4 release is a minor release.

We'll continue to have quarterly Android releases. The Q1 and Q3 updates in-between the API releases will provide incremental updates to help ensure continuous quality. We're actively working with our device partners to bring the Q2 release to as many devices as possible.

Using new APIs with major and minor releases

Guarding a code block with a check for API level is done today using the SDK_INT constant with VERSION_CODES. This will continue to be supported for major Android releases.

if (SDK_INT >= VERSION_CODES.BAKLAVA) {
  // Use APIs introduced in Android 16
}

The new SDK_INT_FULL constant can be used for API checks against both major and minor versions with the new VERSION_CODES_FULL enumeration.

if (SDK_INT_FULL >= VERSION_CODES_FULL.[MAJOR or MINOR RELEASE]) {
  // Use APIs introduced in a major or minor release
}

You can also use the Build.getMinorSdkVersion() method to get just the minor SDK version.

val minorSdkVersion = Build.getMinorSdkVersion(VERSION_CODES_FULL.BAKLAVA)

These APIs have not yet been finalized and are subject to change, so please send us feedback if you have any concerns.

Experiencia del usuario y IU del sistema

Android 16 les brinda a los desarrolladores de apps y a los usuarios más control y flexibilidad para configurar sus dispositivos según sus necesidades.

Notificaciones centradas en el progreso

Android 16 引入了以进度为中心的通知,可帮助用户顺畅地跟踪用户发起的端到端历程。

Notification.ProgressStyle 是一种新的通知样式,可让您创建以进度为中心的通知。主要用例包括共享车辆、送货和导航。在 Notification.ProgressStyle 类中,您可以使用细分来表示用户体验历程中的状态和里程碑。

To learn more, see the Progress-centric notifications documentation page.

锁屏上显示的以进度为中心的通知。
在通知栏中显示的以进度为中心的通知。

Actualizaciones del gesto atrás predictivo

Android 16 添加了新 API,可帮助您在手势导航中启用预测性返回系统动画,例如“返回主屏幕”动画。通过使用新的 PRIORITY_SYSTEM_NAVIGATION_OBSERVER 注册 onBackInvokedCallback,您的应用可以在系统处理返回导航时接收常规的 onBackInvoked 调用,而不会影响正常的返回导航流程。

Android 16 还添加了 finishAndRemoveTaskCallback()moveTaskToBackCallback。通过向 OnBackInvokedDispatcher 注册这些回调,系统可以在调用返回手势时触发特定行为并播放相应的提前动画。

Tecnología táctil más enriquecida

Android has exposed control over the haptic actuator ever since its inception.

Android 11 added support for more complex haptic effects that more advanced actuators could support through VibrationEffect.Compositions of device-defined semantic primitives.

Android 16 adds haptic APIs that let apps define the amplitude and frequency curves of a haptic effect while abstracting away differences between device capabilities.

Productividad y herramientas para desarrolladores

Si bien la mayor parte de nuestro trabajo para mejorar tu productividad se centra en herramientas como Android Studio, Jetpack Compose y las bibliotecas de Android Jetpack, siempre buscamos formas en la plataforma para ayudarte a materializar tu visión.

Manejo de contenido para fondos animados

在 Android 16 中,动态壁纸框架将获得一个新的 content API,以应对由用户驱动的动态壁纸带来的挑战。目前,包含用户提供的内容的实时壁纸需要复杂的服务专用实现。Android 16 引入了 WallpaperDescriptionWallpaperInstance。借助 WallpaperDescription,您可以识别同一服务中的动态壁纸的不同实例。例如,如果某张壁纸同时在主屏幕和锁定屏幕上显示,则这两种情况下显示的内容可能各不相同。壁纸选择器和 WallpaperManager 会使用此元数据更好地向用户呈现壁纸,从而简化创建多样化个性化动态壁纸体验的过程。

Rendimiento y batería

Android 16 presenta APIs que ayudan a recopilar estadísticas sobre tus apps.

Generación de perfiles activada por el sistema

ProfilingManager 在 Android 15 中添加,让应用能够在现场使用 Perfetto 请求收集性能数据。不过,由于此性能分析必须从应用启动,因此应用很难或根本无法捕获启动或 ANR 等关键流程。

为此,Android 16 向 ProfilingManager 引入了系统触发的性能分析。应用可以注册接收特定触发器(例如冷启动 reportFullyDrawn 或 ANR)轨迹的兴趣,然后系统会代表应用启动和停止轨迹。轨迹完成后,结果会传送到应用的数据目录。

Inicia el componente en ApplicationStartInfo

ApplicationStartInfo 在 Android 15 中添加,可让应用查看进程启动原因、启动类型、启动时间、节流和其他实用诊断数据。Android 16 添加了 getStartComponent(),用于区分触发启动的组件类型,这有助于优化应用的启动流程。

Mejor introspección de trabajos

JobScheduler#getPendingJobReason() API 会返回作业可能处于待处理状态的原因。不过,作业处于待处理状态的原因可能有多种。

在 Android 16 中,我们引入了一个新 API JobScheduler#getPendingJobReasons(int jobId),该 API 会返回作业处于待处理状态的多种原因,包括开发者设置的显式约束条件和系统设置的隐式约束条件。

我们还引入了 JobScheduler#getPendingJobReasonsHistory(int jobId),用于返回最新约束条件更改的列表。

我们建议您使用该 API 来调试作业可能无法执行的原因,尤其是在您发现某些任务的成功率降低或某些作业完成延迟存在 bug 时。例如,未能在后台更新微件,或在应用启动之前未能调用预加载作业。

这还有助于您更好地了解某些作业是否因系统定义的约束条件而无法完成,而不是因明确设置的约束条件而无法完成。

Frecuencia de actualización adaptativa

Adaptive refresh rate (ARR), introduced in Android 15, enables the display refresh rate on supported hardware to adapt to the content frame rate using discrete VSync steps. This reduces power consumption while eliminating the need for potentially jank-inducing mode-switching.

Android 16 introduces hasArrSupport() and getSuggestedFrameRate(int) while restoring getSupportedRefreshRates() to make it easier for your apps to take advantage of ARR. RecyclerView 1.4 internally supports ARR when it is settling from a fling or smooth scroll, and we're continuing our work to add ARR support into more Jetpack libraries. This frame rate article covers many of the APIs you can use to set the frame rate so that your app can directly use ARR.

APIs de Headroom en ADPF

SystemHealthManager 引入了 getCpuHeadroomgetGpuHeadroom API,旨在为游戏和资源密集型应用提供可用 CPU 和 GPU 资源的估算值。通过这些方法,您可以评估应用或游戏如何以最佳方式改善系统运行状况,尤其是在与用于检测热节流的其他 Android 动态性能框架 (ADPF) API 搭配使用时。

在受支持的设备上使用 CpuHeadroomParamsGpuHeadroomParams,您可以自定义用于计算余量的时间范围,并在平均资源可用性或最低资源可用性之间进行选择。这有助于您相应地减少 CPU 或 GPU 资源用量,从而提升用户体验并延长电池续航时间。

Accesibilidad

Android 16 agrega nuevas APIs y funciones de accesibilidad que pueden ayudarte a llevar tu app a todos los usuarios.

APIs de accesibilidad mejoradas

Android 16 添加了其他 API 来增强界面语义,这有助于为依赖于无障碍服务(例如 TalkBack)的用户提高一致性。

向 TtsSpan 添加了时长

Android 16 使用 TYPE_DURATION 扩展了 TtsSpan,其中包含 ARG_HOURSARG_MINUTESARG_SECONDS。这样,您就可以直接为时长添加注释,确保通过 TalkBack 等服务获得准确且一致的文本转语音输出。

支持具有多个标签的元素

Android 目前允许界面元素从其他元素派生其无障碍功能标签,现在还支持关联多个标签,这是 Web 内容中常见的情况。通过在 AccessibilityNodeInfo 中引入基于列表的 API,Android 可以直接支持这些多标签关系。在进行这项更改的过程中,我们已弃用 AccessibilityNodeInfo#setLabeledBy#getLabeledBy,改用 #addLabeledBy#removeLabeledBy#getLabeledByList

改进了对可展开元素的支持

Android 16 添加了无障碍功能 API,可让您传达互动元素(例如菜单和展开式列表)的展开或收起状态。通过使用 setExpandedState 设置展开状态,并使用 CONTENT_CHANGE_TYPE_EXPANDED 内容更改类型调度 TYPE_WINDOW_CONTENT_CHANGED AccessibilityEvents,您可以确保 TalkBack 等屏幕阅读器会读出状态更改,从而提供更直观、更包容的用户体验。

不确定进度条

Android 16 添加了 RANGE_TYPE_INDETERMINATE,让您可以为确定性和不确定性 ProgressBar 微件公开 RangeInfo,从而让 TalkBack 等服务能够更一致地为进度指示器提供反馈。

三态复选框

Android 16 中的新 AccessibilityNodeInfo getCheckedsetChecked(int) 方法现在除了“已选中”和“未选中”之外,还支持“部分选中”状态。此字段取代了已废弃的布尔值 isCheckedsetChecked(boolean)

补充说明

如果无障碍服务提供关于 ViewGroup 的说明,则会将来自其子视图的内容标签合并在一起。如果您为 ViewGroup 提供 contentDescription,无障碍服务会假定您还要覆盖不可聚焦的子视图的说明。如果您想为下拉菜单(例如“字体系列”)添加标签,同时保留当前的无障碍功能选择(例如“Roboto”),这可能会造成问题。Android 16 添加了 setSupplementalDescription,以便您提供用于提供 ViewGroup 相关信息的文本,而不会覆盖其子项中的信息。

必填表单字段

Android 16 向 AccessibilityNodeInfo 添加了 setFieldRequired,以便应用可以告知无障碍服务需要输入表单字段。对于填写各种类型表单的用户来说,这是一个重要的场景,即使是简单的必填条款及条件复选框,也能帮助用户始终如一地识别必填字段并在必填字段之间快速导航。

Teléfono como entrada de micrófono para llamadas de voz con audífonos LEA

Android 16 新增了一项功能,让 LE Audio 助听器用户能够在助听器的内置麦克风和手机上的麦克风之间切换,以进行语音通话。在嘈杂的环境或助听器麦克风可能无法正常工作的其他情况下,这会很有帮助。

Controles de volumen ambiental para audífonos LEA

Android 16 adds the capability for users of LE Audio hearing aids to adjust the volume of ambient sound that is picked up by the hearing aid's microphones. This can be helpful in situations where background noise is too loud or too quiet.

Cámara

Android 16 mejora la compatibilidad con los usuarios de cámaras profesionales, lo que permite una exposición automática híbrida junto con ajustes precisos de temperatura de color y tono. Un nuevo indicador de modo nocturno ayuda a tu app a saber cuándo cambiar de una sesión de cámara con modo nocturno a una sin él y viceversa. Las nuevas acciones de Intent facilitan la captura de fotos en movimiento y seguimos mejorando las imágenes UltraHDR con compatibilidad con la codificación HEIF y nuevos parámetros del borrador del estándar ISO 21496-1.

Exposición automática híbrida

Android 16 agrega nuevos modos de exposición automática híbridos a Camera2, lo que te permite controlar manualmente aspectos específicos de la exposición y, al mismo tiempo, permitir que el algoritmo de exposición automática (AE) controle el resto. Puedes controlar ISO + AE y tiempo de exposición + AE, lo que proporciona una mayor flexibilidad en comparación con el enfoque actual en el que tienes control manual completo o dependes por completo de la exposición automática.

public void setISOPriority() {
  ...
  int[] availablePriorityModes =
     mStaticInfo.getCharacteristics().get(CameraCharacteristics.
     COLOR_AE_AVAILABLE_PRIORITY_MODES);
  ...
  // Turn on AE mode to set priority mode
  reqBuilder.set(CaptureRequest.CONTROL_AE_MODE,
      CameraMetadata.CONTROL_AE_MODE_ON);
  reqBuilder.set(CaptureRequest.CONTROL_AE_PRIORITY_MODE,
      CameraMetadata.CONTROL_AE_PRIORITY_MODE_SENSOR_SENSITIVITY);
  reqBuilder.set(CaptureRequest.SENSOR_SENSITIVITY,
      TEST_SENSITIVITY_VALUE);
  CaptureRequest request = reqBuilder.build();
  ...
}

Ajustes precisos de temperatura de color y tono

Android 16 adds camera support for fine color temperature and tint adjustments to better support professional video recording applications. In previous Android versions, you could control white balance settings through CONTROL_AWB_MODE, which contains options limited to a preset list, such as Incandescent, Cloudy, and Twilight. The COLOR_CORRECTION_MODE_CCT enables the use of COLOR_CORRECTION_COLOR_TEMPERATURE and COLOR_CORRECTION_COLOR_TINT for precise adjustments of white balance based on the correlated color temperature.

fun setCCT() {
    // ... (Your existing code before this point) ...

    val colorTemperatureRange: Range<Int> =
        mStaticInfo.characteristics[CameraCharacteristics.COLOR_CORRECTION_COLOR_TEMPERATURE_RANGE]

    // Set to manual mode to enable CCT mode
    reqBuilder[CaptureRequest.CONTROL_AWB_MODE] = CameraMetadata.CONTROL_AWB_MODE_OFF
    reqBuilder[CaptureRequest.COLOR_CORRECTION_MODE] = CameraMetadata.COLOR_CORRECTION_MODE_CCT
    reqBuilder[CaptureRequest.COLOR_CORRECTION_COLOR_TEMPERATURE] = 5000
    reqBuilder[CaptureRequest.COLOR_CORRECTION_COLOR_TINT] = 30

    val request: CaptureRequest = reqBuilder.build()

    // ... (Your existing code after this point) ...
}

The following examples show how a photo would look after applying different color temperature and tint adjustments:

The original image with no color temperature or tint adjustments applied.
The image with color temperature adjusted to 3000.
The image with color temperature adjusted to 7000.


The image with tint levels lowered by 50.
The image with tint levels raised by 50.

Detección de escenas del modo nocturno de la cámara

为了帮助应用了解何时切换到夜间模式相机会话以及何时从夜间模式相机会话切换出,Android 16 添加了 EXTENSION_NIGHT_MODE_INDICATOR。如果受支持,则可在 Camera2 内的 CaptureResult 中使用。

这是我们在Instagram 如何让用户拍出令人惊艳的低光照片博文中提到的即将推出的 API。该博文提供了有关如何实现夜间模式的实用指南,并附有一份案例研究,该案例研究将应用内夜间模式照片质量的提升与通过应用内相机分享的照片数量的增加联系起来。

Acciones de intent de captura de fotos en movimiento

Android 16 添加了标准 intent 操作 ACTION_MOTION_PHOTO_CAPTUREACTION_MOTION_PHOTO_CAPTURE_SECURE,用于请求相机应用拍摄动态照片并将其返回。

您必须传递额外的 EXTRA_OUTPUT 来控制将图片写入的位置,或者通过 Intent.setClipData(ClipData) 传递 Uri。如果您未设置 ClipData,系统会在调用 Context.startActivity(Intent) 时将其复制到该位置。

动态照片示例,显示静态图片和动态播放画面。

Mejoras de imagen UltraHDR

标准动态范围 (SDR) 与高动态范围 (HDR) 图片质量对比示意图。

Android 16 继续致力于通过 UltraHDR 图片提供出色的图片质量。它添加了对 HEIC 文件格式的 UltraHDR 图片的支持。这些图片将获得 ImageFormat 类型 HEIC_ULTRAHDR,并包含类似于现有 UltraHDR JPEG 格式的嵌入式增益图。我们还在努力为 UltraHDR 添加 AVIF 支持,敬请期待。

此外,Android 16 在 UltraHDR 中实现了 ISO 21496-1 草稿标准中的其他参数,包括能够获取和设置应应用增益图算法的色彩空间,以及支持使用 SDR 增益图的 HDR 编码基础图片。

Gráficos

Android 16 incluye las mejoras gráficas más recientes, como los efectos gráficos personalizados con AGSL.

Efectos gráficos personalizados con AGSL

Android 16 adds RuntimeColorFilter and RuntimeXfermode, allowing you to author complex effects like Threshold, Sepia, and Hue Saturation and apply them to draw calls. Since Android 13, you've been able to use AGSL to create custom RuntimeShaders that extend Shader. The new API mirrors this, adding an AGSL-powered RuntimeColorFilter that extends ColorFilter, and a Xfermode effect that lets you implement AGSL-based custom compositing and blending between source and destination pixels.

private val thresholdEffectString = """
    uniform half threshold;

    half4 main(half4 c) {
        half luminosity = dot(c.rgb, half3(0.2126, 0.7152, 0.0722));
        half bw = step(threshold, luminosity);
        return bw.xxx1 * c.a;
    }"""

fun setCustomColorFilter(paint: Paint) {
   val filter = RuntimeColorFilter(thresholdEffectString)
   filter.setFloatUniform(0.5);
   paint.colorFilter = filter
}

Conectividad

Android 16 actualiza la plataforma para darle a tu app acceso a los avances más recientes en las tecnologías inalámbricas y de comunicación.

Rango con seguridad mejorada

Android 16 adds support for robust security features in Wi-Fi location on supported devices with Wi-Fi 6's 802.11az, allowing apps to combine the higher accuracy, greater scalability, and dynamic scheduling of the protocol with security enhancements including AES-256-based encryption and protection against MITM attacks. This allows it to be used more safely in proximity use cases, such as unlocking a laptop or a vehicle door. 802.11az is integrated with the Wi-Fi 6 standard, leveraging its infrastructure and capabilities for wider adoption and easier deployment.

APIs de rango genérico

Android 16 includes the new RangingManager, which provides ways to determine the distance and angle on supported hardware between the local device and a remote device. RangingManager supports the usage of a variety of ranging technologies such as BLE channel sounding, BLE RSSI-based ranging, Ultra Wideband, and Wi-Fi round trip time.

Contenido multimedia

Android 16 incluye una variedad de funciones que mejoran la experiencia multimedia.

Mejoras en el selector de fotos

照片选择器为用户提供了一种安全的内置授权方式,让用户可以向应用授予对本地存储空间和云端存储空间中所选图片和视频的访问权限,而不是对整个媒体库的访问权限。通过 Google 系统更新Google Play 服务组合使用模块化系统组件,该工具向后支持到 Android 4.4(API 级别 19)。只需几行代码即可与相关的 Android Jetpack 库集成。

Android 16 对照片选择器进行了以下改进:

  • 嵌入式照片选择器新 API,可让应用将照片选择器嵌入其视图层次结构中。这样,它就感觉像是应用中更为集成的一部分,同时仍可利用进程隔离功能,让用户能够选择媒体,而无需应用拥有过于宽泛的权限。为了最大限度地提高跨平台版本的兼容性并简化集成,如果您想集成嵌入式照片选择器,则需要使用即将推出的 Android Jetpack 库。
  • 照片选择器中的云搜索新的 API 可让 Android 照片选择器从云端媒体提供商中进行搜索。照片选择器中的搜索功能即将推出。

Video profesional avanzado

Android 16 introduce la compatibilidad con el códec de video profesional avanzado (APV), que está diseñado para usarse en la grabación y postproducción de video de alta calidad a nivel profesional.

El estándar de códec APV tiene las siguientes características:

  • Calidad de video sin pérdida perceptiva (cercana a la calidad de video sin procesar)
  • Codificación solo dentro de la trama de baja complejidad y alta capacidad de procesamiento (sin predicción de dominio de píxeles) para admitir mejor los flujos de trabajo de edición
  • Compatibilidad con un rango de tasa de bits alto de hasta unos pocos Gbps para contenido de resolución 2K, 4K y 8K, habilitado por un esquema de codificación de entropía ligero
  • Recorte de fotogramas para contenido envolvente y para habilitar la codificación y decodificación en paralelo
  • Compatibilidad con varios formatos de muestreo de crominancia y profundidades de bits
  • Compatibilidad con varias decodificaciones y recodificaciones sin degradación severa de la calidad visual
  • Compatibilidad con videos multivista y auxiliares, como profundidad, alfa y vista previa
  • Compatibilidad con HDR10/10+ y metadatos definidos por el usuario

Se proporciona una implementación de referencia de APV a través del proyecto OpenAPV. Android 16 implementará la compatibilidad con el perfil APV 422-10 que proporciona muestreo de color YUV 422 junto con codificación de 10 bits y para tasas de bits objetivo de hasta 2 Gbps.

Privacidad

Android 16 incluye una variedad de funciones que ayudan a los desarrolladores de apps a proteger la privacidad del usuario.

Actualizaciones de Health Connect

Health Connect in the developer preview adds ACTIVITY_INTENSITY, a new data type defined according to World Health Organization guidelines around moderate and vigorous activity. Each record requires the start time, the end time and whether the activity intensity is moderate or vigorous.

Health Connect also contains updated APIs supporting health records. This allows apps to read and write medical records in FHIR format with explicit user consent. This API is in an early access program. If you'd like to participate, sign up to be part of our early access program.

Privacy Sandbox en Android

Android 16 incorporates the latest version of the Privacy Sandbox on Android, part of our ongoing work to develop technologies where users know their privacy is protected. Our website has more about the Privacy Sandbox on Android developer beta program to help you get started. Check out the SDK Runtime which allows SDKs to run in a dedicated runtime environment separate from the app they are serving, providing stronger safeguards around user data collection and sharing.

Seguridad

Android 16 incluye funciones que te ayudan a mejorar la seguridad de tu app y a proteger sus datos.

API de uso compartido de claves

Android 16 添加了一些 API,这些 API 支持与其他应用共享对 Android Keystore 密钥的访问权限。新的 KeyStoreManager 类支持按应用 uid 授予撤消对密钥的访问权限,并包含一个供应用访问共享密钥的 API。

Factores de forma de los dispositivos

Android 16 les brinda a tus apps la compatibilidad para aprovechar al máximo los factores de forma de Android.

Marco de trabajo estandarizado de calidad de imagen y audio para TVs

El nuevo paquete MediaQuality en Android 16 expone un conjunto de APIs estandarizadas para acceder a perfiles de audio y de imagen, y a la configuración relacionada con el hardware. Esto permite que las apps de transmisión consulten perfiles y los apliquen al contenido multimedia de forma dinámica:

  • Las películas masterizadas con un rango dinámico más amplio requieren una mayor precisión de color para ver detalles sutiles en las sombras y adaptarse a la luz ambiental, por lo que puede ser apropiado un perfil que prefiera la precisión del color en lugar del brillo.
  • Los eventos deportivos en vivo suelen masterizarse con un rango dinámico estrecho, pero a menudo se miran a la luz del día, por lo que un perfil que prefiera el brillo sobre la precisión del color puede brindar mejores resultados.
  • El contenido totalmente interactivo requiere un procesamiento mínimo para reducir la latencia y tasas de fotogramas más altas, por lo que muchas TVs se envían con un perfil de juego.

La API permite que las apps cambien entre perfiles y que los usuarios disfruten de la sintonización de TVs compatibles para que se adapten mejor a su contenido.

Internacionalización

Android 16 agrega funciones y capacidades que complementan la experiencia del usuario cuando se usa un dispositivo en diferentes idiomas.

Texto vertical

Android 16 添加了对垂直渲染和测量文本的低级支持,以便为库开发者提供基本的垂直书写支持。这对于日语等通常使用竖向书写系统的语言特别有用。Paint 类中添加了一个新标志 VERTICAL_TEXT_FLAG。使用 Paint.setFlags 设置此标志后,Paint 的文本测量 API 将报告垂直进度,而不是水平进度,并且 Canvas 将垂直绘制文本。

val text = "「春は、曙。」"
Box(
    Modifier.padding(innerPadding).background(Color.White).fillMaxSize().drawWithContent {
        drawIntoCanvas { canvas ->
            val paint = Paint().apply { textSize = 64.sp.toPx() }
            // Draw text vertically
            paint.flags = paint.flags or VERTICAL_TEXT_FLAG
            val height = paint.measureText(text)
            canvas.nativeCanvas.drawText(
                text,
                0,
                text.length,
                size.width / 2,
                (size.height - height) / 2,
                paint
            )
        }
    }
) {}

Personalización del sistema de medición

Los usuarios ahora pueden personalizar su sistema de medición en las preferencias regionales de la configuración. La preferencia del usuario se incluye como parte del código de configuración regional, por lo que puedes registrar un BroadcastReceiver en ACTION_LOCALE_CHANGED para controlar los cambios de configuración regional cuando cambien las preferencias regionales.

El uso de formatos puede ayudar a que coincidan con la experiencia local. Por ejemplo, "0.5 in" en inglés (Estados Unidos) es "12.7 mm" para un usuario que configuró su teléfono en inglés (Dinamarca) o que usa su teléfono en inglés (Estados Unidos) con el sistema métrico como preferencia de sistema de medición.

Para encontrar esta configuración, abre la app de Configuración y dirígete a Sistema > Idiomas y región.