Visão geral de recursos e APIs

O Android 15 apresenta ótimos recursos e APIs para desenvolvedores. As seções a seguir resumem esses recursos para ajudar você a começar a usar as APIs relacionadas.

Para uma lista detalhada das APIs adicionadas, modificadas e removidas, leia o Relatório de diferenças da API. Para saber mais sobre as APIs adicionadas, acesse a Referência da API do Android. No Android 15, procure as APIs que foram adicionadas no nível 35 da API. Para saber mais sobre as áreas em que as mudanças na plataforma podem afetar seus apps, confira as mudanças de comportamento do Android 15 para apps destinados ao Android 15 e para todos os apps.

Câmera e mídia

O Android 15 inclui vários recursos que melhoram a experiência de câmera e mídia e oferecem acesso a ferramentas e hardware para ajudar os criadores de conteúdo a dar vida às ideias no Android.

Para saber mais sobre os recursos mais recentes e as soluções para desenvolvedores de mídia e câmera do Android, consulte a palestra Como criar experiências modernas de mídia e câmera do Android do Google I/O.

Aumento do modo pouca luz

Android 15 introduces Low Light Boost, an auto-exposure mode available to both Camera 2 and the night mode camera extension. Low Light Boost adjusts the exposure of the Preview stream in low-light conditions. This is different from how the night mode camera extension creates still images, because night mode combines a burst of photos to create a single, enhanced image. While night mode works very well for creating a still image, it can't create a continuous stream of frames, but Low Light Boost can. Thus, Low Light Boost enables camera capabilities, such as:

  • Providing an enhanced image preview, so users are better able to frame their low-light pictures
  • Scanning QR codes in low light

If you enable Low Light Boost, it automatically turns on when there's a low light level, and turns off when there's more light.

Apps can record off the Preview stream in low-light conditions to save a brightened video.

For more information, see Low Light Boost.

Controles da câmera no app

Android 15 adds an extension for more control over the camera hardware and its algorithms on supported devices:

  • Advanced flash strength adjustments enabling precise control of flash intensity in both SINGLE and TORCH modes while capturing images.

Controle de headroom de HDR

Android 15 会选择适合底层设备功能和面板位深的 HDR 余量。对于包含大量 SDR 内容的网页(例如显示单个 HDR 缩略图的消息应用),此行为最终可能会对 SDR 内容的感知亮度产生不利影响。在 Android 15 中,您可以使用 setDesiredHdrHeadroom 控制 HDR 余量,以便在 SDR 内容和 HDR 内容之间取得平衡。

左侧屏幕上的 SDR 界面元素的亮度似乎比右侧屏幕上的亮度更均匀,这模拟了混合 HDR 和 SDR 内容时可能出现的余量问题。通过调整 HDR 余量,您可以在 SDR 和 HDR 内容之间实现更好的平衡。

Controle de loudness

Android 15 引入了对 CTA-2075 响度标准的支持,可帮助您避免音频响度不一致,并确保用户在切换内容时不必不断调整音量。系统利用输出设备(头戴式耳机和扬声器)的已知特性以及 AAC 音频内容中提供的响度元数据,智能调整音频响度和动态范围压缩级别。

如需启用此功能,您需要确保 AAC 内容中提供响度元数据,并在应用中启用平台功能。为此,您可以通过使用关联的 AudioTrack 中的音频会话 ID 调用其 create 工厂方法来实例化 LoudnessCodecController 对象;这会自动开始应用音频更新。您可以传递 OnLoudnessCodecUpdateListener 来修改或过滤响度参数,然后再将其应用于 MediaCodec

// Media contains metadata of type MPEG_4 OR MPEG_D
val mediaCodec = 
val audioTrack = AudioTrack.Builder()
                                .setSessionId(sessionId)
                                .build()
...
// Create new loudness controller that applies the parameters to the MediaCodec
try {
   val lcController = LoudnessCodecController.create(mSessionId)
   // Starts applying audio updates for each added MediaCodec
}

AndroidX media3 ExoPlayer 也将更新,以使用 LoudnessCodecController API,可实现无缝应用集成。

Dispositivos MIDI 2.0 virtuais

Android 13 添加了对使用 USB 连接 MIDI 2.0 设备的支持,这些设备使用通用 MIDI 数据包 (UMP) 进行通信。Android 15 将 UMP 支持扩展到了虚拟 MIDI 应用,使作曲应用能够像使用 USB MIDI 2.0 设备一样,将虚拟 MIDI 2.0 设备用作控制合成器应用的设备。

Decodificação de software AV1 mais eficiente

dav1d 徽标

dav1d 是 VideoLAN 推出的热门 AV1 软件解码器,适用于不支持硬件 AV1 解码的 Android 设备。与旧版 AV1 软件解码器相比,dav1d 的性能最高可提升 3 倍,让更多用户(包括一些低端和中端设备)能够播放高清 AV1 视频。

您的应用需要选择启用 dav1d,方法是通过名称 "c2.android.av1-dav1d.decoder" 调用它。在后续更新中,dav1d 将成为默认的 AV1 软件解码器。此支持已标准化,并向后移植到收到 Google Play 系统更新的 Android 11 设备。

Produtividade e ferramentas para desenvolvedores

Embora a maior parte do nosso trabalho para melhorar a produtividade se concentre em ferramentas como Android Studio, Jetpack Compose e as bibliotecas do Android Jetpack, sempre procuramos maneiras de ajudar você a realizar sua visão.

