Most Android apps now use the support libraries to help users add all kinds of updated widgets and to address compatibility issues across Android devices and OS versions. You’d be hard-pressed to find an Android app that doesn’t use something from them, and they’re included as a dependency in template projects made in Android Studio. Widgets as fundamental as RecyclerView are included in them.
The support libraries are great to use, but they have evolved quite a bit over the years and the names have become somewhat confusing. There are com.android.support:support-v4 and com.android.support:support-v13, for example. Looking at the names alone, do you know what classes are in them? The names are supposed to designate what version of Android they support, but, as they have evolved, the minimum version has increased to API Level 14.
Google has realized that this variety of ever-changing libraries is very confusing for new (and old) developers and has decided to start over. Consequently, it has created Android Jetpack as a way of both providing guidance and also as a recommended set of libraries and tools. Through Jetpack, Google provides components that form a recommended way to architect your app. Furthermore, Google hopes that Jetpack will eliminate boilerplate code and simplify complex tasks while still providing backwards compatibility.
To help address version confusion, Google is also resetting all of the Jetpack-related libraries to version 1.0.0 and starting their package names with a base name of androidx. Moreover, each component will be in its own library, though it’s important to note that Google is still working on transitioning libraries to the new package names.
There are also a couple of other resources in Jetpack, including the Android KTX library, which makes it easier to use Kotlin with Android. And, finally, Android Studio 3.2 Canary 14+ now has a Migrate to AndroidX option to convert your existing code and libraries to androidx (but I would recommend you wait until they are out of alpha, since pretty substantial known issues exist in the Canary 14 and 15 conversions).
Jetpack is broken up into four main areas: Architecture, Foundation, Behavior and UI. Most of the items in Jetpack are a re-arrangement and categorization of existing libraries, but a few of the items are new. By the end of this article, you should have a good sense of Jetpack’s features and where to find more information on each of them.
Jetpack: Architecture
The Architecture area of Jetpack includes eight different libraries and tools that help you architect your app and manage the data used by and displayed in the app. Most of these are existing libraries. However, there are three new libraries: Navigation, Paging, and WorkManager. Beginning with the newest libraries:
Navigation
Navigating between activities and/or fragments has never been easy. Now, with the Navigation library and the navigation viewer built into Android Studio, you can visually design how your screens are connected to one another. Many people have noticed that this is similar to Storyboards in Apple’s Interface Builder for iOS app development.
Using Navigation, you visually connect one screen to another using “destinations”. You create a navigation graph that will have a starting destination that can have actions to go to other destinations. The great thing about this is that you can define animations in the visual editor. The library even handles deep linking into your app. Passing data between destinations can be done in a safe way with a new plugin called safeargs. You can define what arguments the Fragments in the navigation graph accept from within the navigation file itself.
Here is a screenshot of two fragments with an action between the two. You can set up your app to navigate to the second fragment from inside a button click listener in the first fragment.
You can find more information about Navigation here: Navigation.
Paging
Have you ever had to deal with large amounts of related data? Maybe too much for you to download at once? The Paging library will help by providing ways to handle the paging of data in a RecyclerView.
The Paging library uses several key classes: PagedList, PagedListAdapter, and DataSource. PagedList is a list that loads data lazily from a DataSource, allowing the app to load data in chunks or pages. PagedListAdapter is a custom RecyclerView.Adapter that handles pages with a DiffUtil callback.
For the DataSource, you will use one of three different subclasses: PageKeyedDataSource, ItemKeyedDataSource, or PositionalDataSource.
You can find more information here: Paging.
WorkManager
Over the years, there have been several systems built into Android for handling background jobs or alarms. They differ on different versions of Android and you have to write a lot of code to handle the different versions of the OS.
WorkManager solves this problem and gives you one library for creating deferrable, asynchronous tasks and defining when they should run. You can define one-time jobs or repeating jobs.
You can find more information here: WorkManager.
Data Binding
This library has been around for awhile. Data Binding lets you bind your data to your layout in XML, so that, when you change your data in running code, the views defined by the layout are automatically updated. Moreover, when your UI changes, your data objects are updated.
You can find more information here: Data Binding.
Lifecycle
The Lifecycle library helps you listen for lifecycle events in other components besides an activities and fragments. This allows you to have lifecycle-aware logic in places other than just an Activity or Fragment. The library works by using annotations on methods so you get notified for the events that you are interested in.
You implement LifecycleObserver, annotate methods and add this observer to a lifecycle owner, which is usually an Activity or Fragment. The LifecycleObserver class can get the current lifecycle state by calling lifecycle.getCurrentState()
and can use this information to avoid calling code when not in the correct state.
A LifecycleOwner is an object that has Android lifecycle events. The support library Activity and Fragment classes already implement the LifecycleOwner methods. A LifecycleOwner has a Lifecycle object that it can return to let the observer know what the current state is.
You can find more information here: Lifecycles.
LiveData
The LiveData library uses the Observer pattern for data but handles it in a lifecycle-aware manner. You get the benefits of automatic UI updates when data changes without calling UI elements when the UI is not in the correct state.
LiveData is the class that implements the observer pattern, holds that data, and notifies listeners when that data has changed.
You can find more information here: LiveData.
Room
If you have ever struggled working with the SQLite database in an Android app, you will appreciate what the Room library does for you. You create several simple classes that define your data and how to access them, and the Room library will do most of the rest. The only SQL code you have to write is for queries, which are usually pretty straightforward. And you gain compile-time checks of your SQL code when using Room.
There are three important classes you need to use with Room: Database (this contains your main entry point and holds a reference to the database object for the app), Entity (you create one for each table in the database), and DAO (this contains the methods for retrieving and managing the data).
You can find more information here: Room.
ViewModel
While the Room library persists your data in permanent storage, the ViewModel class allows you to hold onto data in device memory in a lifecycle-aware manner. One of the nice features of a ViewModel is that it can survive the re-construction of an Activity or Fragment over a configuration change such as a device rotation. The system will hold onto that ViewModel re-associate it with the Activity or Fragment. ViewModels are also where you can load data in the background and use LiveData to notify listeners that the data is ready.
You can find more information here: ViewModel.
Jetpack: Foundation
The Foundation area of Jetpack involves core system components, Kotlin extensions and Testing Libraries. This includes the AppCompat library, which you’ve probably been using for awhile, and the new Kotlin KTX extension library for easier development in Kotlin.
Testing is very important and has it’s own section to with frameworks to let you test your app, for both UI testing or unit testing.
Android app codebases are getting bigger and bigger, so you’ll want to visit the Multidex section of Foundation to see how to handle the 64K method limit.
You can find more information about what’s available in Foundation here: Foundation.
AppCompat
The AppCompat library in Jetpack Foundation consists of all of the components from the old v7 libraries. This includes:
- AppCompat
- Cardview
- GridLayout
- MediaRouter
- Palette
- RecyclerView
- Renderscript
- Preferences
- Leanback
- Vector Drawable
- Design
- Custom tabs
- And even a few others…
You can find more information here: AppCompat.
Android KTX
Android KTX is the only new library in Foundation and is a set of Kotlin extensions designed to streamline the development of Android apps when using Kotlin.
There are several KTX modules that are linked to other libraries in Jetpack. For instance, if you are working with the Navigation library, then you could use:
- android.arch.navigation:navigation-common-ktx
- android.arch.navigation:navigation-fragment-ktx
- android.arch.navigation:navigation-runtime-ktx
- and android.arch.navigation:navigation-ui-ktx
SharedPreferences is an example of how using KTX can make your code simpler. Take a look at the Kotlin code below:
sharedPreferences.edit()
.putBoolean("key", value)
.apply()
Compare that with the KTX-based code:
sharedPreferences.edit {
putBoolean("key", value)
}
The KTX code is streamlined a bit and removed the need to add apply()
.
And here’s a SQLite example without KTX:
db.beginTransaction()
try {
// insert data
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
And the corresponding KTX version:
db.transaction {
// insert data
}
KTX streamlines a SQLite transaction into a simple function call with a trailing lambda.
You can find more information here: Android KTX.
Test
The Test part of Foundation includes the Espresso UI testing framework and AndroidJUnitRunner for unit testing. Unit tests are for writing small tests on the logic within your code, usually at the level of individual methods. They should run fast and help you test a specific piece of logic. Espresso is used for the testing of UI elements.
You can find more information here: Testing.
Multidex
As you build out your app and include more and more libraries, your app can grow large enough that you need to use the Multidexing capabilities of Android. Once your app includes more than 65,536 methods across all classes, you will need to have the system split your .dex file (basically, a .zip file of classes) into multiple .dex files.
You can learn more about multidexing and how to use it here: Multidex.
Jetpack: Behavior
The Behavior area of Jetpack features libraries that help you interact with your user through the UI, including using video or sound. It includes many components such as media, notifications, permissions, downloading, sharing and the new Slices library.
You can find more information here: Behavior.
Notifications
Android Notifications have been around since the beginning but have changed over time. They have become more expressive and can contain buttons and images. Since Android 5.0 Lollipop, a notification called a heads-up notification can be displayed. You can even use notifications on Android Wear and TV for controlling media.
You can find more information here: Notifications.
Permissions
This part of the Behavior area showcases how to use and request permissions. Since Android 6.0 Marshmallow, permissions are now required to be requested and given before certain elements of a device’s components can be accessed, such as contacts, location and camera information. You declare permissions in the manifest, and you must deal with both cases of a user accepting or denying your permission request.
You can find more information here: Permissions.
Sharing
The Sharing part of Behavior explains how to share content and the ShareActionProvider class and how to use it. You will can share information with other apps and receive information from other apps. You can create a share action, share files and use ContentProviders for sharing data.
You can find more information here: Sharing.
Media
The Behavior area of Jetpack includes the MediaPlayer and AudioManager classes. You can play media and sounds, use the MediaPlayer in a service, and control the device volume. Android supports various media formats. You can also use the ExoPlayer library, which Google uses for it’s own media players in apps such as YouTube.
You can find more information here: Media.
Download Manager
The DownloadManager service helps you download files in the background. Avoid dealing with connection problems, retrying and even system reboots by using the DownloadManager service. Since the DownloadManager is a system service, you can just start a download and listen for a broadcast event to handle the finished download. No need to worry about network issues or crashes.
You can find more information here: Download Manager.
Slices
The Slices library is new and lets you create UI templates to share your data through the system in rich, flexible layouts. One of the examples Google gave at Google I/O was a weather app that can show more data depending on the space it has to show. Currently, it is only used by the Google Search App but should extend to the Google Assistant.
You can make your app data available to these apps using Slices so that a user can find information from your app by using Google Search or the Assistant.
You can find more information here: Slices
Jetpack: UI
Most of the UI libraries in Jetpack are based on existing code. They include: animations, fragments, palettes, layouts, Emojis, Android Auto, Wear and TV. The EmojiCompat library is the newest of the libraries and gives you up-to-date emojis and the fonts needed to use them.
You can find more information about the UI area here: UI.
Animation
This part of Jetpack includes APIs for the different types of animations available on Android. The Jetpack site documentation covers the old as well as new ways to use animations. Vector graphics and vector animations are included as well.
There is also a physics-based animation system that includes spring and fling animations. You can setup transitions between activities as well as property and object animations. You can also set a layout to animate any updates you make to the layout.
You can find more information here: Animations.
Emoji
EmojiCompat handles emoji characters and uses downloadable font support. This allows your app to stay up to date with the latest emojis without depending on the Android OS. Whenever you update this library dependency, you will have the latest emojis. There is a concrete Span class called EmojiSpan that is used to create emojis in your text.
You can find more information here: Emoji.
Fragment
The Fragment support class has moved into this part of Jetpack. It includes the different kinds of fragments, such as: DialogFragment, ListFragment, and PreferenceFragmentCompat. An important part of a Fragment is the lifecycle, and the Fragment class included in Jetpack is well-integrated with the Lifecycle class in Jetpack: Architecture.
You can find more information here: Fragments.
Layout
A Layout defines the Views and ViewGroups in your app. In the Jetpack Layout documentation, you learn how to declare layouts in XML and in code. It also describes some of the more common layouts, such as LinearLayout, RelativeLayout and the newer ConstraintLayout. Moreover, you’ll pick up tips on more specific features like creating lists of items with RecyclerView, as well as the card layout CardView.
You can find more information here: Layouts.
Palette
The Palette library allows you to pick colors for themes and from images to make your UI’s match your images. You can also create a palette and choose different colors using the Palette.Builder class. Some of the types of colors produced are: Light Vibrant, Vibrant, Dark Vibrant, Light Muted, Muted and Dark Muted.
You can find more information here: Palettes.
TV
If you are building your app for Android TV, then the TV part of Jetpack is for you. You can control TV Hardware and controllers and create a navigation system that works for TVs. There is the leanback theme that is used for TV layouts and the Leanback library helps with TV controls. You can setup a D-pad controller to let users navigate the TV UI.
You can find more information here: TV.
Wear
Wear OS is the version of Android for wearable devices. You can create an app that plays media, controls your media from a watch, or create a standalone watch app or watch face.
You can find more information here: Wear.
Auto
Jetpack helps you develop apps for Android Auto — audible only, messaging, working with hardware and more. You can provide audio playback for the car as well as messaging. You can test Auto apps on the car screen using the Desktop Head Unit (DHU), which is a testing tool that allows you to test without the hardware.
You can find more information here: Auto.
Where to Go From Here?
As you can see, there is quite a lot included in Google’s new Android Jetpack package. All of the libraries you know and love can be found there, as well as several new ones.
In this article, you were introduced to the four main parts of Jetpack: Architecture, Foundation, UI and Behavior. Some of the new libraries, like the Navigation library, will change the way you write your apps, making it easier than ever. WorkManager solves a long standing problem of reliably running jobs at different times on different OS versions. Paging will help with larger data sets and let you use RecyclerViews and adapters with less code. The Android KTX library makes working in Kotlin even easier and will continue to evolve. Slices are new and, as you learn more, you should be able to make available more of your data outside of your app. With the Emoji library, you can have all of the latest and best emojis available.
Hopefully this post provided a good overview of what is available in Jetpack and will get you excited about using something new. The main Jetpack page is located here: Android Jetpack
If you would like more in-depth information on Jetpack Navigation, you can find a screencast here. We also have screencasts on LiveData, ViewModel, and Paging Library. Finally, you can find a short introduction to WorkManager in our Background Processing course here.
Let us know what part of Android Jetpack you are most looking forward to using in the discussion forum below!
The post Introduction to Android Jetpack appeared first on Ray Wenderlich.