Android
Jetpack, with new
features in 2021
02 	New in Stable
01	 Overview
04 Debut in Alpha
05 	Additional Talks
03 	Up to Beta
Workshop Host
Jetpack,


with new features in 2021
Wonyoung Choi - AVP, Mobile Developer, OCBC

@TORU_0239
android


jetpack
Of top 1K apps


using two or more non-core Jetpack
Libraries
How increased?
97%
2021
47%
2020
Pre-release cycles and what they mean for developers
Versioning
Alpha, Beta
• Active development


• API may be added,
changed, removed


• Tested and highly-
functional
• Feature Stabilization


• No API changes


• APIs changed only in
response to critical
issues or community
feedback
Alpha Beta
Metadata that helps tools and other developers
understand your code
Experimental Annotations
Metadata
androix:annotation:annotation-experimental
builder.setAutoCloseTimeout(2000, SECONDS)


@ExperimentalRoomApi


Or


@OptIn(ExperimentalRoomApi::class)
The Opt-in usage should be marked with
either one from the right.


[UnsafeOptInUsageError]
androix:annotation:annotation-experimental
@OptIn(ExperimentalRoomApi::class)


builder.setAutoCloseTimeout(2000, SECONDS)
02 	New in Stable
01	 Overview
03 	Up to Beta
04 Debut in Alpha
05 	Additional Talks
Unified API surface for accessing camera functionality
across the various OS versions and devices
CameraX
Hardware
• Adjusting exposure compensation

• Access to the information about


camera state and features

• Interoperability via Camera2Interop
CameraX
The latest improvements to the
common requests
androidx.camera:camera
CameraX
• HDR (High Dynamic Range) preview*

• Zoom ratio controls

• Do-Not-Disturb
Supports for the latest device and


OS features
* Supported for Pixel 4A and 5 only, but soon on more devices
androidx.camera:camera
CameraX
• Faster image capture

• Faster initialization*
Performace enhancement for
better experience
* Up to 25% on legacy devices, according to Google
androidx.camera:camera
// Set up the CameraController


val cameraController = LifecycleCameraController(context)


cameraController.bindToLifecycle(lifecycleOwner)


// Attach the CameraController to PreviewView


val previewView = findViewById(R.id.previewView)


previewView.setController(cameraController)


// Use the CameraController


cameraController.takePicture(...)
Simplified dependency injection solution


built on top of Dagger2, for Jetpack
Architecture
Hilt
• ViewModel support into the core Hilt

• SavedStateHandle added as a default

• Integrated with Navigation and
Compose
Hilt
Reached Stable stage with changes
androidx.hilt:hilt
@HiltViewModel


class MyViewModel @Inject constructor(


val handle: SavedStateHandle,


val repository: Repository


) : ViewModel {


// ...


}
@HiltViewModel


class MyViewModel @Inject constructor(


val handle: SavedStateHandle,


val repository: Repository


) : ViewModel {


// ...


}


@AndroidEntryPoint


class MyFragment : Fragment() {


val viewModel: MyViewModel by viewModels()


val navigationGraphScoped: MyViewModel by


hiltNavGraphViewModels(R.id.nav_graph)


}
@HiltWorker


class MyWorker @AssistInject constructor(


@Assisted context: Context,


@Assisted params: WorkerParameters,


repo: Repository


) : Worker {


// ...


}
@HiltAndroidTest


@UninstallModules(RepositoryModule::class)


@RunWith(AndroidJUnit4::class)


class Test {


@Module


@InstallIn(ApplicationComponent::class)


object FakeRepositoryModule {


@Provides


fun provideRepo() = FakeRepository()


}


}
@Module


@TestInstallIn(


components = SingletonComponent::class,


replaces = RepositoryModule::class


)


object FakeRepositoryModule {


@Provides


fun provideRepo() = FakeRepository()


}
The recommended data persistence layer, providing increased usability and safety
over the platform
Architecture
Room
Experimental support for Kotlin Symbol Processing

Built-in support for enums and RxJava3

Introduction to QueryCallback

New annotation @ProviderTypeConverter
Room
2.3.0 Stable version
androidx.room:room
Support for Auto-Migrations
2.4.0 Alpha version
@ProvidedTypeConverter


