Funkcje i interfejsy API – przegląd

Android 14 wprowadza świetne funkcje i interfejsy API dla deweloperów. Poniższe materiały pomogą Ci poznać funkcje aplikacji i zacząć korzystać z powiązanych interfejsów API.

Szczegółową listę dodanych, zmodyfikowanych i usuniętych interfejsów API znajdziesz w raporcie o różnicach w interfejsach API. Szczegółowe informacje o dodanych interfejsach API znajdziesz w dokumentacji interfejsu Android API. W przypadku Androida 14 poszukaj interfejsów API dodanych na poziomie 34. Aby dowiedzieć się więcej o obszarach, w których zmiany na platformie mogą mieć wpływ na Twoje aplikacje, zapoznaj się ze zmianami w działaniu Androida 14 w przypadku aplikacji kierowanych na Androida 14w przypadku wszystkich aplikacji.

Internacjonalizacja

Wybór języka według aplikacji

Android 14 rozszerza funkcje języka na poziomie aplikacji, które zostały wprowadzone w Androidzie 13 (poziom API 33), o te dodatkowe możliwości:

  • Automatyczne generowanie localeConfig w aplikacji: od wersji Android Studio Giraffe Canary 7 i AGP 8.1.0-alpha07 możesz skonfigurować aplikację tak, aby automatycznie obsługiwała ustawienia języka na poziomie aplikacji. Na podstawie zasobów projektu wtyczka Androida do obsługi Gradle generuje plik LocaleConfig i dodaje do niego odwołanie w pliku manifestu końcowego. Dzięki temu nie musisz już tworzyć ani aktualizować tego pliku ręcznie. AGP korzysta z zasobów w folderach res w modułach aplikacji oraz z zależnych modułów bibliotek, aby określić lokalizacje, które mają być uwzględnione w pliku LocaleConfig.

  • Dynamiczne aktualizacje localeConfig aplikacji: użyj metod setOverrideLocaleConfig() i getOverrideLocaleConfig() w LocaleManager, aby dynamicznie aktualizować listę obsługiwanych języków aplikacji w ustawieniach systemu urządzenia. Dzięki tej elastyczności możesz dostosować listę obsługiwanych języków w danym regionie, przeprowadzać eksperymenty A/B lub przesyłać zaktualizowaną listę lokalizacji, jeśli Twoja aplikacja korzysta z push na serwerze do celów lokalizacji.

  • Widoczność języka aplikacji w edytorach metody wprowadzania: edytorzy metody wprowadzania mogą korzystać z metody getApplicationLocales(), aby sprawdzić język bieżącej aplikacji i dostosować do niego język edytora metody wprowadzania.

Grammatical Inflection API

3 miliardy ludzi mówi językami z płcią: językami, w których kategorie gramatyczne (np. rzeczowniki, czasowniki, przymiotniki i przyimki) odmieniają się w zależności od płci osób i rzeczy, do których się zwracamy lub o których mówimy. Tradycyjnie wiele języków z płcią gramatyczną używa męskiej formy gramatycznej jako domyślnej lub uniwersalnej.

Zwracanie się do użytkowników w niewłaściwym rodzaju gramatycznym, np. do kobiet w męskim rodzaju gramatycznym, może negatywne wpłynąć na ich wyniki i postawę. Z kolei interfejs z językiem, który poprawnie odzwierciedla płeć gramatyczną użytkownika, może zwiększyć zaangażowanie użytkowników i zapewnić bardziej spersonalizowane i naturalne wrażenia.

为帮助您针对区分性别的语言构建以用户为中心的界面,Android 14 引入了 Grammatical Inflection API,让您无需重构应用便能添加对语法性别的支持。

Preferencje regionalne

用户可通过地区偏好设置对温度单位、一周的第一天和编号系统进行个性化设置。居住在美国的欧洲用户可能更希望使用摄氏度,而不是华氏度,并且希望应用将星期一视为一周的开始,而不是像美国那样默认从星期日开始。

