The New Features in Android Jetpack

Kayvan Kaseb
Software Development
10 min readAug 13, 2020
The picture is provided by Unsplash

As a matter of fact, Android Jetpack was inspired by the Support Library, which is a set of components to take advantage of advanced Android features; whereas, it maintains backwards compatibility. Google mentioned that it is currently used by 99% of every app in the Play Store. There have been carried out a number of works and improvements in Android Jetpack during recent years by Google. Additionally, these new libraries and features will make it easier to implement better apps. This essay aims to introduce some major enhancements and feature to existing libraries in Android Jetpack to expand their scopes.

Introduction and Overview

Basically, Android Jetpack is a set of libraries, tools, and guidance for modern Android development. Currently, there are four categories for using Jetpack, which includes: Architecture, UI, Behavior, and Foundation. Jetpack has seen incredible adoption and momentum. At the moment, 80% of the top 1,000 apps in the Play store are using Jetpack.

The picture is provided by Google Documents

There have been done a number of works and improvements in Android Jetpack during these years by Google. In addition, these new libraries and features will make it easier to implement better apps. So, this article will demonstrate some major additions and features to existing libraries to expand their scopes.

Hilt

Fundamentally, Hilt is Jetpack’s recommended dependency injection library. Dependency injection is a technique widely used in programming and well-suited to Android developments. However, dependencies are provided to a class instead of the class straight in itself. This helps diminish coupling in your codes. By using dependency injection, you get better code re-usability because of the coupling between components, and testing become much more easier since your class dependencies are well-defined. Furthermore, in the latest Android Developer Benchmark Survey by Google, 49% of the developers asked Google to work on a dependency injection solutions. As a result, Google has teamed up with the Dagger Team to create Hilt. Dagger’s dependency injection library developed by Google, and is widely adopted in the top rated android apps. However, getting started with Dagger on Android has some challenges for developers due to complexity of this library.

Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project.

Hilt is an opinionated dependency injection library specifically built for Android on top of Dagger. When using Hilt, you annotate your classes with the AndroidEntryPoint annotation, and Hilt will make them inject-able. So, you can be able to use the @Inject annotation to inject your dependencies. Additionally, you can use the AndroidEntryPoint annotation in other Android components.

@AndroidEntryPoint
class SampleActivity : AppCompatActivity() { ... }

Hilt currently provides the following Android classes:

  • Application (by using @HiltAndroidApp)
  • Activity
  • Fragment
  • View
  • Service
  • BroadcastReceiver

Eventually, you require to annotate your Application class with the HiltAndroidApp annotation. All apps that use Hilt must include an Application class that is annotated with @HiltAndroidApp.

@HiltAndroidApp triggers Hilt's code generation, including a base class for your app, which serves as the application-level dependency container.

@HiltAndroidApp
class SampleApplication : Application() { ... }

This generated Hilt component is attached to the Application object's lifecycle, and supports dependencies to it. Besides, it is the parent component of the app, which means that other components can be able to access the dependencies that it provides. Thus, Hilt can create the dependency graph for your Android app. The tight integration between Jetpack libraries and Hilt can help you that remodel can also be injected automatically. All you need to do is to annotate your ViewModel constructor with the ViewModelInject annotation we should ask Hilt to inject it.

If a dependency you want to provide needs more menu setup, you can create a Dagger module with the InstallIn annotation, and Hilt will discover it automatically. With InstallIn, you can specify the scope of dependencies provided by your module. Hilt comes with predefined scopes for Android, so you do not require to define your own for the common cases. Hilt not only decreases the code unit right, but also diminishes the mental load to get started. It also scales very well with your application as is already used by major Google apps like YouTube.

Some benefits of using Hilt in Android apps:

  1. Hilt supports a standard method to use Dependency Injection(DI) in your app by providing containers for every Android class in your project and managing their lifecycles automatically.

2. Hilt Contains extensions for providing classes from other Jetpack libraries. Now, Hilt supports the following Jetpack components: ViewModel and WorkManager.

3. It has an Android Studio Integration for a more delightful developer experience.

