头图

Author/Florina Muntenescu, Android Developer Advocate

Android Jetpack is a set of libraries, tools, and guidelines that help developers follow best practices, reduce template code, and write consistent code that runs on different Android versions and devices. Today, 84% of the top 1,000 apps on Google Play use Jetpack.

Let us take a look at the latest updates of Jetpack. If you have watched the ☟Jetpack update list☟ presentation, this article will make further additions, please don’t miss it!

https://www.bilibili.com/video/BV1964y1d7p3/?aid=758249804&cid=341875570&page=1

△ Jetpack update list

Stable Channel Update List

CameraX

CameraX library provides a unified API interface for accessing camera functions across operating system versions, including compatibility fixes and workarounds for specific devices. Some of the latest improvements to the library address common functional requirements, including support for adjusting exposure compensation and access to more detailed information about camera status and functions. In addition, it is now possible to change camera settings such as FPS range Camera2Interop The library also brings support for the latest device and operating system features, including high dynamic range (HDR) preview, zoom rate control, and support for Android's Do Not Disturb mode. But perhaps most importantly, the CameraX library continues to solve performance issues, making image capture and initialization faster, especially on older devices.

Hilt

Hilt is a dependency injection solution built on Dagger recommended by Jetpack. As part of the transition to the stable version, Hilt's ViewModel support has risen to the core Hilt Android API, and SavedStateHandle has been added as a default dependency in ViewModelComponent In addition, Hilt is now integrated with Navigation and Compose: You can get an annotated Hilt ViewModel whose scope is the destination or the navigation map itself. Developers have already started using Hilt in their applications, please check out the blog see what experience they have gained.

Paging 3.0

Paging library allows you to load and display small pieces of data to improve the consumption of network and system resources. This version is characterized by a complete rewrite using Kotlin, first-class support for coroutines and Flow, asynchronous loading with RxJava and Guava primitives, and comprehensive improvements to the repository and presentation layer.

Compared with Paging 2, version 3.0 has a great improvement in usability. Partial and phased migration is considered when rewriting, so that developers can make the transition according to their own plans. Please check Paging 3.0 documents and Paging 3.0 codelab for more details and hands-on practice.

ConstraintLayout and MotionLayout

ConstraintLayout (a flexible system for designing layouts in Jetpack) and MotionLayout (an API for managing motion and widget animation) have now released stable versions. MotionLayout now supports foldable devices, image filters and motion effects. Please watch this Google I/O talk learn more about the new content of design tools.

Security Crypto

Security Crypto library allows you to safely and easily encrypt files and SharedPreferences . If you want to encrypt SharedPreferences EncryptedSharedPreferences object with the appropriate key and scheme, and then use it SharedPreferences

val prefs: SharedPreferences = EncryptedSharedPreferences.create(
        context,
        "prefs_file_name",
        mainKey,
        prefKeyEncryptionScheme = AES256_SIV,
        prefValueEncryptionScheme = AES256_GCM,
)
// Use the resulting SharedPreferences object as usual.
prefs.edit()
    .putBoolean("show_completed", true)
    .apply()

Fragment

In the past year, we have worked hard on the Fragment library, cleaning up its internal implementation and reducing undocumented behavior, making it easier for developers to follow best practices in their applications and write reliable test. This lays the foundation for future improvements of the library, such as supporting multiple back stacks in Navigation, which may require some work to implement the strict implementation of the API contract. Specifically, after updating the library, please pay close attention to your tests. You can check Fragment's release note for specific cases that need attention.

The latest version of Fragment also introduced ActivityResult integration, making it possible to register Activity results from the fragment. Fragment also adds a new FragmentOnAttachListener interface to replace the less flexible onAttachFragment method. Existing code that rewrites this method in Fragment or FragmentActivity can still run normally, but we have deprecated onAttachFragment to prevent new code from accidentally adopting less flexible practices.

// Obtain the fragment manager. May be a childFragmentManager,
// if in a fragment, to observe child attachment.
val fm = supportFragmentManager


val listener = FragmentOnAttachListener {
    fragmentManager, fragment ->
  // Respond to the fragment being attached.
}


fm.addFragmentOnAttachListener(listener)

Beta channel update list

Once the development of the library's functions is completed, it will enter the Beta version to maintain stability. After that, only if major issues are discovered or based on community feedback, will the API be modified.

DataStore

DataStore provides a robust data storage solution that solves the shortcomings of SharedPreferences, while keeping the API interface simple and highly available. DataStore brings support for best practices, such as Kotlin coroutines and Flow and RxJava. DataStore allows you to store key-value pairs through Preference DataStore, or store type objects in protobuff format through Proto DataStore. You can also insert own serialization solution, such as Kotlin Serialization.

Alpha channel update list

The Alpha version of the library is under active development: APIs may be added, changed or deleted, but the content in the library is tested and generally has a high degree of usability.

AppSearch

AppSearch is a new on-device search library that provides high-performance and feature-rich full-text search functions. Compared with SQLite, AppSearch supports multiple languages, simplifies the sorting of query results, and has lower latency for indexing and searching large data sets.

AppSearch 1.0.0-alpha01 brings LocalStorage support, which allows your application to manage structured data, called "documents", and then query it. Your application uses "pattern types" to define the structure. For example, you can model a message as a pattern type, which includes data such as subject, body, and sender.

Use the builder to create pattern-type files, and then add them to the storage. The query "body:fruit" will retrieve all documents with the word "fruit" in the body of the message.