Atualizações do OpenJDK 17

Android 15 continues the work of refreshing Android's core libraries to align with the features in the latest OpenJDK LTS releases.

The following key features and improvements are included:

These APIs are updated on over a billion devices running Android 12 (API level 31) and higher through Google Play System updates, so you can target the latest programming features.

Melhorias em PDFs

Android 15 对 PdfRenderer API 进行了重大改进。应用可以整合呈现等高级功能 受密码保护的文件、注释、表单编辑searching,而 selection 则包含副本。支持线性化 PDF 优化,此功能可加快本地 PDF 查看速度并减少资源使用量。Jetpack PDF 库使用这些 API 来简化 PDF 的添加 查看功能。

<ph type="x-smartling-placeholder">
</ph>
PDF 渲染的最新更新包括 搜索嵌入式 PDF 文件中的内容。

PdfRenderer 已移至一个可使用 Google Play 系统更新独立于平台版本,并且我们支持 将这些变更还原到 Android 11(API 级别 30),方法是创建兼容的 Android 15 之前版本的 API Surface,称为 PdfRendererPreV

Aprimoramentos da troca automática de idioma

Android 14 在音频中添加了设备端多语言识别功能,并支持在语言之间自动切换,但这可能会导致丢失字词,尤其是当两次语音之间语言切换的间隔时间较短时。Android 15 添加了其他控件,以帮助应用根据其用例调整此切换。EXTRA_LANGUAGE_SWITCH_INITIAL_ACTIVE_DURATION_TIME_MILLIS 会将自动切换限制在音频会话开始时,而 EXTRA_LANGUAGE_SWITCH_MATCH_SWITCHES 会在发生指定次数的切换后停用语言切换。如果您预计会话期间只会使用一种语言,并且该语言应被自动检测到,这些选项会特别有用。

API de fonte variável OpenType melhorada

Android 15 improves the usability of the OpenType variable font. You can create a FontFamily instance from a variable font without specifying weight axes with the buildVariableFamily API. The text renderer overrides the value of wght axis to match the displaying text.

Using the API simplifies the code for creating a Typeface considerably:

Kotlin

val newTypeface = Typeface.CustomFallbackBuilder(
            FontFamily.Builder(
                Font.Builder(assets, "RobotoFlex.ttf").build())
                    .buildVariableFamily())
    .build()

Java

Typeface newTypeface = Typeface.CustomFallbackBuilder(
            new FontFamily.Builder(
                new Font.Builder(assets, "RobotoFlex.ttf").build())
                    .buildVariableFamily())
    .build();

Previously, to create the same Typeface, you would need much more code:

Kotlin

val oldTypeface = Typeface.CustomFallbackBuilder(
            FontFamily.Builder(
                Font.Builder(assets, "RobotoFlex.ttf")
                    .setFontVariationSettings("'wght' 400")
                    .setWeight(400)
                    .build())
                .addFont(
                    Font.Builder(assets, "RobotoFlex.ttf")
                        .setFontVariationSettings("'wght' 100")
                        .setWeight(100)
                        .build()
                )
                .addFont(
                    Font.Builder(assets, "RobotoFlex.ttf")
                        .setFontVariationSettings("'wght' 200")
                        .setWeight(200)
                        .build()
                )
                .addFont(
                    Font.Builder(assets, "RobotoFlex.ttf")
                        .setFontVariationSettings("'wght' 300")
                        .setWeight(300)
                        .build()
                )
                .addFont(
                    Font.Builder(assets, "RobotoFlex.ttf")
                        .setFontVariationSettings("'wght' 500")
                        .setWeight(500)
                        .build()
                )
                .addFont(
                    Font.Builder(assets, "RobotoFlex.ttf")
                        .setFontVariationSettings("'wght' 600")
                        .setWeight(600)
                        .build()
                )
                .addFont(
                    Font.Builder(assets, "RobotoFlex.ttf")
                        .setFontVariationSettings("'wght' 700")
                        .setWeight(700)
                        .build()
                )
                .addFont(
                    Font.Builder(assets, "RobotoFlex.ttf")
                        .setFontVariationSettings("'wght' 800")
                        .setWeight(800)
                        .build()
                )
                .addFont(
                    Font.Builder(assets, "RobotoFlex.ttf")
                        .setFontVariationSettings("'wght' 900")
                        .setWeight(900)
                        .build()
                ).build()
        ).build()

Java

Typeface oldTypeface = new Typeface.CustomFallbackBuilder(
    new FontFamily.Builder(
        new Font.Builder(assets, "RobotoFlex.ttf")
            .setFontVariationSettings("'wght' 400")
            .setWeight(400)
            .build()
    )
    .addFont(
        new Font.Builder(assets, "RobotoFlex.ttf")
            .setFontVariationSettings("'wght' 100")
            .setWeight(100)
            .build()
    )
    .addFont(
        new Font.Builder(assets, "RobotoFlex.ttf")
            .setFontVariationSettings("'wght' 200")
            .setWeight(200)
            .build()
    )
    .addFont(
        new Font.Builder(assets, "RobotoFlex.ttf")
            .setFontVariationSettings("'wght' 300")
            .setWeight(300)
            .build()
    )
    .addFont(
        new Font.Builder(assets, "RobotoFlex.ttf")
            .setFontVariationSettings("'wght' 500")
            .setWeight(500)
            .build()
    )
    .addFont(
        new Font.Builder(assets, "RobotoFlex.ttf")
            .setFontVariationSettings("'wght' 600")
            .setWeight(600)
            .build()
    )
    .addFont(
        new Font.Builder(assets, "RobotoFlex.ttf")
            .setFontVariationSettings("'wght' 700")
            .setWeight(700)
            .build()
    )
    .addFont(
        new Font.Builder(assets, "RobotoFlex.ttf")
            .setFontVariationSettings("'wght' 800")
            .setWeight(800)
            .build()
    )
    .addFont(
        new Font.Builder(assets, "RobotoFlex.ttf")
            .setFontVariationSettings("'wght' 900")
            .setWeight(900)
            .build()
    )
    .build()
).build();

