What's new in Android Jetpack

Hi, my name is Yigit Boyar and I'm a Technical Lead on Android.

Today, we'll talk about what is new in Jetpack.

Android Jetpack is a suite of libraries to help developers write high-quality apps more easily.

These libraries help youfollow best practices, free you from writing boilerplate code and accommodate your application across operating system versions, so that you can focus on the code you care about.

Since its launch, Jetpack has seena high amount of adoption across many of the topAndroid applications.

47% of the top 1, 000 apps use two or more Jetpack libraries and that number doesn't even include core libraries like AppCompat or Lifecycle.

We are excited about the growth we have seen and the incredible feedback we've received from the community.

Thank you.

We have done a lot of workover the past year.

We have new libraries launching today that will make it easier to write better apps and we have also made major additions to existing libraries to expand their scope.

There's a lot to coverso let's get started.

First up, Hilt.

Hilt is Jetpack's recommended dependency injection library.

Dependency injection is a techniquewidely used in programming and well-suited to Android developments.

But dependencies are provided to a class instead of the class straight in itself.

This helps reduce coupling in your code base.

By using dependency injection, you get better code reusability due to the coupling between components, and testing becomes easier since your class dependenciesare well-defined.

Moreover, in the latest Android Developer Benchmark Survey, 49% of the workers asked us to workon a dependency injection solution.

So we have teamed up with the Dagger Team to create Hilt.

Dagger's a dependency injection library developed by Google, and is widely adopted in the top Android apps.

However, getting startedwith Dagger on Android, has a steep learning curve.

Hence, we have created Hilt.

Hilt is an opinionateddependency injection library specifically built for Androidon top of Dagger.

While using Hilt, you annotate your fragments with the AndroidEntryPoint annotationand Hilt will make them injectable.

And now, you can usethe Inject annotation to inject your dependencies.

You can also use the AndroidEntryPoint annotation in other Android componentslike activities or services.

Finally, you need to annotateyour Application class with the HiltAndroidApp annotation so that Hilt can create the dependency graph for your application.

Thanks to the tight integration between Jetpack libraries and Hilt, your remodels can also be injected automatically.

All you need to do is to annotateyour ViewModel constructor with the ViewModelInject annotation we should ask Hilt to inject it.

Because Hilt is designed for Android, it knows what the ViewModel is, its scope, etc.

So it does the right things by default.

If a dependency you want to provide needs more menu setup, you can create a Dagger modulewith the installing annotation and Hilt will discover it automatically.

With InstallIn, you can specifythe scope of dependencies provided by your module.

Hilt comes with predefinedscopes for Android, so you don't need to define your ownfor the common cases.

We have seen great results fromintegrating Hilt into our applications.

We have replaced Dagger with Hilt in the Google I/O application and we were able to delete 75% of the dependency injection code.

I know it sounds too good to be true, but it is true, go check it out.

Hilt not only reduces the code unit right but also reduces the mental load to get started.

It also scales very wellwith your application as is already used by major Google Apps like YouTube.

To recap, Hilt is the new recommendedJetpack dependency injection library.

It's built on top of already proven Dagger, it has integrations with ViewModels, Fragments and WorkManager, it has well defined scopes for Android, and my favorite part, it also has out of the box testing APIs so you can replace your dependencies per test with supportfor both integration and robolectric tests.

Last but not least, it has Android Studio Integration for a more delightful developer experience.

It's available as Alpha today and we have even created a Cheat Sheetfor you to quickly get started.

Check it out and let us knowwhat you think.

Next, another new library, App Startup.

Performance is important for us, that's why today we are alsolaunching the Alpha of our AndroidX startup library.

As you add more labels to your application that wants to run some initialization code on App Startup, it has a negative impact on your launch performance.

Most of these librariesuse Content Providers to initialize automatically, including some Jetpack libraries like WorkManager and Lifecycle.

We have analyzed the cost of creating Content Providers and each of them adds at least two milliseconds on a pixel to a device running Android 10.

This is just the cost of Content Providersnot the work library does.

The App Startup library provides a straightforward and performant way to initialize componentsat application startup by avoiding a separate Content Provider for each library.

Here is an example of an initializer component that configures WorkManager.

It extends the initializer APIspecifying its type, and when create is called, it simply initializes WorkManagerand returns the instance.

Alternatively, the initializer componentcan also define its dependencies so that the startup library will initialize dependencies before initializing our component.

Under the hood, the startup libraryuses a single content provider shared between all these initializers reducing the application startup time.

So the App Startup library can be used by Both Application and Library Developers to streamline startup.

It supports lazy initialization to further improve Application Startup performance by completely avoidingthe Content Provider.