新 Android 设置菜单包含这些偏好设置,使用户能够在一个位置集中发现这些应用更改偏好设置。这些偏好设置在备份和恢复设备后也会保持不变。多个 API 和 intent(例如 getTemperatureUnitgetFirstDayOfWeek)会为您的应用授予读取权限来访问用户偏好设置,因此您的应用可以调整其显示信息的方式。您还可以在 ACTION_LOCALE_CHANGED 上注册 BroadcastReceiver,以便在地区偏好设置发生更改时处理语言区域配置更改。

如需找到这些设置,请打开“设置”应用,然后依次前往系统 > 语言和输入法 > 地区偏好设置

Android 系统设置中的地区偏好设置界面。
Android 系统中地区偏好设置的温度选项 设置。

Ułatwienia dostępu

Nieliniowe skalowanie czcionki do 200%

Starting in Android 14, the system supports font scaling up to 200%, providing low-vision users with additional accessibility options that align with Web Content Accessibility Guidelines (WCAG).

To prevent large text elements on screen from scaling too large, the system applies a nonlinear scaling curve. This scaling strategy means that large text doesn't scale at the same rate as smaller text. Nonlinear font scaling helps preserve the proportional hierarchy between elements of different sizes while mitigating issues with linear text scaling at high degrees (such as text being cut off or text that becomes harder to read due to an extremely large display sizes).

Test your app with nonlinear font scaling

Enable the maximum font size in a device's accessibility settings to test your app.

If you already use scaled pixels (sp) units to define text sizing, then these additional options and scaling improvements are applied automatically to the text in your app. However, you should still perform UI testing with the maximum font size enabled (200%) to ensure that your app applies the font sizes correctly and can accommodate larger font sizes without impacting usability.

To enable 200% font size, follow these steps:

  1. Open the Settings app and navigate to Accessibility > Display size and text.
  2. For the Font size option, tap the plus (+) icon until the maximum font size setting is enabled, as shown in the image that accompanies this section.

Use scaled pixel (sp) units for text-sizes

Remember to always specify text sizes in sp units. When your app uses sp units, Android can apply the user's preferred text size and scale it appropriately.

Don't use sp units for padding or define view heights assuming implicit padding: with nonlinear font scaling sp dimensions might not be proportional, so 4sp + 20sp might not equal 24sp.

Convert scaled pixel (sp) units

Use TypedValue.applyDimension() to convert from sp units to pixels, and use TypedValue.deriveDimension() to convert pixels to sp. These methods apply the appropriate nonlinear scaling curve automatically.

Avoid hardcoding equations using Configuration.fontScale or DisplayMetrics.scaledDensity. Because font scaling is nonlinear, the scaledDensity field is no longer accurate. The fontScale field should be used for informational purposes only because fonts are no longer scaled with a single scalar value.

Use sp units for lineHeight

Always define android:lineHeight using sp units instead of dp, so the line height scales along with your text. Otherwise, if your text is sp but your lineHeight is in dp or px, it doesn't scale and looks cramped. TextView automatically corrects the lineHeight so that your intended proportions are preserved, but only if both textSize and lineHeight are defined in sp units.

Aparat i multimedia

Ultra HDR w przypadku zdjęć

An illustration of Standard Dynamic Range (SDR) versus High Dynamic Range (HDR) image quality.

Android 14 adds support for High Dynamic Range (HDR) images that retain more of the information from the sensor when taking a photo, which enables vibrant colors and greater contrast. Android uses the Ultra HDR format, which is fully backward compatible with JPEG images, allowing apps to seamlessly interoperate with HDR images, displaying them in Standard Dynamic Range (SDR) as needed.