Here's an example of how a Typeface created with both the old and new APIs renders:

An example of how Typeface rendering differs using new and old
APIs

In this example, the Typeface created with the old API doesn't have the capability to create accurate font weights for the 350, 450, 550 and 650 Font instances, so the renderer falls back to the closest weight. So in this case, 300 is rendered instead of 350, 400 is rendered instead of 450, and so on. By contrast, the Typeface created with the new APIs dynamically creates a Font instance for a given weight, so accurate weights are rendered for 350, 450, 550, and 650 as well.

Controles granulares de quebra de linha

Starting in Android 15, a TextView and the underlying line breaker can preserve the given portion of text in the same line to improve readability. You can take advantage of this line break customization by using the <nobreak> tag in string resources or createNoBreakSpan. Similarly, you can preserve words from hyphenation by using the <nohyphen> tag or createNoHyphenationSpan.

For example, the following string resource doesn't include a line break, and renders with the text "Pixel 8 Pro." breaking in an undesirable place:

<resources>
    <string name="pixel8pro">The power and brains behind Pixel 8 Pro.</string>
</resources>

In contrast, this string resource includes the <nobreak> tag, which wraps the phrase "Pixel 8 Pro." and prevents line breaks:

<resources>
    <string name="pixel8pro">The power and brains behind <nobreak>Pixel 8 Pro.</nobreak></string>
</resources>

The difference in how these strings are rendered is shown in the following images:

Layout for a line of text where the phrase "Pixel 8 Pro." isn't wrapped using a <nobreak> tag.
Layout for the same line of text where the phrase "Pixel 8 Pro." is wrapped using a <nobreak> tag.

Arquivamento de apps

O Android e o Google Play anunciaram o suporte ao arquivamento de apps por último ano, permitindo que os usuários liberem espaço removendo parcialmente apps usados com pouca frequência do dispositivo que foram publicados usando o app Android Pacote no Google Play. O Android 15 inclui suporte no nível do SO para arquivamento e desarquivamento de apps, facilitando a implementação em todas as app stores.

Apps com a permissão REQUEST_DELETE_PACKAGES podem chamar o PackageInstaller requestArchive para solicitar o arquivamento de um do pacote de apps instalado, que remove o APK e todos os arquivos em cache, mas persiste dados do usuário. Os apps arquivados são retornados como apps que podem ser exibidos por meio do APIs do LauncherApps os usuários verão um tratamento de interface para destacar e os apps são arquivados. Se um usuário tocar em um app arquivado, o instalador responsável receberá uma solicitação para desarquivá-la. Nesse caso, será possível monitorado pela transmissão ACTION_PACKAGE_ADDED.

使用开发者选项在设备上启用 16 KB 模式

切换以 16KB 页面大小启动设备开发者选项,以便在 16 KB 模式下启动设备。

从 Android 15 QPR1 开始,您可以使用某些设备上提供的开发者选项,以 16 KB 模式启动设备并执行设备端测试。在使用开发者选项之前,请依次前往“设置”->“系统”->“软件更新”,然后应用所有可用的更新。

此开发者选项适用于以下设备:

  • Pixel 8 和 Pixel 8 Pro(搭载 Android 15 QPR1 或更高版本)

    警告:由于 Android 15 QPR2 Beta 版 3 存在已知问题,在安装 Android 15 QPR2 Beta 版 3 并以 16 KB 模式启动设备后,Pixel 8 设备上的触摸屏无法正常使用。此问题不会影响 Pixel 8 Pro 设备。

  • Pixel 8a(搭载 Android 15 QPR1 或更高版本)

    警告:由于 Android 15 QPR2 Beta 版 3 存在已知问题,在安装 Android 15 QPR2 Beta 版 3 并以 16 KB 模式启动设备后,Pixel 8a 设备上的触摸屏无法正常使用。

  • Pixel 9、Pixel 9 Pro 和 Pixel 9 Pro XL(搭载 Android 15 QPR2 Beta 2 或更高版本)

Gráficos

O Android 15 traz as melhorias gráficas mais recentes, incluindo ANGLE e adições ao sistema gráfico de tela.

Modernização do acesso à GPU do Android

Vulkan 徽标

与早期相比,Android 硬件已经有了很大的进步。早期,核心操作系统在单个 CPU 上运行,并且使用基于固定功能流水线的 API 访问 GPU。从 Android 7.0(API 级别 24)开始,NDK 中就提供了 Vulkan® 图形 API,其较低级别的抽象更好地反映了现代 GPU 硬件,可更好地扩缩以支持多个 CPU 核心,并可降低 CPU 驱动程序开销,从而提升应用性能。所有现代游戏引擎都支持 Vulkan。

