Android 14 mang đến cho nhà phát triển các tính năng và API tuyệt vời. Nội dung sau đây giúp bạn tìm hiểu các tính năng cho ứng dụng cũng như làm quen với các API liên quan.
Để biết danh sách chi tiết về các API đã thêm, sửa đổi và xoá, hãy đọc báo cáo điểm khác biệt về API. Để biết thông tin chi tiết về các API đã thêm, hãy truy cập vào tài liệu tham khảo về API Android. Đối với Android 14, hãy tìm các API đã thêm trong API cấp 34. Để tìm hiểu những thay đổi của nền tảng có thể tác động đến ứng dụng của bạn, hãy nhớ tham khảo các thay đổi về hành vi của Android 14 đối với ứng dụng nhắm đến Android 14 và tất cả ứng dụng.
Quốc tế hoá
Lựa chọn ưu tiên về ngôn ngữ cho mỗi ứng dụng
Android 14 expands on the per-app language features that were introduced in Android 13 (API level 33) with these additional capabilities:
Automatically generate an app's
localeConfig
: Starting with Android Studio Giraffe Canary 7 and AGP 8.1.0-alpha07, you can configure your app to support per-app language preferences automatically. Based on your project resources, the Android Gradle plugin generates theLocaleConfig
file and adds a reference to it in the final manifest file, so you no longer have to create or update the file manually. AGP uses the resources in theres
folders of your app modules and any library module dependencies to determine the locales to include in theLocaleConfig
file.Dynamic updates for an app's
localeConfig
: Use thesetOverrideLocaleConfig()
andgetOverrideLocaleConfig()
methods inLocaleManager
to dynamically update your app's list of supported languages in the device's system settings. Use this flexibility to customize the list of supported languages per region, run A/B experiments, or provide an updated list of locales if your app utilizes server-side pushes for localization.App language visibility for input method editors (IMEs): IMEs can utilize the
getApplicationLocales()
method to check the language of the current app and match the IME language to that language.
API Biến tố ngữ pháp
3 billion people speak gendered languages: languages where grammatical categories—such as nouns, verbs, adjectives, and prepositions—inflect according to the gender of people and objects you talk to or about. Traditionally, many gendered languages use masculine grammatical gender as the default or generic gender.
Addressing users in the wrong grammatical gender, such as addressing women in masculine grammatical gender, can negatively impact their performance and attitude. In contrast, a UI with language that correctly reflects the user's grammatical gender can improve user engagement and provide a more personalized and natural-sounding user experience.
To help you build a user-centric UI for gendered languages, Android 14 introduces the Grammatical Inflection API, which lets you add support for grammatical gender without refactoring your app.
Lựa chọn ưu tiên theo khu vực
Regional preferences enable users to personalize temperature units, the first day of the week, and numbering systems. A European living in the United States might prefer temperature units to be in Celsius rather than Fahrenheit and for apps to treat Monday as the beginning of the week instead of the US default of Sunday.
New Android Settings menus for these preferences provide users with a
discoverable and centralized location to change app preferences. These
preferences also persist through backup and restore. Several APIs and
intents—such as
getTemperatureUnit
and
getFirstDayOfWeek
—
grant your app read access to user preferences, so your app can adjust how it
displays information. You can also register a
BroadcastReceiver
on
ACTION_LOCALE_CHANGED
to handle locale configuration changes when regional preferences change.
To find these settings, open the Settings app and navigate to System > Languages & input > Regional preferences.