Rendering these images in the UI in HDR is done automatically by the framework when your app opts in to using HDR UI for its Activity Window, either through a manifest entry or at runtime by calling Window.setColorMode(). You can also capture compressed Ultra HDR still images on supported devices. With more colors recovered from the sensor, editing in post can be more flexible. The Gainmap associated with Ultra HDR images can be used to render them using OpenGL or Vulkan.

Zoom, ostrość, podgląd i inne funkcje w rozszerzeniach aparatu

Android 14 upgrades and improves camera extensions, allowing apps to handle longer processing times, which enables improved images using compute-intensive algorithms like low-light photography on supported devices. These features give users an even more robust experience when using camera extension capabilities. Examples of these improvements include:

Zoom na matrycy

CameraCharacteristics 中的 REQUEST_AVAILABLE_CAPABILITIES_STREAM_USE_CASE 包含 SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW 时,您的应用可以使用高级传感器功能,将剪裁后的 RAW 数据流的像素与全视野范围相同,方法是将 CaptureRequest 与将数据流用例设置为 CameraMetadata.SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW 的 RAW 目标搭配使用。通过实现请求替换控件,更新后的相机可让用户在其他相机控件准备就绪之前使用缩放控件。

Bezstratny dźwięk przez USB

Android 14 gains support for lossless audio formats for audiophile-level experiences over USB wired headsets. You can query a USB device for its preferred mixer attributes, register a listener for changes in preferred mixer attributes, and configure mixer attributes using the AudioMixerAttributes class. This class represents the format, such as channel mask, sample rate, and behavior of the audio mixer. The class allows for audio to be sent directly, without mixing, volume adjustment, or processing effects.

Wydajność i narzędzia dla programistów

Credential Manager

Android 14 将 Credential Manager 添加为平台 API,并通过使用 Google Play 服务的 Jetpack 库,向后额外支持 Android 4.4(API 级别 19)设备。Credential Manager 旨在通过 API 使用用户配置的凭据提供程序检索和存储凭据,让用户更轻松地登录。Credential Manager 在单个 API 中支持多种登录方法,包括用户名和密码、通行密钥和联合登录解决方案(如“使用 Google 账号登录”)。

通行密钥具有许多优势。例如,通行密钥是基于业界标准构建的,可在各种不同的操作系统和浏览器生态系统中使用,并且可用于网站和应用。

如需了解详情,请参阅 Credential Manager 和通行密钥文档以及介绍 Credential Manager 和通行密钥的博文

Health Connect

Health Connect to repozytorium danych o zdrowiu i kondycji fizycznej użytkownika na urządzeniu. Umożliwia ona użytkownikom udostępnianie danych między ulubionymi aplikacjami i zarządzanie w jednym miejscu danymi, które chcą udostępniać tym aplikacjom.

Na urządzeniach z Androidem w wersjach starszych niż 14 aplikację Health Connect można pobrać ze Sklepu Google Play. Od Androida 14 Zarządzanie danymi o zdrowiu jest częścią platformy i otrzymuje aktualizacje w ramach aktualizacji systemowych Google Play bez konieczności osobnego pobierania. Dzięki temu Health Connect może być często aktualizowany, a Twoje aplikacje mogą korzystać z Health Connect na urządzeniach z Androidem w wersji 14 lub nowszej. Użytkownicy mogą korzystać z Health Connect w ustawieniach urządzenia, a ustawienia prywatności są zintegrowane z ustawieniami systemu.

Użytkownicy mogą zacząć korzystać z Health Connect bez konieczności pobierania osobnej aplikacji na urządzeniach z Androidem 14 lub nowszym.
Użytkownicy mogą kontrolować, które aplikacje mają dostęp do ich danych o zdrowiu i kondycji fizycznej, za pomocą ustawień systemu.

Health Connect zawiera kilka nowych funkcji w Androidzie 14, takich jak trasy treningów, które umożliwiają użytkownikom udostępnianie trasy treningu, którą można wyświetlić na mapie. Trasa to lista lokalizacji zapisanych w określonym przedziale czasu. Aplikacja może wstawiać trasy do sesji ćwiczeń, łącząc je ze sobą. Aby mieć pełną kontrolę nad tymi poufnymi danymi, użytkownicy muszą zezwolić na udostępnianie poszczególnych tras innym aplikacjom.

