头图

By Amanda Alexander, Product Manager, Android

Android Jetpack is the key to Modern Android Development (MAD), a suite of over 100 libraries, tools, and guides to help developers follow best practices, reduce template code, and write in Code that behaves consistently across Android versions and devices, allowing you to focus on implementing unique features in your app.

In Google Play, the vast majority of applications use Jetpack to implement the application architecture. Today, over 90% of the top 1,000 apps use Jetpack .

This article is the highlight of a recent update to Jetpack and an extension of the I/O talk: What's New in Jetpack !

Next, we'll cover Jetpack's updates in three main areas:

  1. Architecture libraries and guides;
  2. Application performance optimization;
  3. User interface library and guides.

And a summary of some other key updates.

1. Architecture library and guide

The application architecture library and its components ensure robustness, testability, and maintainability of applications.

data persistence

Room is our recommended data persistence layer that provides an abstraction layer on top of SQLite, improving the usability and security of the platform.

In Room 2.4, support for Kotlin Symbol Processing (KSP) has been stabilized. In our benchmarks against Kotlin code, KSP has twice the speedup over KAPT. Room 2.4 also has built-in support for enums and RxJava3, as well as full support for Kotlin 1.6.

We've rewritten the entire library in Kotlin starting with Room 2.5. This change lays the groundwork for future Kotlin-related improvements while being binary compatible with previous versions written in the Java programming language. This release also has built-in support for Paging 3.0, which allows Room to return a PagingSource object by using the room-paging component. In addition, since Room supports association lookups using multiple maps (nested Maps and Arrays), developers can now use JOIN queries without defining additional data structures.

 @Query("SELECT * FROM Artist 
    JOIN Song ON Artist.artistName = 
    Song.songArtistName")
fun getArtistToSongs(): Map<Artist, List<Song>>

△ Association lookup method using multimap as return value

AutoMigrations has been updated to further simplify database migrations with support for additional annotations and properties. Among them, a new attribute has been added to the @Database annotation, which can be used to define which two versions need to be automatically migrated. And when Room needs some additional information (such as table or column modification information), you can use the @AutoMigration annotation to specify the input.

 Database(
  version = MyDb.LATEST_VERSION,
  autoMigrations = {
    @AutoMigration(from = 1, to = 2,
      spec = MyDb.MyMigration.class),
    @AutoMigration(from = 2, to = 3)
  }
)
public abstract class MyDb
    extends RoomDatabase {
  ...

DataStore

The DataStore library is a robust and reliable data storage solution that solves the problems of SharedPreferences. If you want to learn how to use this powerful alternative in various SharedPreferences application scenarios, you can check out the MAD Skills: DataStore series of articles and videos, which covers how to test the use of the DataStore library in your application, how to cooperate with Dependency Injection Using DataStore, and how to migrate from SharedPreference to Proto DataStore.

Incremental data acquisition

The Paging library allows you to load and display a small fraction of the overall data, improving network and system resource consumption. You can elegantly load app data incrementally with RecyclerViews or Compose lazy lists.

Paging 3.1 provides stable support for Rx and Guava integration, providing a Java-edition alternative to the Kotlin coroutines used natively by Paging. This release also improves handling of invalid race conditions with a new return type LoadResult.Invalid to represent invalid or expired data. This release also improves handling of no-op loads and manipulating empty pages through the new onPagesPresented and addOnPagesUpdatedListener APIs.

To learn more about Paging 3, see the new simplified tutorial on the Android Developers site: Paging Basics Codelab , which describes how to integrate the Paging library in an app that contains lists.

Define the in-app navigation model

The Navigation library is a framework for moving between destinations in an app.

The Navigation component is now integrated into Jetpack Compose via the navigation-compose component, allowing composable functions as destinations in your app.

The optimized Multiple Back Stacks function makes it easier for the Navigation component to record the state. NavigationUI can now automatically store and restore the state of pop destinations, which means developers can support multiple back stacks without changing any code.

Support for large-screen devices is further enhanced by the Navigation-fragment component, which provides a pre-made two-pane layout implementation in the AbstractListDetailFragment. This Fragment uses SlidingPaneLayout to manage a list pane (managed by your subclass), and a details pane implemented by NavHostFragment.

All Navigation components are now rewritten in Kotlin and use generics to improve the nullability of classes such as NavType subclasses.

Architecture Library Guide

If you'd like to learn more about how our core architecture libraries work together, you can watch our collection of videos and articles covering modern Android development best practices series - MAD Skills: Architecture .

2. Optimize application performance

By using performance libraries, you can build high-performance applications and make targeted optimizations to maintain their performance for a better end-user experience.

Optimize startup time

The startup time of an application has a huge impact on the user experience, especially when the application is used immediately after installation. To improve the experience on first launch, we created Baseline Profiles . Baseline Profiles allow apps and libraries to provide metadata about code path usage to the Android runtime to prioritize ahead-of-time compilation. This profile aggregates data from dependent libraries, puts it in the application's APK as a baseline.prof file, and is then used to partially precompile the application at install time and to statically link library code. This makes your app load faster and reduces dropped frames the first time the user interacts with the app.

We have started using Baseline Profiles within Google. After the Play Store app was connected to Baseline Profiles, the rendering time of the initial page of the search results page was reduced by 40% . In order to provide a better user experience for end users, some popular dependency libraries have also added Baseline Profiles, such as Fragment and Compose. If you want to create your own baseline profiles, you need to use the Macrobenchmark library.

Detect your app

The Macrobenchmark library can help developers better understand application performance by extending the coverage of Jetpack benchmarks to more complex use cases. This includes application startup and integrated UI operations (such as scrolling the RecyclerView or running animations). Macrobenchmark can also be used to generate Baseline Profiles.

Macrobenchmark has been updated to improve testing speed and also bring several new experimental features. It also now supports custom trace-based timing measurements using TraceSectionMetric, allowing developers to benchmark against specific sections of code. Additionally, AudioUnderrunMetric can now detect audio cache underruns to help developers understand audio stuttering.

BaselineProfileRule can generate profiles to help with runtime optimization. It works like other macro benchmarks, you just express user actions via lambda code. In the example below, a key user-scenario that the compiler should optimize ahead of time is a cold start: opening the app's launch Activity from the launcher.

 @ExperimentalBaselineProfilesApi
@RunWith(AndroidJUnit4::class)
class BaselineProfileGenerator {
  @get:Rule
  val baselineProfileRule = BaselineProfileRule()

  @Test
  fun startup() = baselineProfileRule.collectBaselineProfile(
    packageName = "com.example.app"
  ) {
    pressHome()

    // 这一代码块定义了应用的关键用户场景。这里我们所关注的是应用启动的优化,但您
    // 也可以进行导航和滚动浏览您最重要的界面。
    startActivityAndWait()
  }
}

For more detailed information and a complete guide to generating and using benchmark profiles with Macrobenchmark, see the Android Developer's Guide document - Benchmark Profiles .

Avoid interface lag

The new JankStats library helps you track down and analyze performance issues in your app's interface, including reporting missing rendered frames - commonly referred to as "jank". JankStats is built on top of existing Android platform APIs (such as FrameMetrics), but works with API Level 16 minimum.

JankStats also provides other capabilities beyond the platform's built-in capabilities: heuristics that help locate the cause of dropped frames, UI status that provides additional context in reports, and report callbacks that can be used to upload data for analysis.

Let's talk about the three main functions of JankStats in detail:

  1. Identifying stutters: JankStats uses built-in heuristics to determine when stutters occur, and uses this information to know when to publish stutter reports, allowing developers to obtain information about these issues to help analyze and fix them.
  2. Provide UI context : In order to improve the usability and operability of stuck reports, JankStats provides a mechanism to help track the current UI and user state. Whenever a report is logged, the corresponding information is provided, which not only helps the developer understand when the problem occurred, but also what the user was doing at the time. This helps identify problematic areas in your app that can be addressed later. Some of this state is provided automatically by some Jetpack libraries, but developers are also encouraged to provide their own application-specific state.
  3. Report results : On each frame, the JankStats client receives a notification via the listener containing information about the frame, including how long it took the frame to complete, whether it was considered stuttering, and what the UI context was during the display of the frame . Clients are encouraged to aggregate and upload data suitable for analysis to help and debug overall performance issues.

Add logs to your app

The Tracing library enables application profiling by writing trace events to a system buffer. Tracing 1.1 supports profiling of non-debug builds of applications down to API Level 14, similar to the <profileable> manifest file tag introduced in API Level 29.

3. Interface library and guide

We've made some changes to the interface library to better support large screen compatibility, foldable devices, and Emoji.

Jetpack Compose

Jetpack Compose, Android's modern tool for building native interfaces, has now been updated to 1.2 beta. The new version adds features to support advanced use cases, including support for downloadable fonts, lazy layouts, and nested scrolling interoperability. For more information, see the article: A Look at I/O | What's New in Jetpack Compose .

Understanding window states

The new WindowManager library helps developers adapt their applications to support multi-window environments and new device forms by providing a common API interface that supports API Level 14 as low as possible.

The initial release targeted the use case of foldable devices, including querying physical properties that affect how content is displayed.

Jetpack's SlidingPaneLayout component has been updated to use the WindowManager's smart layout API to avoid content being placed in occluded areas (eg spanning physical hinge areas).

drag and drop

The new DragAndDrop helps implement functionality in new form factors and window modes by letting developers receive drag and drop data from within and outside the app. DrapAndDrop includes consistent drop target functionality that supports at least API Level 24:

Porting new API to old API Level

The AppCompat library allows us to access the new API under the old platform API version, including some porting of interface features, such as dark mode.

AppCompat 1.4 integrates the Emoji2 library, bringing default support for new Emoji to API Level 14 and above, all text-based views supported in AppCompat.

Custom region selection is currently supported down to API Level 14. This feature supports manual persistence of locale settings across applications, and can support automatic persistence through the metadata tag of the Service. It can tell the library to load regions synchronously and rebuild any running Activity as needed. At API Level 33 and above, persistence is managed by the platform without additional overhead.

Other key updates

Annotation

The Annotation library exposes metadata to help tools and other developers understand the application's code. It provides some familiar annotations like @NonNull. These annotations are paired with lint checks to improve code correctness and usability.

Annotation is migrating to Kotlin, so developers using Kotlin will see more appropriate annotation targets, including @file.

Some highly requested annotations have been added with their corresponding lint checks. These include annotations about method or function overrides, as well as the @DeprecatedSinceApi annotation. The latter, as a corollary of @RequiresApi, can prevent usage above a certain API level.

Contribute to the Jetpack repository on Github

We currently have over 100 projects on GitHub!

Developers can contribute code to the following projects, all based on Github's standard process:

  • activity
  • AppCompat
  • Biometric
  • Collection
  • Compose Compiler
  • Compose Runtime
  • Core
  • DataStore
  • Fragment
  • Lifecycle
  • Navigation
  • Paging
  • Room
  • WorkManager

Check out the project homepage for more, including how we handle pull requests and how to get started building apps with Jetpack.

That's all for a brief overview of all the changes to Jetpack over the past few months. For more information on each Jetpack library, see the following:

You are welcome to click here to submit feedback to us, or to share what you like and problems you find. Your feedback is very important to us, thank you for your support!

* Java is a trademark or registered trademark of Oracle and/or its affiliates .


Android开发者
404 声望2k 粉丝

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