Hỗ trợ tiếp cận
Điều chỉnh tỷ lệ phông chữ phi tuyến tính lên đến 200%
Kể từ Android 14, hệ thống sẽ hỗ trợ việc chuyển tỷ lệ phông chữ lên đến 200%, cung cấp người dùng có thị lực kém có thêm các lựa chọn hỗ trợ tiếp cận phù hợp với ngôn ngữ Web Nguyên tắc về khả năng tiếp cận nội dung (WCAG).
Để ngăn các thành phần văn bản cỡ lớn trên màn hình bị chuyển tỷ lệ quá lớn, hệ thống áp dụng đường cong tỷ lệ phi tuyến tính. Chiến lược điều chỉnh tỷ lệ này có nghĩa là văn bản lớn không chuyển tỷ lệ theo cùng mức độ với văn bản nhỏ hơn. Việc chuyển tỷ lệ phông chữ phi tuyến tính giúp bảo toàn thứ bậc tỷ lệ giữa các phần tử có kích thước khác nhau, trong khi giảm thiểu vấn đề với việc chuyển tỷ lệ văn bản tuyến tính ở mức cao (chẳng hạn như văn bản bị cắt hoặc văn bản trở nên khó đọc hơn do kích thước trên màn hình cực kỳ lớn).
Kiểm thử ứng dụng bằng tỷ lệ phông chữ phi tuyến tính