Więcej informacji znajdziesz w dokumentacji dotyczącej funkcji Health Connection oraz w poście na blogu Co nowego w Androidzie Health.

Aktualizacje OpenJDK 17

Android 14 continues the work of refreshing Android's core libraries to align with the features in the latest OpenJDK LTS releases, including both library updates and Java 17 language support for app and platform developers.

The following features and improvements are included:

  • Updated approximately 300 java.base classes to Java 17 support.
  • Text Blocks, which introduce multi-line string literals to the Java programming language.
  • Pattern Matching for instanceof, which allows an object to be treated as having a specific type in an instanceof without any additional variables.
  • Sealed classes, which allow you restrict which classes and interfaces can extend or implement them.

Thanks to Google Play system updates (Project Mainline), over 600 million devices are enabled to receive the latest Android Runtime (ART) updates that include these changes. This is part of our commitment to give apps a more consistent, secure environment across devices, and to deliver new features and capabilities to users independent of platform releases.

Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Ulepszenia w sklepach z aplikacjami

Android 14 introduces several PackageInstaller APIs that allow app stores to improve their user experience.

Request install approval before downloading

Installing or updating an app might require user approval. For example, when an installer making use of the REQUEST_INSTALL_PACKAGES permission attempts to install a new app. In prior Android versions, app stores can only request user approval after APKs are written to the install session and the session is committed.

Starting with Android 14, the requestUserPreapproval() method lets installers request user approval before committing the install session. This improvement lets an app store defer downloading any APKs until after the installation has been approved by the user. Furthermore, once a user has approved installation, the app store can download and install the app in the background without interrupting the user.

Claim responsibility for future updates

The setRequestUpdateOwnership() method allows an installer to indicate to the system that it intends to be responsible for future updates to an app it is installing. This capability enables update ownership enforcement, meaning that only the update owner is permitted to install automatic updates to the app. Update ownership enforcement helps to ensure that users receive updates only from the expected app store.

Any other installer, including those making use of the INSTALL_PACKAGES permission, must receive explicit user approval in order to install an update. If a user decides to proceed with an update from another source, update ownership is lost.

Update apps at less-disruptive times

App stores typically want to avoid updating an app that is actively in use because this leads to the app's running processes being killed, which potentially interrupts what the user was doing.

Starting with Android 14, the InstallConstraints API gives installers a way to ensure that their app updates happen at an opportune moment. For example, an app store can call the commitSessionAfterInstallConstraintsAreMet() method to make sure that an update is only committed when the user is no longer interacting with the app in question.

Seamlessly install optional splits

With split APKs, features of an app can be delivered in separate APK files, rather than as a monolithic APK. Split APKs allow app stores to optimize the delivery of different app components. For example, app stores might optimize based on the properties of the target device. The PackageInstaller API has supported splits since its introduction in API level 22.

In Android 14, the setDontKillApp() method allows an installer to indicate that the app's running processes shouldn't be killed when new splits are installed. App stores can use this feature to seamlessly install new features of an app while the user is using the app.

Pakiety metadanych aplikacji

从 Android 14 开始,Android 软件包安装程序可让您指定应用元数据(例如数据安全做法),以在 Google Play 等应用商店页面上架。

Wykrywanie, kiedy użytkownicy robią zrzuty ekranu urządzenia

To create a more standardized experience for detecting screenshots, Android 14 introduces a privacy-preserving screenshot detection API. This API lets apps register callbacks on a per-activity basis. These callbacks are invoked, and the user is notified, when the user takes a screenshot while that activity is visible.

Interfejs użytkownika

Działania niestandardowe na arkuszu udostępniania i ulepszone rankingi