Vulkan 是 Android 与 GPU 的首选接口。因此,Android 15 包含 ANGLE 作为可选层,用于在 Vulkan 基础上运行 OpenGL® ES。改用 ANGLE 将标准化 Android OpenGL 实现,提高兼容性,在某些情况下还有助于提升性能。在 Android 15 中,您可以依次前往设置 -> 系统 -> 开发者选项 -> 实验性功能:启用 ANGLE,启用开发者选项,以便通过 ANGLE 测试 OpenGL ES 应用的稳定性和性能。

Android ANGLE on Vulkan 路线图

Android GPU API 即将发生变更的路线图。

为了简化 GPU 堆栈,我们今后将在更多新设备上将 ANGLE 作为 GL 系统驱动程序提供,未来 OpenGL/ES 将只能通过 ANGLE 获得支持。尽管如此,我们计划继续在所有设备上支持 OpenGL ES

建议的后续措施

使用开发者选项为 OpenGL ES 选择 ANGLE 驱动程序,然后测试您的应用。对于新项目,我们强烈建议您为 C/C++ 使用 Vulkan。

Melhorias no Canvas

Android 15 continues our modernization of Android's Canvas graphics system with additional capabilities:

  • Matrix44 provides a 4x4 matrix for transforming coordinates that should be used when you want to manipulate the canvas in 3D.
  • clipShader intersects the current clip with the specified shader, while clipOutShader sets the clip to the difference of the current clip and the shader, each treating the shader as an alpha mask. This supports the drawing of complex shapes efficiently.

Desempenho e bateria

O Android continua focado em ajudar você a melhorar a performance e a qualidade dos seus apps. O Android 15 apresenta APIs que ajudam a tornar as tarefas no app mais eficientes para executar, otimizar o desempenho do app e coletar insights sobre seus apps.

Para conferir as práticas recomendadas de eficiência de bateria, a depuração de rede e o uso de energia, além de detalhes sobre como estamos melhorando a eficiência da bateria do trabalho em segundo plano no Android 15 e nas versões mais recentes do Android, consulte a palestra Como melhorar a eficiência da bateria do trabalho em segundo plano no Android do Google I/O.

API ApplicationStartInfo

In previous versions of Android, app startup has been a bit of a mystery. It was challenging to determine within your app whether it started from a cold, warm, or hot state. It was also difficult to know how long your app spent during the various launch phases: forking the process, calling onCreate, drawing the first frame, and more. When your Application class was instantiated, you had no way of knowing whether the app started from a broadcast, a content provider, a job, a backup, boot complete, an alarm, or an Activity.

The ApplicationStartInfo API on Android 15 provides all of this and more. You can even choose to add your own timestamps into the flow to help collect timing data in one place. In addition to collecting metrics, you can use ApplicationStartInfo to help directly optimize app startup; for example, you can eliminate the costly instantiation of UI-related libraries within your Application class when your app is starting up due to a broadcast.

Informações detalhadas sobre o tamanho do app

Since Android 8.0 (API level 26), Android has included the StorageStats.getAppBytes API that summarizes the installed size of an app as a single number of bytes, which is a sum of the APK size, the size of files extracted from the APK, and files that were generated on the device such as ahead-of-time (AOT) compiled code. This number is not very insightful in terms of how your app is using storage.

Android 15 adds the StorageStats.getAppBytesByDataType([type]) API, which lets you get insight into how your app is using up all that space, including APK file splits, AOT and speedup related code, dex metadata, libraries, and guided profiles.

Criação de perfil gerenciada pelo app

Android 15 includes the ProfilingManager class, which lets you collect profiling information from within your app such as heap dumps, heap profiles, stack sampling, and more. It provides a callback to your app with a supplied tag to identify the output file, which is delivered to your app's files directory. The API does rate limiting to minimize the performance impact.

To simplify constructing profiling requests in your app, we recommend using the corresponding Profiling AndroidX API, available in Core 1.15.0-rc01 or higher.

Melhorias no banco de dados SQLite

Android 15 引入了 SQLite API,这些 API 可公开底层 SQLite 引擎的高级功能,以解决可能在应用中出现的特定性能问题。将 SQLite 更新到版本 3.44.3

开发者应参阅 SQLite 性能最佳实践 以便充分利用其 SQLite 数据库,尤其是在处理大型 或运行对延迟敏感的查询时

Atualizações do Framework de Performance Dinâmica do Android

Android 15 continues our investment in the Android Dynamic Performance Framework (ADPF), a set of APIs that allow games and performance intensive apps to interact more directly with power and thermal systems of Android devices. On supported devices, Android 15 adds ADPF capabilities:

  • A power-efficiency mode for hint sessions to indicate that their associated threads should prefer power saving over performance, great for long-running background workloads.
  • GPU and CPU work durations can both be reported in hint sessions, allowing the system to adjust CPU and GPU frequencies together to best meet workload demands.
  • Thermal headroom thresholds to interpret possible thermal throttling status based on headroom prediction.

To learn more about how to use ADPF in your apps and games, head over to the documentation.

Privacidade

O Android 15 inclui vários recursos que ajudam os desenvolvedores de apps a proteger a privacidade do usuário.

Detecção de gravação de tela

Android 15 adds support for apps to detect that they are being recorded. A callback is invoked whenever the app transitions between being visible or invisible within a screen recording. An app is considered visible if activities owned by the registering process's UID are being recorded. This way, if your app is performing a sensitive operation, you can inform the user that they're being recorded.