Nếu bạn đã sử dụng đơn vị pixel được điều chỉnh theo tỷ lệ (sp) để xác định kích thước văn bản, thì các tuỳ chọn bổ sung và cải tiến về tỷ lệ này sẽ tự động áp dụng cho văn bản trong ứng dụng. Tuy nhiên, bạn vẫn nên kiểm thử giao diện người dùng với kích thước phông chữ tối đa được bật (200%) để đảm bảo ứng dụng áp dụng kích thước phông chữ chính xác và có thể sử dụng kích thước phông chữ lớn hơn mà không ảnh hưởng đến khả năng hữu dụng.
Để bật kích thước phông chữ 200%, hãy làm theo các bước sau:
- Mở ứng dụng Cài đặt rồi chuyển đến phần Hỗ trợ tiếp cận > Văn bản và kích thước hiển thị.
- Đối với tuỳ chọn Kích thước phông chữ, hãy nhấn vào biểu tượng dấu cộng (+) cho đến khi bật chế độ cài đặt kích thước phông chữ tối đa, như trong hình ảnh kèm theo phần này.
Sử dụng đơn vị pixel được điều chỉnh theo tỷ lệ (sp) đối với kích thước văn bản
Hãy nhớ luôn chỉ định kích thước văn bản theo đơn vị sp. Khi ứng dụng của bạn sử dụng đơn vị sp, Android có thể áp dụng kích thước văn bản mà người dùng ưu tiên và chuyển tỷ lệ văn bản một cách thích hợp.
Đừng sử dụng đơn vị sp cho khoảng đệm hoặc xác định chiều cao của thành phần hiển thị giả định khoảng đệm ngầm ẩn: kích thước sp tỷ lệ phông chữ phi tuyến tính có thể không tỷ lệ, vì vậy 4sp + 20 sp có thể không bằng 24 sp.
Chuyển đổi đơn vị pixel được điều chỉnh theo tỷ lệ (sp)
Sử dụng TypedValue.applyDimension()
để chuyển đổi từ đơn vị sp sang pixel và sử dụng TypedValue.deriveDimension()
để chuyển đổi pixel thành sp. Các phương thức này tự động áp dụng đường cong tỷ lệ phi tuyến tính thích hợp.
Tránh mã hoá cứng phương trình bằng
Configuration.fontScale
hoặc
DisplayMetrics.scaledDensity
. Vì việc chuyển tỷ lệ phông chữ
phi tuyến tính, trường scaledDensity
không còn chính xác nữa. fontScale
trường này chỉ nên được sử dụng cho mục đích thông tin vì phông chữ không còn được sử dụng nữa
được điều chỉnh theo tỷ lệ với một giá trị vô hướng duy nhất.
Sử dụng đơn vị sp cho lineHeight
Luôn xác định android:lineHeight
bằng cách sử dụng đơn vị sp thay vì dp, vì vậy, chiều cao dòng sẽ điều chỉnh theo văn bản của bạn. Nếu không, nếu văn bản của bạn là sp nhưng lineHeight
ở dạng dp hoặc px, thì văn bản sẽ không theo tỷ lệ và trông chật chội.
TextView sẽ tự động sửa lineHeight
để giữ nguyên tỷ lệ bạn dự định, nhưng chỉ khi cả textSize
và lineHeight
được xác định theo đơn vị sp.
Máy ảnh và nội dung nghe nhìn
Ultra HDR cho hình ảnh

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.
Thu phóng, Lấy nét, Xem sau và nhiều tính năng khác trong tiện ích máy ảnh
Android 14 nâng cấp và cải thiện tiện ích máy ảnh, cho phép các ứng dụng xử lý trong thời gian dài hơn, nhờ đó hình ảnh được cải thiện bằng cách sử dụng các thuật toán chuyên sâu về điện toán như chụp ảnh ở điều kiện ánh sáng yếu trên các thiết bị được hỗ trợ. Các tính năng này mang đến cho người dùng trải nghiệm mạnh mẽ hơn nữa khi sử dụng các tính năng của tiện ích máy ảnh. Sau đây là một số ví dụ về những điểm cải tiến này:
- Tính năng ước tính độ trễ xử lý ảnh tĩnh động cung cấp thông tin ước tính độ trễ chụp ảnh tĩnh chính xác hơn nhiều dựa trên điều kiện môi trường và cảnh hiện tại. Gọi
CameraExtensionSession.getRealtimeStillCaptureLatency()
để lấy đối tượngStillCaptureLatency
có hai phương thức ước tính độ trễ. Phương thứcgetCaptureLatency()
trả về độ trễ ước tính giữaonCaptureStarted
vàonCaptureProcessStarted()
, còn phương thứcgetProcessingLatency()
trả về độ trễ ước tính giữaonCaptureProcessStarted()
và khung hình đã xử lý cuối cùng. - Hỗ trợ các lệnh gọi lại tiến trình chụp để ứng dụng có thể hiển thị tiến trình hiện tại của các thao tác xử lý ảnh chụp tĩnh, chạy trong thời gian dài. Bạn có thể kiểm tra xem tính năng này có dùng được với
CameraExtensionCharacteristics.isCaptureProcessProgressAvailable
hay không. Nếu có, bạn sẽ triển khai lệnh gọi lạionCaptureProcessProgressed()
, trong đó tiến trình (từ 0 đến 100) được truyền vào dưới dạng tham số. Siêu dữ liệu dành riêng cho tiện ích, chẳng hạn như
CaptureRequest.EXTENSION_STRENGTH
để điều chỉnh mức độ của một hiệu ứng tiện ích, chẳng hạn như mức độ làm mờ nền bằngEXTENSION_BOKEH
.Tính năng Xem sau cho tính năng Chụp ảnh tĩnh trong các tiện ích máy ảnh, cung cấp hình ảnh được xử lý ít hơn và nhanh hơn so với hình ảnh cuối cùng. Nếu một tiện ích tăng độ trễ xử lý, thì bạn có thể cung cấp hình ảnh sau khi xem làm phần giữ chỗ để cải thiện trải nghiệm người dùng và sau đó chuyển sang hình ảnh cuối cùng. Bạn có thể kiểm tra xem tính năng này có dùng được với
CameraExtensionCharacteristics.isPostviewAvailable
hay không. Sau đó, bạn có thể truyềnOutputConfiguration
đếnExtensionSessionConfiguration.setPostviewOutputConfiguration
.Hỗ trợ
SurfaceView
cho phép đường dẫn kết xuất bản xem trước được tối ưu hoá và tiết kiệm điện năng hơn.Hỗ trợ tính năng nhấn để lấy nét và thu phóng trong quá trình sử dụng tiện ích.
Thu phóng trong cảm biến
When REQUEST_AVAILABLE_CAPABILITIES_STREAM_USE_CASE
in
CameraCharacteristics
contains
SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW
, your app
can use advanced sensor capabilities to give a cropped RAW stream the same
pixels as the full field of view by using a CaptureRequest
with a RAW target that has stream use case set to
CameraMetadata.SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW
.
By implementing the request override controls, the updated camera gives users
zoom control even before other camera controls are ready.
Âm thanh USB không bị mất dữ liệu
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.
Công cụ và năng suất của nhà phát triển
Trình quản lý thông tin xác thực
Android 14 adds Credential Manager as a platform API, with additional support back to Android 4.4 (API level 19) devices through a Jetpack Library using Google Play services. Credential Manager aims to make sign-in easier for users with APIs that retrieve and store credentials with user-configured credential providers. Credential Manager supports multiple sign-in methods, including username and password, passkeys, and federated sign-in solutions (such as Sign-in with Google) in a single API.
Passkeys provide many advantages. For example, passkeys are built on industry standards, can work across different operating systems and browser ecosystems, and can be used with both websites and apps.
For more information, see the Credential Manager and passkeys documentation and the blogpost about Credential Manager and passkeys.
Health Connect
Health Connect is an on-device repository for user health and fitness data. It allows users to share data between their favorite apps, with a single place to control what data they want to share with these apps.
On devices running Android versions prior to Android 14, Health Connect is available to download as an app on the Google Play store. Starting with Android 14, Health Connect is part of the platform and receives updates through Google Play system updates without requiring a separate download. With this, Health Connect can be updated frequently, and your apps can rely on Health Connect being available on devices running Android 14 or higher. Users can access Health Connect from the Settings in their device, with privacy controls integrated into the system settings.