class TimeStampConverter(timeformat: String) {


@TypeConverter


fun fromTimestamp(value: Long) {


// implementation


}


}


Room.inMemoryDatabaseBuilder(context, CacheDatabase::class)


.addTypeConverter(TimeStampConverter(getPreferredTimeStamp()))


.build()
Support for Auto-Migrations
Room
2.4.0 Alpha version
androidx.room:room
@Database(


- version = 1,


+ version = 2,


entities = { Penang.class },


+ autoMigrations = {


+ @AutoMigration (from = 1, to = 2)


+ }


)


public abstract class DoggosDatabase extends RoomDatabase { }
Load and display small chunks of data to improve


network and system resource consumption
UI
Paging Library
Complete rewrite in Kotlin, supported for Kotlin coroutines and Flow

Asynchronous loading with RxJava and Guava primitives

Improvements to the repository and presentation layers


Supports for headers, footers, separators, and loading state
Paging Library
androidx.paging:paging
Paging Library
androidx.paging:paging
RxPagingSource for RxJava Flow for stream
Paging Library
androidx.paging:paging
ListenableFuturePagingSource for ListenableFuture
Safely and easily encrypt files


and SharedPreferences
Data
Security Crypto
val prefs: SharedPreferences = EncryptedSharedPreferences.create(


context,


"preference_file_name",


mainKey,


prefKeyEncryptionScheme = AES256_SIV,


prefValueEncryptionScheme = AES256_GCM,


)


// Use the resulting SharedPreferences object as usual.


prefs.edit()


.putBoolean("launch_completed", true)


.apply()
Can it be combined with
Room or DataStore?
Encrypted DataStore will be provided, Room can already be used with SQLCipher, not decided
yet if it’ll be included out of the box.
Answer
Schedule deferrable, asynchronous


tasks that must be run reliably
Architecture
WorkManager
WorkManager
androidx:work.work
Support in version 2.5 and later for apps that use multiple processes

Version 2.7 handles Android S foreground restrictions

Newly introduced Workmanager Inspector
androidx:work.work
WorkManager Inspector
Available in Android Studio Arctic Fox
Flexible, intuitive system for positioning


and animating user interfaces
UI
ConstraintLayout
• Reached 2.0.0 stable

• MotionLayout to provide rich
animation and state management
ConstraintLayout
ConstraintLayout 2.0.0 stable
androidx:constraintlayout:constraintlayout
MotionLayout
What’s new in design tools
androidx:constraintlayout:constraintlayout
Abstraction for segmenting an user interface 

into reusable components
UI
Fragment
Clean up the internal implementation 

Reduce undocumented behaviour and Increase stability
Fragment
Androidx:fragment:fragment
• Don’t forget to read the release note before updating to fragment:1.3.0
ActivityResult Integration
// 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)


onAttachFragment() has been deprecated.
onAttachFragment()
02 	New in Stable
01	 Overview
03 	Up to Beta
04 Debut in Alpha
05 	Additional Talks
Data storage solution that allows you to store key-value pairs


or typed object with protocol buffers
Data
DataStore
Fully asynchronous with Kotlin
coroutine / Flow support, RxJava
2&3
DataStore
Key-values pairs

Protocol buffers (strongly typed)

Your own plugin (Kotlin serialization)
Replacement for SharedPreference Multiple backing implementations
androidx.datastore:datastore
SharedPreferences DataStore
Asynchronous API
Synchronous API
Safe to call on UI thread
Call signal errors
Safe from runtime exceptions
Transactional API with strong


consistency guarantees
Handles data migration
Type safety
O only for change listener O via coroutine, RxJava
O O via runBlocking
X O
X O
X O
X O
X O
X O
// At the top level of your kotlin file:


val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
Create a preferences Datastore
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")


val exampleCounterFlow: Flow<Int> = context.dataStore.data