In Android S, AppSearch will also provide PlatformStorage, allowing you to safely share data in your application with other applications, and because there is no need to link additional native libraries, the binary size of your application will be smaller. Please note that AppSearch is currently not available in Jetpack because it has not been developed for the Android S SDK.

△ Android S+ 上的集中存储,用于整合到全设备搜索中

△ Centralized storage on Android S+ for integration into all-device search

Room

Room is the data persistence layer we recommend everyone to adopt to provide more usability and security on the platform.

Room 2.4.0-alpha brings support for automatic migration . When your database schema changes, you can now declare a @AutoMigration to indicate which version you want to migrate from, and Room will generate the migration result for you. For more complex migrations, you can still use the Migration class.

@Database(
-   version = 1,
+   version = 2,
    entities = { Doggos.class },
+   autoMigrations = {
+         @AutoMigration (from = 1, to = 2)
+     }
  )
public abstract class DoggosDatabase extends RoomDatabase { }

Room 2.3.0 stable version brings Kotlin symbol processing . In our benchmark test of Kotlin code, its speed is 2 times faster than KAPT, and it also brings built-in enumeration and RxJava3 stand by.

Room also introduced the QueryCallback class, which is used to provide callbacks when executing SQLite statements to simplify tasks such as logging. In addition, a new @ProvidedTypeConverter note has been added, which allows you to be more flexible when creating type converters.

WorkManager

WorkManager library is a method recommended by Android to schedule asynchronous tasks that can be postponed, even if the application exits or the device restarts. WorkManager has improved the reliability of task adjustment to ensure that all tasks are executed, and provides various solutions for specific Android OS versions.

The latest version of WorkManager improves 's support for multi-process applications , including the performance advantages of unifying work request scheduling into one process, and limiting database growth when scheduling many requests.

Version 2.7 is now in the alpha version, developed for the Android S SDK, and adapted to the new front-end restrictions of the platform. Please watch Effective Background Tasks on Android talk for more details.

Background Tasks Inspector is now available in Android Studio Arctic Fox, you can easily view and debug WorkManager tasks when using the latest version of the library:

△ Background Tasks Inspector

△ Background Tasks Inspector

Navigation

Jetpack's Navigation library is a framework for navigation in applications. It now provides support for multiple back stacks and simplifies the situation where the destination is at the same depth, such as the bottom navigation bar.

Macrobenchmark

The Macrobenchmark library extends Jetpack's benchmarking range to application startup and comprehensive behaviors, such as scrolling performance. You can use this library remotely to track metrics in continuous integration testing, or use it locally with the profiling results in Android Studio. Please watch Google I/O talk further details.

For developers who want to integrate more closely with Google Assistant, the Google Shortcuts library provides a way to provide actions to Google Assistant and other Google services ShortcutInfo

You can send up to 15 shortcuts at once through ShortcutManager to display in Google Assistant and other services, making them available for voice and other interactions.

To achieve this, you need Intent and a capability binding; this binding provides semantically meaningful information, which will help Google services find out what to display to the user The best way.

// expose a "Cappuccino" action to Google Assistant and other services
ShortcutInfoCompat siCompat =
  ShortcutInfoCompat.Builder(ctx, "id_cappuccino")
    .setShortLabel("Cappuccino")
    .setIntent(Intent(ctx, OrderCappuccino::class.java))
    .addCapabilityBinding(
        "actions.intent.ORDER_MENU_ITEM",
        "menuItem.name",
        asList("cappuccino")
    )
    .build()


ShortcutManagerCompat.pushDynamicShortcut(ctx, siCompat)

EmojiCompat

All user-generated content in your app contains 🎉, and supporting modern emoji is the key to making your app✨! EmojiCompat library supports modern emojis in API 19 and higher. It has been transferred to a new component: emoji2:emoji2, replacing the previous :emoji:emoji component. The new emoji2 library uses the AppStartup library to add the 🪄 automatic configuration function (you don't need to add any code 💻 to display 🐼 )!

AppCompat has added emoji2 since AppCompat 1.4. If your app uses AppCompat, users will be able to see modern emoji ⭐ without further configuration. For applications that do not use AppCompat, you can add :emoji2:emoji2-views. For custom TextViews, you can use the practical methods in :emoji2:emoji2-views-helpers, or support modern emojis by inheriting the AppCompat view.

Jetpack Compose

Jetpack Compose is a modern toolkit for building native UI on Android, simplifying and accelerating UI development on Android. Jetpack Compose is currently in the Beta version and plans to release the stable version in July. Many of the libraries mentioned in this article, as well as other libraries you may already be using, are specifically designed to integrate with Jetpack Compose. Including Activity, ViewModel, Navigation and Hilt, all these libraries can help you use Compose in your application more smoothly. Please watch Google I/O talk further details.

Different device types

Jetpack makes it easier for you to develop for different types of devices, including foldable devices, large screen devices and Wear devices. We have introduced new specifications for large-screen device development, and improved Jetpack libraries such as WindowManager and SlidingPaneLayout Read this blog post more information.

summary

The above is an overview of what's new in Jetpack. Please read AndroidX's release notes to understand all the update details of each library, and watch the Google I/O talk learn more about some of these libraries.

If you have any feedback or questions, please submit them to us via the QR code below. Your question may appear in the next FAQ and be answered. thank you for your support!


Android开发者
404 声望2k 粉丝

Android 最新开发技术更新,包括 Kotlin、Android Studio、Jetpack 和 Android 最新系统技术特性分享。更多内容,请关注 官方 Android 开发者文档。