It automatically adds Trace points for every initializer.

This way you know the true costof components being initialized at application launch using toolslike Systrace and Perfetto.

It's available as offered today, try it out and see how your applaunch performance improves.

Moving on to the Android Game SDK.

To make game development easier, we have launched the AndroidGame SDK earlier this year.

It includes a set of libraries that are designed to help you improve your game performance across devices.

It has been available on the Android website and now is part of the Jetpack family, and also available on Google's Maven repository.

The SDK currently containstwo important modules.

The frame pacing API allows gamesto maintain a steady frame rate and can lower a game's input latency.

The library detects the expected frame rate and auto adjusts frame presentation times accordingly.

Android Performance Tuner enables you to measure and optimize frame rate at scale.

By integrating it with your game, you get near performance inside Android vitals designed specifically for game developers.

It's available as Alpha on the Google Play Maven Repository.

As you can see, performance is important for us, and we are not just focusing on game performance, but we are also investing in toolsfor application developers.

Today we have a new Alpha release for the Benchmarking library.

It integrates with the CPU profiler so that you can profile your benchmarks, and then weave the method, or sample trace it right in Android studio.

We have also added support for memory allocation tracking so that you can optimize the time spent for allocations and reduce a lot on garbage collection.

Next, Paging 3.

Paging is a library that helps you load and display small chunksof data incrementally.

Today, we are shipping Paging 3, completely right off the libraryusing Kotlin Coroutines and adds highly requestedfeatures like separators.

Here is how it looks.

This is the heart of the Paging, where we connect at our back end.

We extend this PagingSource class which is a single method that we need implemented.

Here we call our API to get the resultand return the page.

If something goes wrong, we return an error result to notify Paging that an expected error has happened.

Once you have the PagingSource, you can create a Pager, provide with the configuration of our page size, and get the flow out of it.

Finally, in the UI layer, we collect from this flow and pass the values into our paging adapter.

The adapter will take care of displaying the data for us.

To recap, Paging is rewrittenfrom the ground up with Kotlin Coroutines & Flow.

It has built-in API so at headers, footers or separators.

You can even do other transformationslike mapping items or filtering them.

It adds new APIs, to observe the Loading State and has metas to Retry or Refresh.

Last but not least, Paging 3 is fully backwards compatible with Paging 2 to help you migrate easily.

It is available as Alpha now, please check it out and let us know what you think.

We're really excited about our first Kotlin Coroutines library.

Let's move into a librarythat I wish existed when I was working on apps, CameraX.

Creating real time filters 6, 7 years ago, was not fun at all.

CameraX is a Jetpack library that makes integrating camera into your application very easy and reliable.

It reached Beta last February, and we are focusing on reliabilityand better documentation before reaching the stable version.

CameraX runs on 90% of Android devices, which means, there is a lot of variety in terms of performance and feature set.

To make sure CameraX works well, our Test Lab runs our automated test suiteon both low end and high end devices that cover over 400 millionactive devices in use.

This means you can spend more time on your application rather than accounting for different devices in your codebase.

PreviewView is a widget that displaysthe camera preview in your application.

It now handles interactions with your application lifecycle and via pages reliably.

It's also optimized so transparently your surface view under the hood on devices that will benefit from its performance enhancements.

This provides less buffering and better power efficiency.

We are also focused on providing more guidance to make it easier to use CameraX.

We added the sample for YUV to RGB conversion to do image analysis in a more familiar format so that you can easily integrate itwith libraries like in AppKit.

We have created althoughother samples as well, including OpenGL and rotation handling.

So take a look atdeveloper.

android.

com for more details.

Next, WorkManager.

WorkManager is the Jetpack library that allows you to run deferrable background jobs like sending your very important email when the user is connectedto the Internet.

Here are some highlights from the 2.

3 and 2.

4 releases.

WorkManager doesn't only rely on JobScheduler to execute your jobs, it also has an in-process schedulertrying your workers and we have greatly improved it this year.

It now supports delayed workersand periodic work requests.

The scheduler also no longerimposes scheduling limits, which improves the throughputof your work requests.

WorkManager now supports long-running or important work that should be kept alive by the operating system.

Here's an example of a worker that uses the Coroutines API provided by WorkManager.

When the worker starts, we can call the setForeground method with a notification to display to the user.

Finally, we do the actual workand return as usual.

WorkManager will take care of thisusing the service for us.

Because we are usinga foreground service, this worker can run longer than the usual 10 minute limit.

Keep in mind though, this API requires itto show a notification to the user so use it sparingly.

Let's look at another improvementto WorkManager, Diagnostics.

Sometimes it's hard to knowwhy a worker didn't run when you expected it to run.