4. It has a well-defined scopes for android, and it also has out of the box testing APIs. Therefore, you can replace your dependencies per test with support for both Integration and Robolectric tests.

5. Hilt is built on top of the popular DI library Dagger to benefit from the compile-time correctness, runtime performance, and scalability that Dagger provides.

App Startup

As we know, Application startup time is a vital metric for any app. Users expect apps to be responsive and fast to load. When an application does not meet this expectation, it can be disappointing to users. Thus, this inappropriate experience may cause a user to rate your app badly on the Play store, or even abandon your app.

Most of these libraries use Content Provides to initialize automatically, including some Jetpack libraries like WorkManager and Lifecycle. The cost of creating Content Providers has been investigated by Google. They noticed each of them adds at least two milliseconds on a pixel to a device running Android 10. This is just only the cost of Content Providers not the work library does. Jetpack App Startup is a library that provides a straightforward, performant way to initialize components at application startup. So, both library developers and app developers can be able to use App Startup to streamline startup sequences and explicitly set the order of initialization.

Here is an example of an initializer component that configures WorkManager. It extends the initializer API specifying its type, and when crate is called, it simply initialize WorkManager and returns the instance.

class WorkManagerInitializer : Initializer<WorkManager> {
override fun create(context: Context): WorkManager {
val configuration = Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.build()

WorkManager.initialize(context, configuration)
return WorkManager.getInstance(context)
}

// This component does not have any dependencies
override fun dependencies() = emptyList<Class<out Initializer<*>>>()
}

Alternatively, the initializer component can also define its dependencies. So that the Startup library will initialize dependencies before initializing our component. Under the hood, the Startup library uses a single Content Provider shared between all these initializers reducing the application startup time. As a result, the App Startup library can be used by both application and developer to streamline startup. It provides lazy initialization to further improve Application Startup Performance by completing avoiding the Content Provider. In addition, it automatically adds traces points for every initializer. This way of components being initialized at application launch using tools like Systrace and Perfetto.

Android Game SDK

To make game development easier, Google launched the Android Game SDK earlier this year. This includes a set of libraries that are designed to help you enhance your game performance across various devices. It has been available on the Android website, and is considered as a part of the Jetpack family now. Also, it is available on Google’s Maven repository. The SDK currently contains two important features. The Android Frame Pacing library allows games to keep 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 your frame rate at scale across the whole Android ecosystem. You also get new performance insights in Android vitals, designed specifically for game developers, by integrating Android Performance Tuner into your game. Currently, this feature is available as Alpha on the Google Play Maven Repository.

Benchmark 1.1

The Jetpack Benchmark library allows you to quickly benchmark your Kotlin-based or Java-based code from within Android Studio. The library handles warm-up, measures your code performance and allocation counts, and outputs benchmarking results to both the Android Studio console and a JSON file with more detail. The new release for the Benchmarking library has been done by Google recently. It integrates with the CPU Profiler. Thus, 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. You can optimize the time spent for allocations and reduce a lot on garbage collection.

Paging 3

Initially, Paging is a library that helps you load and displays small amounts of data incrementally. Paging 3 completely right off the library using Kotlin Coroutines, and adds highly requested features like Separators. This is the center of the Paging where we connect at our back-end.

The Paging library helps you load and display pages of data from a larger dateset from local storage or over network. This approach allows your app to use both network bandwidth and system resources more efficiently.

We extend this PagingSource class, which is a single method that we need implemented. Here we call our API to get the result and 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, provided with the configuration of our page size, and get the flow out of it. Finally, UI layer, we collect from this flow and pass the values into our paging adapter. That adapter will take care of displaying the data for us.

class DoggosRemotePagingSource(
val backend: GoodDoggosService
) : PagingSource<Int, Dog>() {
override suspend fun load(
params: LoadParams<Int>
): LoadResult<Int, Dog> {
try {
// Load page 1 if undefined.
val nextPageNumber = params.key ?: 1
val response = backend.getDoggos(nextPageNumber)
return LoadResult.Page(
data = response.doggos,
prevKey = null, // Only paging forward.
nextKey = response.nextPageNumber + 1
)
} catch (e: Exception) {
// Handle errors in this block
return LoadResult.Error(exception)
}
}
}