val mCallback = Consumer<Int> { state ->
  if (state == SCREEN_RECORDING_STATE_VISIBLE) {
    // We're being recorded
  } else {
    // We're not being recorded
  }
}

override fun onStart() {
   super.onStart()
   val initialState =
      windowManager.addScreenRecordingCallback(mainExecutor, mCallback)
   mCallback.accept(initialState)
}

override fun onStop() {
    super.onStop()
    windowManager.removeScreenRecordingCallback(mCallback)
}

Recursos de IntentFilter expandidos

Android 15 builds in support for more precise Intent resolution through UriRelativeFilterGroup, which contains a set of UriRelativeFilter objects that form a set of Intent matching rules that must each be satisfied, including URL query parameters, URL fragments, and blocking or exclusion rules.

These rules can be defined in the AndroidManifest XML file with the <uri-relative-filter-group> tag, which can optionally include an android:allow tag. These tags can contain <data> tags that use existing data tag attributes as well as the android:query and android:fragment attributes.

Here's an example of the AndroidManifest syntax:

<intent-filter android:autoVerify="true">
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.BROWSABLE" />
  <category android:name="android.intent.category.DEFAULT" />
  <data android:scheme="http" />
  <data android:scheme="https" />
  <data android:host="astore.com" />
  <uri-relative-filter-group>
    <data android:pathPrefix="/auth" />
    <data android:query="region=na" />
  </uri-relative-filter-group>
  <uri-relative-filter-group android:allow="false">
    <data android:pathPrefix="/auth" />
    <data android:query="mobileoptout=true" />
  </uri-relative-filter-group>
  <uri-relative-filter-group android:allow="false">
    <data android:pathPrefix="/auth" />
    <data android:fragmentPrefix="faq" />
  </uri-relative-filter-group>
</intent-filter>

Espaço privado

可通过解锁和锁定私密空间,在设备上显示或隐藏敏感应用。

借助私密空间,用户可以在设备上创建一个单独的空间,在额外的身份验证层保护下,防止敏感应用遭到窥探。私密空间使用单独的用户个人资料。用户可以选择使用设备锁定方式或为私密空间使用单独的锁定方式。

私密空间中的应用会显示在启动器的单独容器中,并且当私密空间处于锁定状态时,这些应用不会显示在“最近用过”视图、通知、“设置”和其他应用中。用户生成的内容和下载的内容(例如媒体内容或文件)以及账号在私密空间和主空间之间是分开的。在私密空间处于解锁状态时,您可以使用系统 Sharesheet照片选择器向应用授予对各个空间中内容的访问权限。

用户无法将现有应用及其数据移至私密空间。相反,用户可以在私密空间中选择安装选项,以便使用他们偏好的任意应用商店安装应用。私密空间中的应用会作为主空间中任何应用的单独副本进行安装(同一应用的新副本)。

当用户锁定私密空间时,系统会停止该个人资料。在个人资料停止运行时,私密空间中的应用将不再处于活动状态,无法执行前台或后台活动,包括显示通知。

我们建议您使用私密空间测试应用,以确保应用能按预期运行,尤其是当您的应用属于以下某一类别时:

Consultar a seleção de usuário mais recente para o acesso a fotos selecionadas

Apps can now highlight only the most-recently-selected photos and videos when partial access to media permissions is granted. This feature can improve the user experience for apps that frequently request access to photos and videos. To use this feature in your app, enable the QUERY_ARG_LATEST_SELECTION_ONLY argument when querying MediaStore through ContentResolver.

Kotlin

val externalContentUri = MediaStore.Files.getContentUri("external")

val mediaColumns = arrayOf(
   FileColumns._ID,
   FileColumns.DISPLAY_NAME,
   FileColumns.MIME_TYPE,
)

val queryArgs = bundleOf(
   // Return only items from the last selection (selected photos access)
   QUERY_ARG_LATEST_SELECTION_ONLY to true,
   // Sort returned items chronologically based on when they were added to the device's storage
   QUERY_ARG_SQL_SORT_ORDER to "${FileColumns.DATE_ADDED} DESC",
   QUERY_ARG_SQL_SELECTION to "${FileColumns.MEDIA_TYPE} = ? OR ${FileColumns.MEDIA_TYPE} = ?",
   QUERY_ARG_SQL_SELECTION_ARGS to arrayOf(
       FileColumns.MEDIA_TYPE_IMAGE.toString(),
       FileColumns.MEDIA_TYPE_VIDEO.toString()
   )
)

Java

Uri externalContentUri = MediaStore.Files.getContentUri("external");

String[] mediaColumns = {
    FileColumns._ID,
    FileColumns.DISPLAY_NAME,
    FileColumns.MIME_TYPE
};

Bundle queryArgs = new Bundle();
queryArgs.putBoolean(MediaStore.QUERY_ARG_LATEST_SELECTION_ONLY, true);
queryArgs.putString(MediaStore.QUERY_ARG_SQL_SORT_ORDER, FileColumns.DATE_ADDED + " DESC");
queryArgs.putString(MediaStore.QUERY_ARG_SQL_SELECTION, FileColumns.MEDIA_TYPE + " = ? OR " + FileColumns.MEDIA_TYPE + " = ?");
queryArgs.putStringArray(MediaStore.QUERY_ARG_SQL_SELECTION_ARGS, new String[] {
    String.valueOf(FileColumns.MEDIA_TYPE_IMAGE),
    String.valueOf(FileColumns.MEDIA_TYPE_VIDEO)
});