For those cases, we have the new Diagnostics APIthat you can invoke with ADB to peek into the internal stateof WorkManager.

When invoked, WorkManager will dumpits current state into logcat, which we can simply view via an adb logcat command.

As WorkManager is adopted by applications, we identify some common mistakes.

We have added lead roles to catch these so the Studiocan immediately inform you if that happens in your codebase.

Here's an example where we madethe worker class private by mistake.

If you do this, Studio will quickly warn you that the worker needs to be public.

I mean, I know you don't write bugs, but this is for the other peoplewatching the video.

That was all with WorkManager, let's talk about Navigation.

The Navigation library allows you to navigate between different screens of your application with ease while also following Android UI principles.

In Navigation 2.

3, we have added support for dynamic feature modules, which allows you to downloadpieces of your application as the user needs it.

This can significantly reduce the initial download sizeof your application.

Thanks to the integration with the Navigation component, you can navigate to these modulesas if they're part of your base APK.

All you need to do is to annotate your fragments with the module name.

Navigation library will take careof downloading it if necessary before moving to that screen.

In addition, we have madelots of improvements to the Deep Linking feature in Navigation.

You can now access query parameters, provide custom actions and specify mime types.

I remember writing Deep Linking support manually where you had to carry over information on multiple screens to go to the right place.

That was no fun.

With Navigation, it is just one parameter in the graph and always taken care of for me.

I love it.

And last but not least, my favoritenew feature, Returning a Result.

Let's take a look at it.

In Navigation 2.

3, now each screen in your applicationhas a NavBackStackEntry which gives you access to the same state of that entry as well.

To ensure your results are kept over configuration changes or process that Navigation uses the savedStateHandle classto pass data between screens.

Your fragments can access the previous fragment savedStateHandle by using the previous BackStackEntry.

Once you obtain the savedStateHandlefrom the previous entry, you can set the result valueson the SavedState.

To observe the result, you can get the same value from the SavedStateof the currentBackStackEntry and observe the value without live data.

This way, observation is Lifecycle aware.

And because we are using SavedState, it works even if your application's restarted between these two screens.

So that was the new Result API in Navigation.

It's actually part of a bigger old hull of the APIs related to passing databetween screens and applications.

We know there have been many changes recently in terms of permissions on Androidand we wanted to make it easier.

This new API which we callActivityResultContracts, makes asking for permissions super easy as well as many other common taskslike taking a picture.

Let's take a look at an example of how you can ask for permissions using the new Contracts API.

First, we register for an activity result and specify that you want to use the requestPermission contract.

We also need to provide a callback that will be called with the resultof the permission request.

Later, when we want to ask for the permission, all we need to do is to launch the function that was returned from registerForActivityResult with the parameters.

When it's result, it will call the callback we are provided.

If you want to obtain multiple permissions at once, there is also a request multiple permissions contract that you can use.

There are more contracts availablelike asking user take a picture, query contents from a URIor Open Documents.

Check out the Activity ResultsContracts API for more.

On to our most popularlibrary, AppCompat.

AppCompat provides backportsfor a wide variety of UI elements and platform features from the material theme Dark Mode.

Because some of the functionalityfrom the framework is duplicated into AppCompat, it might be difficult to figure outwhich attribute you should use.

To help you make most of the library, we have added a set of library-specific Lint Rules.

For example, here is a layout I've used the drawable start attribute to set a drawable on the textview.

If you open this code in Studio, it will immediately show you a warning and ask you to replace it with the more full-featured version of the same attribute available in AppCompat.

We have also made substantial improvements to AppCompat's implementation of the Dark Theme.

And to make sure you can still customize your theme, we have added a configurationoverrides API.

For instance, if you wanted to specifya custom locale for your activity, you can override the attachBaseContext method and create a new configuration which you can configure as you please.

Afterwards, you should create a new context as a combination of the existing contextplus the custom configuration.

Finally, you should delegateto the super method so that the new contextis used across activity.

Speaking of Dark Theme, Jetpack's Webkit library has a new API in 1.

2.

0 release to forced dark mode for its contents.

When enabled, the WebView will render size and Dark Theme are supported or forcibly in more certain colors if the website doesn't support Dark Mode.

Wow! We have covered a lot in this video.

These are just some of the highlightsthat we think you should know about.

But that's not even everything, where there is more in our What's new in Android Jetpack blog post.

You will find lists of documentation, samples and other features that we weren't able to cover today.

We are excited to hear more from you and what you think on these new APIs.

Try them out and take advantageof the best of Jetpack.

Thank you.

.

Hãy bình luận đầu tiên

Để lại một phản hồi

Thư điện tử của bạn sẽ không được hiện thị công khai.


*