Paging is rewritten from the ground up with Kotlin Coroutines and Flow. It has built-in API at headers, footers or separators. Besides, you can even do other transformations like mapping items filtering. Finally, Paging 3 is fully backwards compatible with Paging 2 to help you migrate easily. At the moment, it is available as Alpha version.

CameraX

As you know, creating real time filters was a difficult task some years ago. Basically, CameraX is a Jetpack library that makes integrating camera into your application very easy and reliable. It reached Beta last February, and Google has focused on reliability and documentation before reaching the stable version. CameraX runs on 90% of Android devices, which means there is a number of variety in terms of performance and feature. PreviewView is a widget that displays the camera preview in your application. Currently, it manages interactions with your app lifecycle via pages reliably. Besides, it optimized transparently your surface view under the hood on devices, which will benefit from its performance enhancements. This provides less buffering and better power efficiency. Google has also focused on providing more guidelines to make it easier to use CameraX. They added the sample for YUV to RGB conversion to do image analysis in more familiar formats. As a result, you can easily integrate it with libraries like in AppKit. Other samples are created including OpenGL and rotation handling.

WorkManager

In fact, WorkManager is the Jetpack library that allows you to run deferrable background jobs like sending your very important email when the user is connected to the Internet. WorkManager does not only rely on JobScheduler to execute your jobs, it also has in-process scheduler trying your workers, and Google has dramatically improved it during this year. Now, It provides delayed workers and periodic work requests. The scheduler also no longer imposes scheduling limits, which enhances the throughput of your work requests. WorkManager supports long-running or significant work that should be kept alive by the Operating System.

WorkManager is an API that makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or the device restarts.

Sometimes it would be difficult to know why a worker did not run when you expected it to run. For these cases, Google has represent the new feature called Diagnostics API that you can invoke with adb to peek into the internal state of WorkManager. When invoked, WorkManager will dump its current state into Logcat, which we can simply view via an adb Logcat command. Additionally, to identify some mistakes, Google has added lead rules to catch these mistakes by using Lint checks as some warnings. Therefore, the Android Studio can immediately inform you if that occurs in your codebase.

Navigation

As a matter of fact, the Navigation library allows you to navigate between various screens of your app with ease while also following Android UI principles.

Navigation refers to the interactions that allow users to navigate across, into, and back out from the different pieces of content within your app. Android Jetpack’s Navigation component helps you implement navigation, from simple button clicks to more complex patterns, such as app bars and the navigation drawer.

In Navigation 2.3, Google has added support for dynamic feature modules, which allows you to download pieces of your application as the user needs it. This significantly reduce the initial download size of your application. The integration with the Navigation component can provide you to navigate to these modules as if they are part of your base APK. All you need to do is to annotate your fragments with the module name. So, Navigation library will support the downloading if it is necessary before moving to that screen. In addition, a number improvements have been made to the Deep Linking feature in Navigation. Now, you can easily access query parameters, provide custom actions, and specify mime types. Finally, Returning a Result feature, In Navigation 2.3, now each screen in your application has 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 class to pass data between screens. Your fragments can access the previous fragment savedStateHandle by using the previous BackStackEntry. Once you obtain the savedStateHandle from the previous entry, you can set the result values on the SavedState. To observe the result, you can get the same value from the SavedState of the currentBackStackEntry and observe the value without LiveData. In this way, observation is considered as Lifecycle aware because we are using SavedState, it works even if your application’s restarted between these two screens.

In conclusion

In fact, Android Jetpack is a set of libraries, tools, and guidance for advanced Android development. Currently, there are four categories for using Jetpack, which includes: Architecture, UI, Behavior, and Foundation. There have been carried out a number of works and enhancements in Android Jetpack during recent years by Google. This article considered some new features and improvements in recent months in Android Jetpack based on Google documents.

--

--

Kayvan Kaseb
Software Development

Senior Android Developer, Technical Writer, Researcher, Artist, Founder of PURE SOFTWARE YAZILIM LİMİTED ŞİRKETİ https://www.linkedin.com/in/kayvan-kaseb