Sandbox de privacidade no Android

Android 15 包含最新的 Android 广告服务扩展,其中包含最新版本的 Privacy Sandbox on Android。我们一直致力于开发可更好地保护用户隐私,并为移动应用打造高效的个性化广告体验的技术,此次添加新功能就是其中的一项举措。我们的 Privacy Sandbox 页面详细介绍了 Privacy Sandbox on Android 开发者预览版和 Beta 版计划,可帮助您上手使用。

Conexão Saúde

Android 15 integrates the latest extensions around Health Connect by Android, a secure and centralized platform to manage and share app-collected health and fitness data. This update adds support for additional data types across fitness, nutrition, skin temperature, training plans, and more.

Skin temperature tracking allows users to store and share more accurate temperature data from a wearable or other tracking device.

Training plans are structured workout plans to help a user achieve their fitness goals. Training plans support includes a variety of completion and performance goals:

Learn more about the latest updates to Health Connect in Android in the Building adaptable experiences with Android Health talk from Google I/O.

Compartilhamento de tela de app

O Android 15 oferece suporte ao compartilhamento de tela de apps para que os usuários possam compartilhar ou gravar apenas uma janela de app, em vez de toda a tela do dispositivo. Esse recurso, ativado pela primeira vez no Android 14 QPR2, inclui callbacks MediaProjection que permitem que seu app personalize a experiência de compartilhamento de tela. Para apps destinados ao Android 14 (nível 34 da API) ou mais recente, o consentimento do usuário é necessário para cada sessão de captura de MediaProjection.

Experiência do usuário e interface do sistema

O Android 15 oferece aos desenvolvedores e usuários de apps mais controle e flexibilidade para configurar o dispositivo de acordo com as necessidades.

Para saber mais sobre como usar as melhorias mais recentes do Android 15 para melhorar a experiência do usuário do app, consulte a palestra Melhorar a experiência do usuário do seu app Android no Google I/O.

Prévias de widgets mais ricas com a API Generated Previews

Before Android 15, the only way to provide widget picker previews was to specify a static image or layout resource. These previews often differ significantly from the look of the actual widget when it is placed on the home screen. Also, static resources can't be created with Jetpack Glance, so a Glance developer had to screenshot their widget or create an XML layout to have a widget preview.

Android 15 adds support for generated previews. This means that app widget providers can generate RemoteViews to use as the picker preview, instead of a static resource.

Apps can provide Remote Views to the Widget Picker, so they can update the content in the picker to be more representative of what the user will see.

Push API

Apps can provide generated previews through a push API. Apps can provide previews at any point in their lifecycle, and don't receive an explicit request from the host to provide previews. Previews are persisted in AppWidgetService, and hosts can request them on-demand. The following example loads an XML widget layout resource and sets it as the preview:

AppWidgetManager.getInstance(appContext).setWidgetPreview(
   ComponentName(
       appContext,
       SociaLiteAppWidgetReceiver::class.java
   ),
   AppWidgetProviderInfo.WIDGET_CATEGORY_HOME_SCREEN,
   RemoteViews("com.example", R.layout.widget_preview)
)

The expected flow is:

  1. At any time, the widget provider calls setWidgetPreview. The provided previews are persisted in AppWidgetService with other provider info.
  2. setWidgetPreview notifies hosts of an updated preview through the AppWidgetHost.onProvidersChanged callback. In response, the widget host reloads all of its provider information.
  3. When displaying a widget preview, the host checks AppWidgetProviderInfo.generatedPreviewCategories, and if the chosen category is available, calls AppWidgetManager.getWidgetPreview to return the saved preview for this provider.

When to call setWidgetPreview

Because there is no callback to provide previews, apps can choose to send previews at any point when they are running. How often to update the preview depends on the widget's use case.

The following list describes the two main categories of preview use cases:

  • Providers that show real data in their widget previews, such as personalized or recent information. These providers can set the preview once the user has signed in or has done initial configuration in their app. After this, they can set up a periodic task to update the previews at their chosen cadence. Examples of this type of widget could be a photo, calendar, weather or news widget.
  • Providers that show static information in previews or quick-action widgets that don't display any data. These providers can set previews once, when the app first launches. Examples of this type of widget include a drive quick actions widget or chrome shortcuts widget.

Some providers might show static previews on the hub mode picker, but real information on the homescreen picker. These providers should follow the guidance for both of these use cases to set previews.

Picture-in-picture

Android 15 introduces changes in Picture-in-Picture (PiP) ensuring an even smoother transition when entering into PiP mode. This will be beneficial for apps having UI elements overlaid on top of their main UI, which goes into PiP.

Developers use the onPictureInPictureModeChanged callback to define logic that toggles the visibility of the overlaid UI elements. This callback is triggered when the PiP enter or exit animation is completed. Beginning in Android 15, the PictureInPictureUiState class includes another state.

With this UI state, apps targeting Android 15 (API level 35) will observe the Activity#onPictureInPictureUiStateChanged callback being invoked with isTransitioningToPip() as soon as the PiP animation starts. There are many UI elements that are not relevant for the app when it is in PiP mode, for example views or layout that include information such as suggestions, upcoming video, ratings, and titles. When the app goes to PiP mode, use the onPictureInPictureUiStateChanged callback to hide these UI elements. When the app goes to full screen mode from the PiP window, use onPictureInPictureModeChanged callback to unhide these elements, as shown in the following examples:

override fun onPictureInPictureUiStateChanged(pipState: PictureInPictureUiState) {
        if (pipState.isTransitioningToPip()) {
          // Hide UI elements
        }
    }
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) {
        if (isInPictureInPictureMode) {
          // Unhide UI elements
        }
    }

This quick visibility toggle of irrelevant UI elements (for a PiP window) helps ensure a smoother and flicker-free PiP enter animation.

Melhorias nas regras do modo "Não perturbe"

O AutomaticZenRule permite que os apps personalizem a atenção de gerenciamento (Não perturbe) e decida quando ativar ou desativar para resolvê-los com rapidez. O Android 15 aprimora essas regras de forma significativa, com o objetivo de melhorar a experiência do usuário. As seguintes melhorias estão incluídas:

  • Adição de tipos a AutomaticZenRule, permitindo que o sistema aplique um tratamento especial a algumas regras.
  • Adição de um ícone à AutomaticZenRule, ajudando a tornar os modos mais reconhecíveis.
  • Adicionar uma string triggerDescription a AutomaticZenRule que descreve as condições em que a regra deve ficar ativa para o usuário.
  • Adicionado ZenDeviceEffects para AutomaticZenRule, permitindo que as regras acionem elementos como escala de cinza tela, modo noturno ou esmaecer o plano de fundo.

Definir VibrationEffect para canais de notificação

Android 15 支持为传入的通知设置丰富的振动,方法是 频道使用的是NotificationChannel.setVibrationEffect,因此 您的用户可以区分不同类型的通知 不需要看他们的设备

Ícone da barra de status da projeção de mídia e parada automática

媒体投放可能会泄露用户的私密信息。一个醒目的新状态栏条状标签可让用户了解任何正在进行的屏幕投影。用户可以点按该条状标签停止投屏、共享或录制屏幕。此外,为了提供更直观的用户体验,当设备屏幕锁定后,所有正在进行的屏幕投影都会自动停止。

Bloco da barra de status para compartilhamento de tela, transmissão e gravação.

Telas grandes e formatos

O Android 15 oferece aos seus apps o suporte necessário para aproveitar ao máximo os formatos do Android, incluindo telas grandes, flippables e dobráveis.

Mais facilidade para várias tarefas em telas grandes

Android 15 为用户提供了在大屏设备上更好地进行多任务处理的方式。对于 例如,用户可以保存自己喜爱的分屏应用组合, 访问并固定屏幕上的任务栏,以便在应用之间快速切换。这意味着 让应用具备自适应能力比以往任何时候都更加重要。

Google I/O 大会上有一些关于构建自适应 Android 的会议 应用使用 Material 3 构建界面 自适应库 我们的文档中提供了更多帮助信息,帮助您针对大型语言 。

Suporte a tela de capa

您的应用可以声明一个属性,Android 15 会使用该属性来允许您的 ApplicationActivity 显示在受支持的可翻转设备的小封面屏幕上。这些屏幕太小,无法被视为适合运行 Android 应用的兼容目标平台,但您的应用可以选择支持它们,从而让您的应用在更多平台上可用。

Conectividade

O Android 15 atualiza a plataforma para dar ao app acesso aos avanços mais recentes em comunicação e tecnologias sem fio.

Suporte a satélite

Android 15 continues to extend platform support for satellite connectivity and includes some UI elements to ensure a consistent user experience across the satellite connectivity landscape.

Apps can use ServiceState.isUsingNonTerrestrialNetwork() to detect when a device is connected to a satellite, giving them more awareness of why full network services might be unavailable. Additionally, Android 15 provides support for SMS and MMS apps as well as preloaded RCS apps to use satellite connectivity for sending and receiving messages.

A notification appears when the device connects to a satellite.

Experiências NFC mais suaves

Android 15 is working to make the tap to pay experience more seamless and reliable while continuing to support Android's robust NFC app ecosystem. On supported devices, apps can request the NfcAdapter to enter observe mode, where the device listens but doesn't respond to NFC readers, sending the app's NFC service PollingFrame objects to process. The PollingFrame objects can be used to auth ahead of the first communication to the NFC reader, allowing for a one tap transaction in many cases.

In addition, apps can register a filter on supported devices so they can be notified of polling loop activity, which allows for smooth operation with multiple NFC-aware applications.

Função da Carteira

Android 15 introduces a Wallet role that allows tighter integration with the user's preferred wallet app. This role replaces the NFC default contactless payment setting. Users can manage the Wallet role holder by navigating to Settings > Apps > Default Apps.

The Wallet role is used when routing NFC taps for AIDs registered in the payment category. Taps always go to the Wallet role holder unless another app that is registered for the same AID is running in the foreground.

This role is also used to determine where the Wallet Quick Access tile should go when activated. When the role is set to "None", the Quick Access tile isn't available and payment category NFC taps are only delivered to the foreground app.

Segurança

O Android 15 ajuda a melhorar a segurança do app, proteger os dados dele e oferecer aos usuários mais transparência e controle sobre os dados. Assista à palestra Proteger a segurança do usuário no Android (link em inglês) da Google I/O para saber mais sobre o que estamos fazendo para melhorar as proteções do usuário e proteger seu app contra novas ameaças.