Health Connect includes several new features in Android 14, such as exercise routes, allowing users to share a route of their workout which can be visualized on a map. A route is defined as a list of locations saved within a window of time, and your app can insert routes into exercise sessions, tying them together. To ensure that users have complete control over this sensitive data, users must allow sharing individual routes with other apps.
For more information, see the Health Connection documentation and the blogpost on What's new in Android Health.
Nội dung cập nhật OpenJDK 17
Android 14 tiếp tục công cuộc làm mới các thư viện cốt lõi của Android để phù hợp với các tính năng trong bản phát hành OpenJDK LTS mới nhất, bao gồm cả bản cập nhật thư viện và tính năng hỗ trợ ngôn ngữ Java 17 cho các nhà phát triển ứng dụng và nền tảng.
Bao gồm các tính năng và điểm cải tiến sau đây:
- Cập nhật tính năng hỗ trợ Java 17 cho khoảng 300 lớp
java.base
. - Khối văn bản (Text Blocks) ra mắt các giá trị cố định dạng chuỗi nhiều dòng bằng ngôn ngữ lập trình Java.
- So khớp mẫu cho instanceof, cho phép một đối tượng được xem là có một kiểu cụ thể trong
instanceof
mà không cần thêm bất cứ biến nào. - Lớp kín (sealed classes) cho phép bạn hạn chế các lớp và giao diện có thể mở rộng hoặc triển khai các lớp đó.
Nhờ các bản cập nhật hệ thống Google Play (Project Mainline), hơn 600 triệu thiết bị được phép nhận các bản cập nhật Android Runtime (ART) mới nhất có các thay đổi này. Đây là một phần trong cam kết của chúng tôi nhằm cung cấp cho các ứng dụng một môi trường nhất quán, bảo mật hơn trên các thiết bị, đồng thời cung cấp các tính năng và chức năng mới cho người dùng độc lập với các bản phát hành nền tảng.
Java và OpenJDK là các nhãn hiệu hoặc nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Những điểm cải tiến cho cửa hàng ứng dụng
Android 14 giới thiệu một số API PackageInstaller
cho phép cửa hàng ứng dụng cải thiện trải nghiệm người dùng.
Yêu cầu phê duyệt lượt cài đặt trước khi tải xuống
Có thể bạn phải yêu cầu người dùng phê duyệt việc cài đặt hoặc cập nhật ứng dụng.
Ví dụ: khi trình cài đặt sử dụng quyền REQUEST_INSTALL_PACKAGES
cố gắng cài đặt một ứng dụng mới. Trong các phiên bản Android trước, cửa hàng ứng dụng chỉ có thể yêu cầu người dùng phê duyệt sau khi các tệp APK được ghi vào phiên cài đặt còn phiên hoạt động thì được cam kết.
Kể từ Android 14, phương thức requestUserPreapproval()
sẽ cho phép trình cài đặt yêu cầu người dùng phê duyệt trước khi xác nhận phiên cài đặt. Điểm cải tiến này cho phép cửa hàng ứng dụng trì hoãn việc tải mọi tệp APK xuống cho đến khi người dùng phê duyệt quá trình cài đặt. Hơn nữa, sau khi người dùng phê duyệt việc cài đặt, cửa hàng ứng dụng có thể tải và cài đặt ứng dụng ở chế độ nền mà không làm gián đoạn người dùng.
Tuyên bố trách nhiệm đối với các bản cập nhật trong tương lai
Phương thức setRequestUpdateOwnership()
cho phép trình cài đặt cho hệ thống biết rằng sau này trình cài đặt dự định sẽ chịu trách nhiệm về các bản cập nhật của ứng dụng đang cài đặt. Tính năng này cho phép thực thi theo quyền sở hữu bản cập nhật, nghĩa là chỉ chủ sở hữu bản cập nhật mới được phép tự động cài đặt bản cập nhật cho ứng dụng. Việc thực thi theo quyền sở hữu bản cập nhật giúp đảm bảo rằng người dùng chỉ nhận được bản cập nhật từ cửa hàng ứng dụng theo đúng mong đợi.
Mọi trình cài đặt khác (bao gồm cả những trình cài đặt sử dụng quyền INSTALL_PACKAGES
) phải nhận được sự chấp thuận rõ ràng của người dùng để có thể cài đặt bản cập nhật. Nếu người dùng quyết định tiếp tục cập nhật từ một nguồn khác, thì quyền sở hữu bản cập nhật sẽ bị mất.
Cập nhật ứng dụng vào những thời điểm ít gây gián đoạn hơn
Các cửa hàng ứng dụng thường muốn tránh cập nhật một ứng dụng đang được sử dụng, vì việc này dẫn đến việc các quy trình đang chạy của ứng dụng bị dừng, có khả năng làm gián đoạn công việc mà người dùng đang thực hiện.
Kể từ Android 14, InstallConstraints
API sẽ giúp trình cài đặt có thể đảm bảo quá trình cập nhật ứng dụng diễn ra đúng lúc. Ví dụ: một cửa hàng ứng dụng có thể gọi phương thức commitSessionAfterInstallConstraintsAreMet()
để đảm bảo rằng bản cập nhật chỉ được cam kết khi người dùng không còn tương tác với ứng dụng có liên quan.
Cài đặt các phần phân tách không bắt buộc sao cho liền mạch
Nhờ tệp APK phân tách, nhiều tính năng của một ứng dụng có thể được phân phối trong các tệp APK riêng biệt, thay vì dưới dạng tệp APK nguyên khối. Tệp APK phân tách cho phép cửa hàng ứng dụng tối ưu hoá việc phân phối nhiều thành phần của ứng dụng. Ví dụ: có thể các cửa hàng ứng dụng sẽ tối ưu hoá dựa trên thuộc tính của thiết bị mục tiêu. PackageInstaller
API đã hỗ trợ các phần phân tách kể từ khi ra mắt trong API cấp 22.
Trong Android 14, phương thức setDontKillApp()
sẽ cho phép trình cài đặt cho biết rằng các quy trình đang chạy của ứng dụng sẽ không bị tắt khi các phần phân tách mới được cài đặt. Các cửa hàng ứng dụng có thể sử dụng tính năng này để cài đặt liền mạch những tính năng mới của một ứng dụng trong khi người dùng đang sử dụng ứng dụng đó.
Gói siêu dữ liệu ứng dụng
Starting in Android 14, the Android package installer lets you specify app metadata, such as data safety practices, to include on app store pages such as Google Play.
Phát hiện thời điểm người dùng chụp ảnh màn hình thiết bị
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.
Trải nghiệm người dùng
Các thao tác tuỳ chỉnh trên Trang chia sẻ nội dung và cách cải thiện thứ hạng
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.

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.