Android 14 updates the system sharesheet to support custom app actions and more informative preview results for users.

Add custom actions

With Android 14, your app can add custom actions to the system sharesheet it invokes.

Screenshot of custom actions on the sharesheet.

Improve ranking of Direct Share targets

Android 14 uses more signals from apps to determine the ranking of the direct share targets to provide more helpful results for the user. To provide the most useful signal for ranking, follow the guidance for improving rankings of your Direct Share targets. Communication apps can also report shortcut usage for outgoing and incoming messages.

Direct Share row in the sharesheet, as shown by 1

Obsługa wbudowanych i niestandardowych animacji przewidywanego przejścia wstecz

视频:预测性返回动画

Android 13 在开发者选项背后引入了预测性“返回主屏幕”动画。在已启用开发者选项的受支持应用中使用时,滑回手势会显示动画,表明返回手势会使应用退回到主屏幕。

Android 14 包含针对“预测性返回”的多项改进和新指南:

在此 Android 14 预览版中,所有预测性返回功能都是位于开发者选项背后。请参阅与将您的应用迁移到预测性返回有关的开发者指南,以及与创建自定义应用内转换有关的开发者指南

Zastąpienia ustawień producenta urządzenia z dużym ekranem dla poszczególnych aplikacji

Per-app overrides enable device manufacturers to change the behavior of apps on large screen devices. For example, the FORCE_RESIZE_APP override instructs the system to resize the app to fit display dimensions (avoiding size compatibility mode) even if resizeableActivity="false" is set in the app manifest.

Overrides are intended to improve the user experience on large screens.

New manifest properties enable you to disable some device manufacturer overrides for your app.

Zastępowanie ustawień aplikacji na urządzeniach z dużym ekranem

Zastąpienia dla poszczególnych aplikacji zmieniają zachowanie aplikacji na urządzeniach z dużym ekranem. Na przykład OVERRIDE_MIN_ASPECT_RATIO_LARGE zastąpienie producenta urządzenia ustawia format obrazu aplikacji na 16:9 niezależnie od konfiguracji aplikacji.

Android 14 QPR1 umożliwia użytkownikom stosowanie zastąpienia dla poszczególnych aplikacji za pomocą nowego menu ustawień na urządzeniach z dużym ekranem.

Udostępnianie ekranu aplikacji

App screen sharing enables users to share an app window instead of the entire device screen during screen content recording.

With app screen sharing, the status bar, navigation bar, notifications, and other system UI elements are excluded from the shared display. Only the content of the selected app is shared.

App screen sharing improves productivity and privacy by enabling users to run multiple apps but limit content sharing to a single app.

Inteligentna odpowiedź na klawiaturze Gboard na Pixelu 8 Pro oparta na LLM

On Pixel 8 Pro devices with the December Feature Drop, developers can try out higher-quality smart replies in Gboard powered by on-device Large Language Models (LLMs) running on Google Tensor.

This feature is available as a limited preview for US English in WhatsApp, Line, and KakaoTalk. It requires using a Pixel 8 Pro device with Gboard as your keyboard.

To try it out, first enable the feature in Settings > Developer Options > AiCore Settings > Enable Aicore Persistent.

Next, open a conversation in a supported app to see LLM-powered Smart Reply in Gboard's suggestion strip in response to incoming messages.

Gboard utilizes on-device LLMs to provide higher-quality smart replies.

Grafika

Ścieżki można wyszukiwać i interpolować

Interfejs API Path na Androida to zaawansowany i elastyczny mechanizm tworzenia i renderowania grafiki wektorowej, który umożliwia kreślenie lub wypełnianie ścieżki, tworzenie ścieżki z segmentów linii albo krzywych kwadratowych i krzywych sześciennych, wykonywanie operacji logicznych w celu uzyskania jeszcze bardziej złożonych kształtów lub wszystkich tych elementów jednocześnie. Ograniczeniem jest możliwość sprawdzenia, co tak naprawdę znajduje się w obiekcie ścieżki. Elementy wewnętrzne obiektu są nieprzezroczyste po jego utworzeniu.