Integrar o Gerenciador de credenciais ao preenchimento automático

A partir do Android 15, os desenvolvedores podem vincular visualizações específicas, como campos de nome de usuário ou senha, a solicitações do Gerenciador de credenciais, facilitando a criação de uma experiência personalizada do usuário durante o processo de login. Quando o usuário foca em uma dessas visualizações, uma solicitação correspondente é enviada ao Gerenciador de credenciais. As credenciais resultantes são agregadas entre os provedores e exibidas em interfaces padrão de preenchimento automático, como sugestões inline ou suspensas. A biblioteca androidx.credentials do Jetpack é o endpoint preferencial para desenvolvedores e em breve estará disponível para aprimorar ainda mais esse recurso no Android 15 e versões mais recentes.

Integrar o processo de inscrição e login com um toque às solicitações biométricas

Credential Manager integrates biometric prompts into the credential creation and sign-in processes, eliminating the need for providers to manage biometric prompts. As a result, credential providers only need to focus on the results of the create and get flows, augmented with the biometric flow result. This simplified process creates a more efficient and streamlined credential creation and retrieval process.

Gerenciamento de chaves para criptografia de ponta a ponta

Estamos lançando o E2eeContactKeysManager no Android 15, que facilita a criptografia de ponta a ponta (E2EE, na sigla em inglês) nos seus apps Android, fornecendo uma API no nível do SO para o armazenamento de chaves públicas criptográficas.

O E2eeContactKeysManager foi projetado para se integrar ao app de contatos da plataforma e oferecer aos usuários uma maneira centralizada de gerenciar e verificar as chaves públicas dos contatos.

Verificações de permissão em URIs de conteúdo

Android 15 引入了一组用于对内容 URI 执行权限检查的 API:

Acessibilidade

O Android 15 adiciona recursos que melhoram a acessibilidade para os usuários.

Melhor braille

In Android 15, we've made it possible for TalkBack to support Braille displays that are using the HID standard over both USB and secure Bluetooth.

This standard, much like the one used by mice and keyboards, will help Android support a wider range of Braille displays over time.

Internacionalização

O Android 15 adiciona recursos e capacidades que complementam a experiência do usuário quando um dispositivo é usado em diferentes idiomas.

Fonte variável CJK

Starting with Android 15, the font file for Chinese, Japanese, and Korean (CJK) languages, NotoSansCJK, is now a variable font. Variable fonts open up possibilities for creative typography in CJK languages. Designers can explore a broader range of styles and create visually striking layouts that were previously difficult or impossible to achieve.

How the variable font for Chinese, Japanese, and Korean (CJK) languages appears with different font widths.

Justificação entre caracteres

Starting with Android 15, text can be justified utilizing letter spacing by using JUSTIFICATION_MODE_INTER_CHARACTER. Inter-word justification was first introduced in Android 8.0 (API level 26), and inter-character justification provides similar capabilities for languages that use the whitespace character for segmentation, such as Chinese, Japanese, and others.

Layout for Japanese text using JUSTIFICATION_MODE_NONE.
Layout for English text using JUSTIFICATION_MODE_NONE.


Layout for Japanese text using JUSTIFICATION_MODE_INTER_WORD.
Layout for English text using JUSTIFICATION_MODE_INTER_WORD.


Layout for Japanese text using the JUSTIFICATION_MODE_INTER_CHARACTER.
Layout for English text using the JUSTIFICATION_MODE_INTER_CHARACTER.

Configuração automática de quebra de linha

Android started supporting phrase-based line breaks for Japanese and Korean in Android 13 (API level 33). However, while phrase-based line breaks improve the readability of short lines of text, they don't work well for long lines of text. In Android 15, apps can apply phrase-based line breaks only for short lines of text, using the LINE_BREAK_WORD_STYLE_AUTO option. This option selects the best word style option for the text.

For short lines of text, phrase-based line breaks are used, functioning the same as LINE_BREAK_WORD_STYLE_PHRASE, as shown in the following image:

For short lines of text, LINE_BREAK_WORD_STYLE_AUTO applies phrase-based line breaks to improve the readability of the text. This is the same as applying LINE_BREAK_WORD_STYLE_PHRASE.

For longer lines of text, LINE_BREAK_WORD_STYLE_AUTO uses a no line-break word style, functioning the same as LINE_BREAK_WORD_STYLE_NONE, as shown in the following image:

For long lines of text, LINE_BREAK_WORD_STYLE_AUTO applies no line-break word style to improve the readability of the text. This is the same as applying LINE_BREAK_WORD_STYLE_NONE.

Fonte japonesa Hentaigana adicional

In Android 15, a font file for old Japanese Hiragana (known as Hentaigana) is bundled by default. The unique shapes of Hentaigana characters can add a distinctive flair to artwork or design while also helping to preserve accurate transmission and understanding of ancient Japanese documents.

Character and text style for the Japanese Hentaigana font.

VideoLAN 圆锥图标 版权所有 (c) 1996-2010 VideoLAN。任何人都可以使用此徽标或修改版徽标来提及 VideoLAN 项目或 VideoLAN 团队开发的任何产品,但这并不表示该项目对其表示认可。

Vulkan 和 Vulkan 徽标是 Khronos Group Inc.的注册商标。

OpenGL 是注册商标,OpenGL ES 徽标是 Hewlett Packard Enterprise 的商标,已获得 Khronos 的许可。