.map { preferences ->


// No type safety.


preferences[EXAMPLE_COUNTER] ?: 0


}
Read from a Preferences Datastore
suspend fun incrementCounter() {


context.dataStore.edit { settings ->


val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0


settings[EXAMPLE_COUNTER] = currentCounterValue + 1


}


}
Write to a Preferences DataStore
val Context.prefStore: DataStore<Prefrences> by preferencesDataStore(


name = USER_PREFERENCES_NAME,


produceMigrations = { context ->


// Since we're migrating from SharedPreferences, add


// a migration based on the SharedPrefernces name


listOf(SharedPreferencesMigration(context, USER_PREFERENCES_NAME))


}
Migrate to DataStore
02 	New in Stable
01	 Overview
03 	Up to Beta
04 Debut in Alpha
05 	Additional Talks
High performance full-text search for


app-local and device-wide use cases
Data
AppSearch
Prefix Indexing


Relevance ranking

Usage scoring
AppSearch
Fuzzy matching

Query expansion

Language support
Full featured vs. SQL Advanced full-text search
androix:appsearch:appsearch
Includes schemas for common object types




Centralised storage on Android S and later for


integrating into device-wide search
androix:appsearch:appsearch
AppSearch
Framework for navigating between destinations


within an app, now with multiple backstack
UI
Navigation
• Added in Navigation 2.4.0

• Utilising APIs which has been added to Fragment 1.4.0 internally.
Navigation
Multiple backstack
androidx.navigation:navigation
saveBackStack() restoreBackStack()
and
<action


android:id=”@+id/swap_stack”


app:destination=”@id/second_stack”


app:restoreState=”true”


app:popUpTo=”@id/first_stack_start_destination”


app:popUpToSaveState=”true” />
// Use the navigate() method that takes a navOptions DSL Builder


navController.navigate(selectedBottomNavRoute) {


launchSingleTop = true


restoreState = true


popUpTo(navController.graph.startDestinationId) {


saveState = true


}


}
Dynamic shortcuts for Google Assistant


and other Google services
UI
Google Shortcuts
androidx:core:core-google-shortcuts
// 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)
All the emoji, everywhere! 😉🎉
UI
EmojiCompat
EmojiCompat
androidx:emoji2:emoji2-views*
Modern emoji on API 19+ to new artifact emoji2:emoji2


Automatic configuration based on the AppStartup library
* Included in AppCompat 1.4.0 and later by default
Accurately measure apps startup and integrated


behaviours, both locally and in CI
Performance
Macrobenchmark
Macrobenchmark
androidx.benchmark.macro:macro
Viewable performance profiling result in Android Studio


Check for regressions in CI before they hit users
@get:Rule


val benchmarkRule = MacrobenchmarkRule()


@Test


fun startup() = benchmarkRule.measureRepeated(


packageName = "mypackage.myapp",


metrics = listOf(StartupTimingMetric()),


iterations = 5,


startupMode = StartupMode.COLD


) { // this = MacrobenchmarkScope


pressHome()


val intent = Intent()


intent.setPackage("mypackage.myapp")


intent.setAction("mypackage.myapp.myaction")


startActivityAndWait(intent)


}
Metrics are displayed directly in Android Studio
02 	New in Stable
01	 Overview
03 	Up to Beta
04 Debut in Alpha
05 	Additional Talks
Compose


Integrations
Compose Integrations
Jetpack Compose Jetpack Libraries in Compose
New UI toolkit without XML • Hilt

• Paging

• Navigation
• Activity

• ViewModel

• ConstraintLayout
Compose Integrations
Jetpack Compose Jetpack Libraries in Compose
Form


factors
Form factors
What’s new in Foldables, Tablets, and Large Screens
Now is the Time: What’s New With Wear OS by Googlee
• androidx.window


• androidx.slidingpanelayout
• androidx.wear
Much More

Things…
Compose

Hilt

Security Keystore

Security Crypto

EmojiCompat

Google Shortcuts

Core

Room

AppSearch
Paging

Macrobenchmark

DataStore

Window

SlidingPaneLayout

Navigation

Fragment

Activity

Lifecycle
CameraX

ConstraintLayout

ConstraintLayout Compose

SplashScreen

Wear

Wear Tiles

Wear Phone Interaction

Wear Remote Interaction

Wear Input
Thank you!
developers.android.com/jetpack

androidx.dev
Resources
Wonyoung Choi - AVP, OCBC bank

@TORU_0239

Jetpack, with new features in 2021 GDG Georgetown IO Extended