Aby utworzyć Path, użyj metod wywoływania takich jak moveTo(), lineTo() i cubicTo(), aby dodać segmenty ścieżki. Nie ma jednak możliwości określenia, jakie segmenty mają się znaleźć na tej ścieżce, więc musisz zachować te informacje w momencie tworzenia.

Począwszy od Androida 14 możesz wysyłać zapytania dotyczące ścieżek, aby dowiedzieć się, co się na nich znajduje. Najpierw musisz uzyskać obiekt PathIterator, korzystając z interfejsu API Path.getPathIterator:

Kotlin

val path = Path().apply {
    moveTo(1.0f, 1.0f)
    lineTo(2.0f, 2.0f)
    close()
}
val pathIterator = path.pathIterator

Java

Path path = new Path();
path.moveTo(1.0F, 1.0F);
path.lineTo(2.0F, 2.0F);
path.close();
PathIterator pathIterator = path.getPathIterator();

Następnie możesz wywołać metodę PathIterator, by iterować po kolei segmenty i pobrać wszystkie niezbędne dane dla każdego z nich. W tym przykładzie użyto obiektów PathIterator.Segment, które gromadzą dane w formie pakietów:

Kotlin

for (segment in pathIterator) {
    println("segment: ${segment.verb}, ${segment.points}")
}

Java

while (pathIterator.hasNext()) {
    PathIterator.Segment segment = pathIterator.next();
    Log.i(LOG_TAG, "segment: " + segment.getVerb() + ", " + segment.getPoints());
}

Funkcja PathIterator ma też wersję next(), która nie przydziela pamięci, i możesz jej użyć do przekazania bufora, aby przechowywać dane punktowe.

Jednym z ważnych zastosowań zapytań o dane Path jest interpolacja. Możesz na przykład chcieć animować (czyli przekształcać) 2 różne ścieżki. Aby jeszcze bardziej uprościć ten przypadek użycia, Android 14 zawiera też metodę interpolate()Path. Zakładając, że 2 ścieżki mają taką samą strukturę wewnętrzną, metoda interpolate() tworzy nowy Path z tym interpolowanym wynikiem. Ten przykład zwraca ścieżkę, która jest połową (interpolacja liniowa 0,5) ścieżki pathotherPath:

Kotlin

val interpolatedResult = Path()
if (path.isInterpolatable(otherPath)) {
    path.interpolate(otherPath, .5f, interpolatedResult)
}

Java

Path interpolatedResult = new Path();
if (path.isInterpolatable(otherPath)) {
    path.interpolate(otherPath, 0.5F, interpolatedResult);
}

Biblioteka Jetpack graphics-path umożliwia korzystanie z podobnych interfejsów API również w starszych wersjach Androida.

Niestandardowe siatki z shaderami wierzchołków i fragmentów

Android has long supported drawing triangle meshes with custom shading, but the input mesh format has been limited to a few predefined attribute combinations. Android 14 adds support for custom meshes, which can be defined as triangles or triangle strips, and can, optionally, be indexed. These meshes are specified with custom attributes, vertex strides, varying, and vertex and fragment shaders written in AGSL.

The vertex shader defines the varyings, such as position and color, while the fragment shader can optionally define the color for the pixel, typically by using the varyings created by the vertex shader. If color is provided by the fragment shader, it is then blended with the current Paint color using the blend mode selected when drawing the mesh. Uniforms can be passed into the fragment and vertex shaders for additional flexibility.

Renderowanie bufora sprzętowego w Canvas

To assist in using Android's Canvas API to draw with hardware acceleration into a HardwareBuffer, Android 14 introduces HardwareBufferRenderer. This API is particularly useful when your use case involves communication with the system compositor through SurfaceControl for low-latency drawing.