Hỗ trợ ảnh động tích hợp sẵn và ảnh động tuỳ chỉnh cho tính năng Xem trước thao tác quay lại
Android 13 introduced the predictive back-to-home animation behind a developer option. When used in a supported app with the developer option enabled, swiping back shows an animation indicating that the back gesture exits the app back to the home screen.
Android 14 includes multiple improvements and new guidance for Predictive Back:
- You can set
android:enableOnBackInvokedCallback=true
to opt in to predictive back system animations per-Activity instead of for the entire app. - We've added new system animations to accompany the back-to-home animation from Android 13. The new system animations are cross-activity and cross-task, which you get automatically after migrating to Predictive Back.
- We've added new Material Component animations for Bottom sheets, Side sheets, and Search.
- We've created design guidance for creating custom in-app animations and transitions.
- We've added new APIs to support custom in-app transition animations:
handleOnBackStarted
,handleOnBackProgressed
,handleOnBackCancelled
in
OnBackPressedCallback
onBackStarted
,onBackProgressed
,onBackCancelled
in
OnBackAnimationCallback
- Use
overrideActivityTransition
instead ofoverridePendingTransition
for transitions that respond as the user swipes back.
With this Android 14 preview release, all features of Predictive Back remain behind a developer option. See the developer guide to migrate your app to predictive back, as well as the developer guide to creating custom in-app transitions.
Chế độ ghi đè cho mỗi ứng dụng của nhà sản xuất thiết bị có màn hình lớn
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.
Ghi đè cho mỗi ứng dụng dành cho người dùng màn hình lớn
Tính năng ghi đè cho mỗi ứng dụng thay đổi hành vi của ứng dụng trên thiết bị có màn hình lớn. Ví dụ: chế độ ghi đè của nhà sản xuất thiết bị OVERRIDE_MIN_ASPECT_RATIO_LARGE
đặt tỷ lệ khung hình của ứng dụng thành 16:9 bất kể cấu hình của ứng dụng.
Android 14 QPR1 cho phép người dùng áp dụng chế độ ghi đè cho mỗi ứng dụng thông qua trình đơn cài đặt mới trên các thiết bị có màn hình lớn.
Chia sẻ màn hình ứng dụng
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.
Tính năng Trả lời thông minh dựa trên LLM trong Gboard trên Pixel 8 Pro
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.
Đồ hoạ
Đường dẫn có thể truy vấn và nội suy
Android's Path
API is a powerful and flexible mechanism for
creating and rendering vector graphics, with the ability to stroke or fill a
path, construct a path from line segments or quadratic or cubic curves, perform
boolean operations to get even more complex shapes, or all of these
simultaneously. One limitation is the ability to find out what is actually in a
Path object; the internals of the object are opaque to callers after creation.
To create a Path
, you call methods such as
moveTo()
, lineTo()
, and
cubicTo()
to add path segments. But there has been no way to
ask that path what the segments are, so you must retain that information at
creation time.
Starting in Android 14, you can query paths to find out what's inside of them.
First, you need to get a PathIterator
object using the
Path.getPathIterator
API:
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();
Next, you can call PathIterator
to iterate through the segments
one by one, retrieving all of the necessary data for each segment. This example
uses PathIterator.Segment
objects, which packages up the data
for you:
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()); }
PathIterator
also has a non-allocating version of next()
where you can pass
in a buffer to hold the point data.
One of the important use cases of querying Path
data is interpolation. For
example, you might want to animate (or morph) between two different paths. To
further simplify that use case, Android 14 also includes the
interpolate()
method on Path
. Assuming the two paths have
the same internal structure, the interpolate()
method creates a new Path
with that interpolated result. This example returns a path whose shape is
halfway (a linear interpolation of .5) between path
and otherPath
:
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); }
The Jetpack graphics-path library enables similar APIs for earlier versions of Android as well.
Lưới tuỳ chỉnh với chương trình đổ bóng đỉnh và mảnh
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.
Trình kết xuất vùng đệm phần cứng cho 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.