### Collect Baseline Profile with Setup Block (Deprecated)
Source: https://developer.android.com/jetpack/androidx/releases/benchmark
This example demonstrates how to collect a baseline profile using the `setupBlock` parameter, which has been deprecated in favor of `profileBlock`.
```kotlin
baselineRule.collectBaselineProfile(
packageName = PACKAGE_NAME,
setupBlock = {
startActivityAndWait()
},
profileBlock = {
// ...
}
)
```
--------------------------------
### Collect Baseline Profile without Setup Block
Source: https://developer.android.com/jetpack/androidx/releases/benchmark
This example shows the current recommended way to collect a baseline profile using `collectBaselineProfile`, where the setup logic is integrated directly into the `profileBlock`.
```kotlin
baselineRule.collectBaselineProfile(
packageName = PACKAGE_NAME,
profileBlock = {
startActivityAndWait()
// ...
}
)
```
--------------------------------
### Install RetainedValuesStore (Previous API)
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime
Demonstrates the previous method for installing a custom RetainedValuesStore using CompositionLocalProvider and DisposableEffect.
```kotlin
val retainedValuesStore = retainControlledRetainedValuesStore()
if (active) {
CompositionLocalProvider(LocalRetainedValuesStore provides retainedValuesStore) {
content()
}
val composer = currentComposer
DisposableEffect(retainedValuesStore) {
val cancellationHandle =
if (retainedValuesStore.retainExitedValuesRequestsFromSelf > 0) {
composer.scheduleFrameEndCallback {
retainedValuesStore.stopRetainingExitedValues()
}
} else {
null
}
onDispose {
cancellationHandle?.cancel()
retainedValuesStore.startRetainingExitedValues()
}
}
}
```
--------------------------------
### Install RetainedValuesStore (New API)
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime
Shows the updated approach for installing a RetainedValuesStore using LocalRetainedValuesStoreProvider, simplifying the process.
```kotlin
val retainedValuesStore = retainManagedRetainedValuesStore()
if (active) {
LocalRetainedValuesStoreProvider(retainedValuesStore) {
content()
}
}
```
--------------------------------
### Start Up WebView with Context
Source: https://developer.android.com/jetpack/androidx/releases/webkit
Add context as a parameter to the startUpWebView() API.
```java
startUpWebView(context);
```
--------------------------------
### Using State Property Delegate Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
This example demonstrates the usage of the `by state { ... }` property delegate operator for State. Ensure the necessary imports are added.
```kotlin
val state by state { initialValue }
```
--------------------------------
### RxJava2 Observable to State Adapter Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
An adapter for RxJava2 Observables that subscribes and returns State. This example shows how to use `subscribeAsState()`.
```kotlin
val value by observable.subscribeAsState()
```
--------------------------------
### Collect Baseline Profile with Setup Block
Source: https://developer.android.com/jetpack/androidx/releases/benchmark?hl=ru
Use this method to collect a baseline profile for your application. The setupBlock is executed before the profileBlock.
```kotlin
baselineRule.collectBaselineProfile(
packageName = PACKAGE_NAME,
setupBlock = {
startActivityAndWait()
},
profileBlock = {
// ...
}
)
```
--------------------------------
### Example Method Signature
Source: https://developer.android.com/jetpack/androidx/releases/compose-animation
Shows the signature format for a method, including its name and return type, used in profile rules.
```plaintext
isPlaced()Z
```
--------------------------------
### LiveData to State Adapter Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
An adapter for LiveData that observes its values as State. This example demonstrates the usage of `observeAsState()`.
```kotlin
val value by liveData.observeAsState()
```
--------------------------------
### Using MutableStateOf Property Delegate Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
This example shows how to use the `by mutableStateOf(...)` property delegate operator for MutableState. Ensure the necessary imports are added.
```kotlin
val mutableState by mutableStateOf(initialValue)
```
--------------------------------
### Example Class Descriptor
Source: https://developer.android.com/jetpack/androidx/releases/compose-animation
Illustrates the descriptor format for a Java class in the context of profile rules.
```plaintext
Landroidx/compose/runtime/SlotTable;
```
--------------------------------
### Flow to State Adapter Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
An adapter for Flow that collects its values as State. This example shows how to use the `collectAsState()` extension function.
```kotlin
val value by flow.collectAsState()
```
--------------------------------
### Get WindowLayoutInfo from UI Context (Experimental)
Source: https://developer.android.com/jetpack/androidx/releases/window
Exposes an experimental version of getting WindowLayoutInfo from a UI context. Use with caution as APIs may change.
```java
WindowLayoutInfo windowLayoutInfo = WindowInfoTracker.getOrCreate(context).getWindowLayoutInfo(uiContext).getValue();
```
--------------------------------
### Collect Baseline Profile without Setup Block
Source: https://developer.android.com/jetpack/androidx/releases/benchmark?hl=ru
Use this method to collect a baseline profile for your application when no specific setup is required before profiling.
```kotlin
baselineRule.collectBaselineProfile(
packageName = PACKAGE_NAME,
profileBlock = {
startActivityAndWait()
// ...
}
)
```
--------------------------------
### Declare Media3 Dependencies (Groovy)
Source: https://developer.android.com/jetpack/androidx/releases/media3
Add Media3 artifacts to your app's build.gradle file. Ensure the Google Maven repository is configured. This example shows dependencies for ExoPlayer, DASH, HLS, SmoothStreaming, RTSP, MIDI, IMA, Cronet, OkHttp, RTMP, Compose UI, Material 3 UI, Views UI, Leanback UI, session management, extractors, inspectors, Cast integration, WorkManager, transformers, effects, Lottie effects, muxers, test utilities, and common components.
```Groovy
dependencies {
def media3_version = "1.10.0"
// For media playback using ExoPlayer
implementation "androidx.media3:media3-exoplayer:$media3_version"
// For DASH playback support with ExoPlayer
implementation "androidx.media3:media3-exoplayer-dash:$media3_version"
// For HLS playback support with ExoPlayer
implementation "androidx.media3:media3-exoplayer-hls:$media3_version"
// For SmoothStreaming playback support with ExoPlayer
implementation "androidx.media3:media3-exoplayer-smoothstreaming:$media3_version"
// For RTSP playback support with ExoPlayer
implementation "androidx.media3:media3-exoplayer-rtsp:$media3_version"
// For MIDI playback support with ExoPlayer (see additional dependency requirements in
// https://github.com/androidx/media/blob/release/libraries/decoder_midi/README.md)
implementation "androidx.media3:media3-exoplayer-midi:$media3_version"
// For ad insertion using the Interactive Media Ads SDK with ExoPlayer
implementation "androidx.media3:media3-exoplayer-ima:$media3_version"
// For loading data using the Cronet network stack
implementation "androidx.media3:media3-datasource-cronet:$media3_version"
// For loading data using the OkHttp network stack
implementation "androidx.media3:media3-datasource-okhttp:$media3_version"
// For loading data using librtmp
implementation "androidx.media3:media3-datasource-rtmp:$media3_version"
// For building media playback UIs using Jetpack Compose
implementation "androidx.media3:media3-ui-compose:$media3_version"
// For building media playback UIs using Jetpack Compose with Material Design 3
implementation "androidx.media3:media3-ui-compose-material3:$media3_version"
// For building media playback UIs using Views
implementation "androidx.media3:media3-ui:$media3_version"
// For building media playback UIs for Android TV using the Jetpack Leanback library
implementation "androidx.media3:media3-ui-leanback:$media3_version"
// For exposing and controlling media sessions
implementation "androidx.media3:media3-session:$media3_version"
// For extracting data from media containers
implementation "androidx.media3:media3-extractor:$media3_version"
// For inspecting media files
implementation "androidx.media3:media3-inspector:$media3_version"
// For extracting and processing video frames
implementation "androidx.media3:media3-inspector-frame:$media3_version"
// For integrating with Cast
implementation "androidx.media3:media3-cast:$media3_version"
// For scheduling background operations using Jetpack Work's WorkManager with ExoPlayer
implementation "androidx.media3:media3-exoplayer-workmanager:$media3_version"
// For transforming media files
implementation "androidx.media3:media3-transformer:$media3_version"
// For applying effects on video frames
implementation "androidx.media3:media3-effect:$media3_version"
// For applying Lottie effects on video frames
implementation "androidx.media3:media3-effect-lottie:$media3_version"
// For muxing media files
implementation "androidx.media3:media3-muxer:$media3_version"
// Utilities for testing media components (including ExoPlayer components)
implementation "androidx.media3:media3-test-utils:$media3_version"
// Utilities for testing media components (including ExoPlayer components) via Robolectric
implementation "androidx.media3:media3-test-utils-robolectric:$media3_version"
// Common functionality for reading and writing media containers
implementation "androidx.media3:media3-container:$media3_version"
// Common functionality for media database components
implementation "androidx.media3:media3-database:$media3_version"
// Common functionality for media decoders
implementation "androidx.media3:media3-decoder:$media3_version"
// Common functionality for loading data
implementation "androidx.media3:media3-datasource:$media3_version"
// Common functionality used across multiple media libraries
implementation "androidx.media3:media3-common:$media3_version"
// Common Kotlin-specific functionality
implementation "androidx.media3:media3-common-ktx:$media3_version"
}
```
--------------------------------
### Paging Dependencies (Pre-AndroidX)
Source: https://developer.android.com/jetpack/androidx/releases/paging?hl=es-419
Include these dependencies for Paging versions prior to AndroidX. This example shows runtime, testing, and RxJava2 support dependencies.
```gradle
dependencies {
def paging_version = "1.0.0"
implementation "android.arch.paging:runtime:$paging_version"
// alternatively - without Android dependencies for testing
testImplementation "android.arch.paging:common:$paging_version"
// optional - RxJava support
implementation "android.arch.paging:rxjava2:$paging_version"
}
```
--------------------------------
### Declare Appcompat Dependencies (Groovy)
Source: https://developer.android.com/jetpack/androidx/releases/appcompat
Add the Google Maven repository to your project and declare Appcompat dependencies in your app's build.gradle file. This example uses Groovy syntax.
```groovy
dependencies {
def appcompat_version = "1.7.1"
implementation "androidx.appcompat:appcompat:$appcompat_version"
// For loading and tinting drawables on older versions of the platform
implementation "androidx.appcompat:appcompat-resources:$appcompat_version"
}
```
--------------------------------
### Declare Media3 Dependencies (Kotlin)
Source: https://developer.android.com/jetpack/androidx/releases/media3
Add Media3 artifacts to your app's build.gradle file using Kotlin syntax. Ensure the Google Maven repository is configured. This example shows dependencies for ExoPlayer and ExoPlayer DASH and HLS playback support.
```Kotlin
dependencies {
val media3_version = "1.10.0"
// For media playback using ExoPlayer
implementation("androidx.media3:media3-exoplayer:$media3_version")
// For DASH playback support with ExoPlayer
implementation("androidx.media3:media3-exoplayer-dash:$media3_version")
// For HLS playback support with ExoPlayer
```
--------------------------------
### Use WorkManager.getInstance(Context)
Source: https://developer.android.com/jetpack/androidx/releases/work?hl=fa
Starting with WorkManager 2.1.0-alpha01, it is recommended to use `WorkManager.getInstance(Context)` instead of `WorkManager.getInstance()` for on-demand initialization and general safety.
```java
WorkManager workManager = WorkManager.getInstance(context);
```
--------------------------------
### Query WorkInfo by States
Source: https://developer.android.com/jetpack/androidx/releases/work?hl=ru
Example of how to query WorkInfo objects based on their states using WorkQuery.Builder.fromStates().
```java
WorkQuery.Builder.fromStates(...)
```
--------------------------------
### Declare Appcompat Dependencies (Kotlin)
Source: https://developer.android.com/jetpack/androidx/releases/appcompat
Add the Google Maven repository to your project and declare Appcompat dependencies in your app's build.gradle file. This example uses Kotlin syntax.
```kotlin
dependencies {
val appcompat_version = "1.7.1"
implementation("androidx.appcompat:appcompat:$appcompat_version")
// For loading and tinting drawables on older versions of the platform
implementation("androidx.appcompat:appcompat-resources:$appcompat_version")
}
```
--------------------------------
### Declare Preference Library Dependencies (Kotlin)
Source: https://developer.android.com/jetpack/androidx/releases/preference?hl=es-419
Add the Google Maven repository and the Preference library artifact to your app's build.gradle file. This example uses Kotlin syntax.
```kotlin
dependencies {
val preference_version = "1.2.1"
// Java language implementation
implementation("androidx.preference:preference:$preference_version")
// Kotlin
implementation("androidx.preference:preference-ktx:$preference_version")
}
```
--------------------------------
### Enable Profile Installation in gradle.properties
Source: https://developer.android.com/jetpack/androidx/releases/profileinstaller
This property must be set in your gradle.properties file to enable the utilization of baseline-prof.txt files. Requires Android Gradle Plugin 7.0+.
```properties
android.enableProfileInstaller=true
```
--------------------------------
### Local Composable Function Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-foundation
Demonstrates a local composable function that captures parent parameters. Note that local composable functions are no longer skippable.
```kotlin
@Composable fun Counter(count: Int, onCountChange: (Int) -> Unit) {
@Composable fun ShowCount() { Text("Count: $count") }
ShowCount()
Button(onClick={ onCountChange(count + 1) }) {
Text("Increment")
}
}
```
--------------------------------
### Declare Preference Library Dependencies (Groovy)
Source: https://developer.android.com/jetpack/androidx/releases/preference?hl=es-419
Add the Google Maven repository and the Preference library artifact to your app's build.gradle file. This example uses Groovy syntax.
```groovy
dependencies {
def preference_version = "1.2.1"
// Java language implementation
implementation "androidx.preference:preference:$preference_version"
// Kotlin
implementation "androidx.preference:preference-ktx:$preference_version"
}
```
--------------------------------
### Implement onInit() and onRelease() in FakeRenderer
Source: https://developer.android.com/jetpack/androidx/releases/media3
Implements the onInit() and onRelease() methods in FakeRenderer for test utilities.
```java
FakeRenderer.onInit()
```
```java
FakeRenderer.onRelease()
```
--------------------------------
### Detect Drag Gestures with onStart Callback
Source: https://developer.android.com/jetpack/androidx/releases/compose-ui?hl=fa
The `detectDragGestures` function now includes an `onStart` callback for handling the initiation of drag gestures. This is useful for scenarios requiring immediate feedback or setup upon drag start.
```kotlin
detectDragGestures(onStart = { press -> /* ... */ }, onDrag = { change, dragAmount -> /* ... */ }, onDragEnd = { /* ... */ }, onDragCancel = { /* ... */ })
```
--------------------------------
### On-Demand Initialization Setup
Source: https://developer.android.com/jetpack/androidx/releases/work?hl=fa
To enable on-demand initialization for WorkManager (introduced in 2.1.0-alpha01), disable the automatic initializer, implement `Configuration.Provider` on your `Application` object, and use `WorkManager.getInstance(Context)`.
```java
public class MyApplication extends Application implements Configuration.Provider {
@Override
public Configuration getWorkManagerConfiguration() {
// Use default configuration or customize it
return new Configuration.Builder()
.setMinimumLoggingLevel(android.util.Log.INFO)
.build();
}
}
```
--------------------------------
### Disable Profile Installation in AndroidManifest.xml
Source: https://developer.android.com/jetpack/androidx/releases/profileinstaller
To disable profile installation, remove the ProfileInstallerInitializer from the manifest. This is useful if you need to manually trigger profile installation using the ProfileInstaller.writeProfile API.
```xml
```
--------------------------------
### Report Start Time of Ad Break with HlsInterstitialsAdsLoader Listener
Source: https://developer.android.com/jetpack/androidx/releases/media3?hl=zh-cn
Adds `HlsInterstitialsAdsLoader.Listener.onAdStarted` to report the start time of an ad break.
```java
HlsInterstitialsAdsLoader.Listener.onAdStarted
```
--------------------------------
### 配置 Media3 Gradle 依赖项
Source: https://developer.android.com/jetpack/androidx/releases/media3?hl=zh-cn
在 build.gradle 文件中添加 Media3 库的依赖项,支持 Groovy 和 Kotlin DSL 两种格式。
```groovy
dependencies {
def media3_version = "1.10.0"
// For media playback using ExoPlayer
implementation "androidx.media3:media3-exoplayer:$media3_version"
// For DASH playback support with ExoPlayer
implementation "androidx.media3:media3-exoplayer-dash:$media3_version"
// For HLS playback support with ExoPlayer
implementation "androidx.media3:media3-exoplayer-hls:$media3_version"
// For SmoothStreaming playback support with ExoPlayer
implementation "androidx.media3:media3-exoplayer-smoothstreaming:$media3_version"
// For RTSP playback support with ExoPlayer
implementation "androidx.media3:media3-exoplayer-rtsp:$media3_version"
// For MIDI playback support with ExoPlayer (see additional dependency requirements in
// https://github.com/androidx/media/blob/release/libraries/decoder_midi/README.md)
implementation "androidx.media3:media3-exoplayer-midi:$media3_version"
// For ad insertion using the Interactive Media Ads SDK with ExoPlayer
implementation "androidx.media3:media3-exoplayer-ima:$media3_version"
// For loading data using the Cronet network stack
implementation "androidx.media3:media3-datasource-cronet:$media3_version"
// For loading data using the OkHttp network stack
implementation "androidx.media3:media3-datasource-okhttp:$media3_version"
// For loading data using librtmp
implementation "androidx.media3:media3-datasource-rtmp:$media3_version"
// For building media playback UIs using Jetpack Compose
implementation "androidx.media3:media3-ui-compose:$media3_version"
// For building media playback UIs using Jetpack Compose with Material Design 3
implementation "androidx.media3:media3-ui-compose-material3:$media3_version"
// For building media playback UIs using Views
implementation "androidx.media3:media3-ui:$media3_version"
// For building media playback UIs for Android TV using the Jetpack Leanback library
implementation "androidx.media3:media3-ui-leanback:$media3_version"
// For exposing and controlling media sessions
implementation "androidx.media3:media3-session:$media3_version"
// For extracting data from media containers
implementation "androidx.media3:media3-extractor:$media3_version"
// For inspecting media files
implementation "androidx.media3:media3-inspector:$media3_version"
// For extracting and processing video frames
implementation "androidx.media3:media3-inspector-frame:$media3_version"
// For integrating with Cast
implementation "androidx.media3:media3-cast:$media3_version"
// For scheduling background operations using Jetpack Work's WorkManager with ExoPlayer
implementation "androidx.media3:media3-exoplayer-workmanager:$media3_version"
// For transforming media files
implementation "androidx.media3:media3-transformer:$media3_version"
// For applying effects on video frames
implementation "androidx.media3:media3-effect:$media3_version"
// For applying Lottie effects on video frames
implementation "androidx.media3:media3-effect-lottie:$media3_version"
// For muxing media files
implementation "androidx.media3:media3-muxer:$media3_version"
// Utilities for testing media components (including ExoPlayer components)
implementation "androidx.media3:media3-test-utils:$media3_version"
// Utilities for testing media components (including ExoPlayer components) via Robolectric
implementation "androidx.media3:media3-test-utils-robolectric:$media3_version"
// Common functionality for reading and writing media containers
implementation "androidx.media3:media3-container:$media3_version"
// Common functionality for media database components
implementation "androidx.media3:media3-database:$media3_version"
// Common functionality for media decoders
implementation "androidx.media3:media3-decoder:$media3_version"
// Common functionality for loading data
implementation "androidx.media3:media3-datasource:$media3_version"
// Common functionality used across multiple media libraries
implementation "androidx.media3:media3-common:$media3_version"
// Common Kotlin-specific functionality
implementation "androidx.media3:media3-common-ktx:$media3_version"
}
```
```kotlin
dependencies {
val media3_version = "1.10.0"
// For media playback using ExoPlayer
implementation("androidx.media3:media3-exoplayer:$media3_version")
// For DASH playback support with ExoPlayer
implementation("androidx.media3:media3-exoplayer-dash:$media3_version")
// For HLS playback support with ExoPlayer
implementation("androidx.media3:media3-exoplayer-hls:$media3_version")
// For SmoothStreaming playback support with ExoPlayer
```
--------------------------------
### Initialize Extensions Library
Source: https://developer.android.com/jetpack/androidx/releases/camera
Shows the required initialization process for the extensions library using a FutureCallback.
```kotlin
val availability = ExtensionsManager.init()
Futures.addCallback(
availability,
object : FutureCallback {
override fun onSuccess(availability: ExtensionsManager.ExtensionsAvailability?) {
// Ready to make extensions calls
}
override fun onFailure(throwable: Throwable) {
// Extensions could not be initialized
}
},
Executors.newSingleThreadExecutor()
)
```
--------------------------------
### Enable Camera Extensions
Source: https://developer.android.com/jetpack/androidx/releases/camera
Demonstrates how to check for extension availability and enable it using a CameraSelector before binding the use case.
```kotlin
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
val builder = ImageCapture.Builder()
val bokehImageCaptureExtender = BokehImageCaptureExtender.create(builder)
if (bokehImageCaptureExtender.isExtensionAvailable(cameraSelector)) {
bokehImageCaptureExtender.enableExtension(cameraSelector)
}
val imageCapture = builder.build()
mCameraProvider?.bindToLifecycle(this, cameraSelector, imageCapture)
```
--------------------------------
### Compose Animation 1.0.0-beta07 NoSuchMethodError Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-animation
An example of a NoSuchMethodError that may occur if libraries dependent on Compose are not recompiled with version 1.0.0-beta07.
```java
java.lang.NoSuchMethodError: No interface method startReplaceableGroup(ILjava/lang/String;)V in class Landroidx/compose/runtime/Composer; or its super classes
```
--------------------------------
### Initialize RuleController with XML rules
Source: https://developer.android.com/jetpack/androidx/releases/window?hl=bn
To set rules from an XML file, use RuleController.getInstance(context).parseRules(R.xml.static_rules) and then ruleController.setRules(rules).
```kotlin
val ruleController = RuleController.getInstance(context)
val rules = ruleController.parseRules(R.xml.static_rules)
ruleController.setRules(rules)
```
--------------------------------
### Room Prepackaged DB Open Callback
Source: https://developer.android.com/jetpack/androidx/releases/room
Added an `onOpenPrepackagedDatabase` callback for when a prepackaged DB is copied.
```java
b/148934423
```
--------------------------------
### Create Perfetto Trace Sink and Driver
Source: https://developer.android.com/jetpack/androidx/releases/tracing
Demonstrates how to create a TraceSink for Perfetto traces and a TraceDriver to enable tracing. Ensure the output directory exists.
```kotlin
/**
* A [TraceSink] defines how traces are serialized.
*
* [androidx.tracing.wire.TraceSink] uses the `Perfetto` trace packet format.
*/
fun createSink(): TraceSink {
val outputDirectory = File(/* pathname = */ "/tmp/perfetto")
// We are using the factory function defined in androidx.tracing.wire
return TraceSink(
sequenceId = 1,
directory = outputDirectory
)
}
/**
* Creates a new instance of [androidx.tracing.TraceDriver].
*/
fun createTraceDriver(): TraceDriver {
// We are using a factory function from androidx.tracing.wire here.
// `isEnabled` controls whether tracing is enabled for the application.
val driver = TraceDriver(sink = createSink(), isEnabled = true)
return driver
}
fun main() {
val driver = createTraceDriver()
driver.use {
driver.tracer.trace(category = CATEGORY_MAIN, name = "basic") {
Thread.sleep(100L)
}
}
}
```
--------------------------------
### Add onOpenPrepackagedDatabase Callback
Source: https://developer.android.com/jetpack/androidx/releases/room
A new `onOpenPrepackagedDatabase` callback has been added for when a prepackaged database is copied.
```java
I1ba74
```
--------------------------------
### Build NavOptions with NavOptions.Builder
Source: https://developer.android.com/jetpack/androidx/releases/navigation?hl=fa
Use the NavOptions.Builder to programmatically set launch options and back stack state management.
```java
NavOptions navOptions = new NavOptions.Builder()
.setLaunchSingleTop(true)
.setRestoreState(true)
.setPopUpTo(NavGraph.findStartDestination(navController.getGraph()).getId(),
```
--------------------------------
### Subcompose Into Moved Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
The `Compose.subcomposeInto` function has moved to `androidx.ui.core.subcomposeInto`.
```kotlin
Compose.subcomposeInto(container, parent, composable)
```
--------------------------------
### Run tests with ManualFrameClock and TestUiDispatcher
Source: https://developer.android.com/jetpack/androidx/releases/compose-foundation?hl=ru
Use `runWithManualClock` for tests requiring a `ManualFrameClock` and `TestUiDispatcher.Main` for easy access to the main UI dispatcher. This example demonstrates advancing the clock and checking for awaiters.
```kotlin
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.runWithManualClock
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.withContext
import org.junit.Test
@Test
fun myTest() = runWithManualClock {
// set some compose content
withContext(TestUiDispatcher.Main) {
clock.advanceClock(1000L)
}
if (clock.hasAwaiters) {
println("The clock has awaiters")
} else {
println("The clock has no more awaiters")
}
}
```
--------------------------------
### Declare privacysandbox-tools Dependencies (Kotlin)
Source: https://developer.android.com/jetpack/androidx/releases/privacysandbox-tools
Add the Google Maven repository to your project and include the necessary privacysandbox-tools artifacts in your app's build.gradle file. This example uses Kotlin syntax.
```kotlin
dependencies {
// Use to implement privacysandbox libraries
implementation("androidx.privacysandbox.tools:tools:1.0.0-alpha14")
implementation("androidx.privacysandbox.tools:tools-apicompiler:1.0.0-alpha14")
implementation("androidx.privacysandbox.tools:tools-apigenerator:1.0.0-alpha14")
implementation("androidx.privacysandbox.tools:tools-core:1.0.0-alpha14")
implementation("androidx.privacysandbox.tools:tools-testing:1.0.0-alpha14")
implementation("androidx.privacysandbox.tools:tools-apipackager:1.0.0-alpha14")
}
```
--------------------------------
### Define a @Model class
Source: https://developer.android.com/jetpack/androidx/releases/compose-material
Example of a class using the deprecated @Model annotation.
```kotlin
@Model class Position(
var x: Int,
var y: Int
)
@Composable fun Example() {
var p = remember { Position(0, 0) }
PositionChanger(
position=p,
onXChange={ p.x = it }
onYChange={ p.y = it }
)
}
```
--------------------------------
### Configure ProcessLifecycleOwner Initialization with AndroidX Startup
Source: https://developer.android.com/jetpack/androidx/releases/lifecycle
Use this configuration in your AndroidManifest.xml to initialize ProcessLifecycleOwner using androidx.startup. This is an alternative to the previous ContentProvider method. Ensure to merge or remove the provider as needed.
```xml
```
```xml
```
--------------------------------
### Initialize SplitController with Context
Source: https://developer.android.com/jetpack/androidx/releases/window
The `SplitController.getInstance()` method now requires a `Context` argument for initialization.
```kotlin
SplitController.getInstance(Context)
```
--------------------------------
### ComponentNode Emit Mode Renamed Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
The `emitMode` method on `ComponentNode` has been renamed to `move`.
```kotlin
componentNode.emitMode(from, to)
```
--------------------------------
### Configure WorkManager Initialization with androidx.startup
Source: https://developer.android.com/jetpack/androidx/releases/work
Use these XML configurations in your AndroidManifest.xml to manage WorkManager initialization when using androidx.startup.
```xml
```
```xml
```
--------------------------------
### ComponentNode Emit Remove At Renamed Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
The `emitRemoveAt` method on `ComponentNode` has been renamed to `removeAt`.
```kotlin
componentNode.emitRemoveAt(index)
```
--------------------------------
### Declare Privacy Sandbox Activity Dependencies (Kotlin)
Source: https://developer.android.com/jetpack/androidx/releases/privacysandbox-activity
Add the Google Maven repository to your project and include the necessary artifacts for the Privacy Sandbox Activity library in your app's build.gradle file. This example uses Kotlin syntax.
```kotlin
dependencies {
// Use to implement privacysandbox activitys
// TODO: Confirm these dependencies
implementation("androidx.privacysandbox.activity:activity:1.0.0-alpha03")
// Use to implement privacysandbox activity complications
// TODO: Confirm these dependencies
implementation "androidx.privacysandbox.activity:activity-complications-data-source:1.0.0-alpha03"
// (Kotlin-specific extensions)
// TODO: Confirm these dependencies
implementation "androidx.privacysandbox.activity:activity-complications-data-source-ktx:1.0.0-alpha03"
// Use to implement a activity style and complication editor
// TODO: Confirm these dependencies
implementation("androidx.privacysandbox.activity:activity-editor:1.0.0-alpha03")
// Can use to render complications.
// TODO: Confirm these dependencies
// This library is optional and activitys may have custom implementation for rendering
// complications.
// TODO: Confirm these dependencies
implementation "androidx.privacysandbox.activity:activity-complications-rendering:1.0.0-alpha03"
}
```
--------------------------------
### ComponentNode Emit Insert At Renamed Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
The `emitInsertAt` method on `ComponentNode` has been renamed to `insertAt`.
```kotlin
componentNode.emitInsertAt(index, instance)
```
--------------------------------
### Query WorkInfo by Tags
Source: https://developer.android.com/jetpack/androidx/releases/work?hl=ru
Example of how to query WorkInfo objects based on their tags using WorkQuery.Builder.fromTags().
```java
WorkQuery.Builder.fromTags(...)
```
--------------------------------
### Replace ShadowMediaCodecConfig.forAllSupportedMimeTypes()
Source: https://developer.android.com/jetpack/androidx/releases/media3?hl=zh-cn
The deprecated `ShadowMediaCodecConfig.forAllSupportedMimeTypes()` method has been removed. Use `ShadowMediaCodecConfig.withAllDefaultSupportedCodecs()` instead.
```java
ShadowMediaCodecConfig.withAllDefaultSupportedCodecs()
```
--------------------------------
### Initialize MeteringPointFactory
Source: https://developer.android.com/jetpack/androidx/releases/camera?hl=fa
Create factories to translate coordinates for focus and metering based on view types or display orientation.
```java
MeteringPointFactory factory = new TextureViewMeteringPointFactory(textureView); MeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(context, lensFacing, viewWidth, viewHeight);
```
--------------------------------
### Create Room Database from Pre-packaged Stream
Source: https://developer.android.com/jetpack/androidx/releases/room
Room provides APIs for creating a database using a pre-packaged database read from an input stream, which is useful for cases like gzipped databases.
```java
3e6792
```
--------------------------------
### Execute Focus and Metering
Source: https://developer.android.com/jetpack/androidx/releases/camera?hl=fa
Start or cancel focus and metering operations using the CameraControl API.
```java
getCameraControl(lensFacing).startFocusAndMetering(action); getCameraControl(lensFacing).cancelFocusAndMetering();
```
--------------------------------
### Get Clipped Bounds in Tests
Source: https://developer.android.com/jetpack/androidx/releases/compose-foundation?hl=bn
A test method has been added to retrieve the clipped bounds of elements.
```kotlin
get clipped bounds
```
--------------------------------
### Compose Into Deprecated Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
The `Compose.composeInto` function is deprecated. Use `setContent` or `setViewContent` instead for composing UI.
```kotlin
Compose.composeInto(container, parent, composable)
```
--------------------------------
### Testing Utilities for Media3
Source: https://developer.android.com/jetpack/androidx/releases/media3?hl=zh-cn
Include these dependencies for utilities to test media components, including ExoPlayer components, with or without Robolectric.
```gradle
// Utilities for testing media components (including ExoPlayer components)
implementation("androidx.media3:media3-test-utils:$media3_version")
```
```gradle
// Utilities for testing media components (including ExoPlayer components) via Robolectric
implementation("androidx.media3:media3-test-utils-robolectric:$media3_version")
```
--------------------------------
### Get Throwable from Operation
Source: https://developer.android.com/jetpack/androidx/releases/work
Renamed from getException() to getThrowable() for clarity. Use this to retrieve any exception associated with an Operation.
```java
Operation.getThrowable()
```
--------------------------------
### Data Source Implementations for Media3
Source: https://developer.android.com/jetpack/androidx/releases/media3?hl=zh-cn
Include these dependencies to enable data loading using different network stacks like Cronet, OkHttp, or RTMP.
```gradle
// For loading data using the Cronet network stack
implementation("androidx.media3:media3-datasource-cronet:$media3_version")
```
```gradle
// For loading data using the OkHttp network stack
implementation("androidx.media3:media3-datasource-okhttp:$media3_version")
```
```gradle
// For loading data using librtmp
implementation("androidx.media3:media3-datasource-rtmp:$media3_version")
```
--------------------------------
### Set Navigation Client for WebView
Source: https://developer.android.com/jetpack/androidx/releases/webkit
Get detailed navigation information by calling WebViewCompat.setNavigationClient with an implementation of the WebNaviagationClient interface.
```java
WebViewCompat.setNavigationClient(webView, navigationClient);
```
--------------------------------
### Implement CameraXConfig.Provider
Source: https://developer.android.com/jetpack/androidx/releases/camera
Applications must implement this interface to provide the default Camera2 configuration during initialization.
```kotlin
import androidx.camera.camera2.Camera2Config
import androidx.camera.core.CameraXConfig
public class MyCameraXApplication : Application(), CameraXConfig.Provider {
override fun getCameraXConfig(): CameraXConfig {
return Camera2Config.defaultConfig(this)
}
}
```
--------------------------------
### Dispose Composition Deprecated Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
The `Compose.disposeComposition` function is deprecated. Use the `dispose` method on the `Composition` object returned by `setContent`.
```kotlin
Compose.disposeComposition(composition)
```
--------------------------------
### Construct a Navigation Graph with NavHost
Source: https://developer.android.com/jetpack/androidx/releases/navigation?hl=fa
Use NavHost to define navigation destinations using composable and dialog functions within a Scaffold.
```kotlin
val navController = rememberNavController()
Scaffold { innerPadding ->
NavHost(navController, "home", Modifier.padding(innerPadding)) {
composable("home") {
// This content fills the area provided to the NavHost
HomeScreen()
}
dialog("detail_dialog") {
// This content will be automatically added to a Dialog() composable
// and appear above the HomeScreen or other composable destinations
DetailDialogContent()
}
}
}
```
--------------------------------
### Configure WorkManager Initialization in AndroidManifest
Source: https://developer.android.com/jetpack/androidx/releases/work
Use these XML configurations to manage WorkManager initialization via androidx.startup when migrating from previous ContentProvider methods.
```xml
```
```xml
```
--------------------------------
### Drop events based on Lifecycle state
Source: https://developer.android.com/jetpack/androidx/releases/lifecycle
Use dropUnlessResumed to prevent click events from executing after a navigation transition has started.
```kotlin
onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) }
```
--------------------------------
### Initialize ProcessCameraProvider
Source: https://developer.android.com/jetpack/androidx/releases/camera
Obtain a per-process instance of the camera provider asynchronously within an activity.
```kotlin
import androidx.camera.lifecycle.ProcessCameraProvider
import com.google.common.util.concurrent.ListenableFuture
class MainActivity : AppCompatActivity() {
private lateinit var cameraProviderFuture : ListenableFuture
override fun onCreate(savedInstanceState: Bundle?) {
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
}
```
--------------------------------
### Initialize DataStore with AeadSerializer
Source: https://developer.android.com/jetpack/androidx/releases/datastore
Use the created AeadSerializer when initializing your DataStore instance. Ensure the scope is correctly provided.
```kotlin
val dataStore = dataStore(
fileName = "settings.json",
serializer = aeadSerializer,
scope = scope,
)
```
--------------------------------
### Get Current Split Ratio
Source: https://developer.android.com/jetpack/androidx/releases/window
Retrieve the current split ratio if the SplitType is RatioSplitType. This value is only meaningful for ratio-based splits.
```kotlin
if (SplitInfo.splitAttributes.splitType is SplitAttributes.SplitType.RatioSplitType) {
val ratio = splitInfo.splitAttributes.splitType.ratio
} else {
// Ratio is meaningless for other types.
}
```
--------------------------------
### Build Preview Use Case
Source: https://developer.android.com/jetpack/androidx/releases/camera
Configure the Preview use case directly using its builder.
```kotlin
preview = Preview.Builder().setTargetAspectRatio(AspectRatio.RATIO_16_9).build()
```
--------------------------------
### Extract Camera2 Camera ID
Source: https://developer.android.com/jetpack/androidx/releases/camera
Use Camera2CameraInfo.extractCameraId to get the camera ID from CameraInfo. Requires the ExperimentalCamera2Interop marker class.
```java
Camera camera = provider.bindToLifecycle(...);
String cameraId =
Camera2CameraInfo.extractCameraId(camera.getCameraInfo());
```
--------------------------------
### Get VideoCapture Mirror Mode
Source: https://developer.android.com/jetpack/androidx/releases/camera
Retrieves the current mirroring mode for VideoCapture. This can be used to check the active mirroring settings.
```java
VideoCapture.getMirrorMode()
```
--------------------------------
### Query WorkInfo by Unique Work Names
Source: https://developer.android.com/jetpack/androidx/releases/work?hl=ru
Example of how to query WorkInfo objects based on their unique work names using WorkQuery.Builder.fromUniqueWorkNames().
```java
WorkQuery.Builder.fromUniqueWorkNames(...)
```
--------------------------------
### Configure Room with WebWorkerSQLiteDriver
Source: https://developer.android.com/jetpack/androidx/releases/room3
Sets up Room to use `WebWorkerSQLiteDriver` for web platforms, enabling off-main thread database operations and OPFS storage. Requires a custom worker implementation.
```kotlin
fun createDatabase(): MusicDatabase {
return Room.databaseBuilder("music.db")
.setDriver(WebWorkerSQLiteDriver(createWorker()))
.build()
}
fun createWorker() =
Worker(js("new URL(\"sqlite-web-worker/worker.js\", import.meta.url)"))
```
--------------------------------
### Observe Composable Function Example
Source: https://developer.android.com/jetpack/androidx/releases/compose-runtime?hl=bn
This pattern can be used to replicate the functionality of the deprecated Observe abstraction. It executes a composable lambda parameter.
```kotlin
@Composable fun Observe(body: @Composable () -> Unit) = body()
```
--------------------------------
### Suggest Dimension.percent(1f) and LayoutReference.withChainParams()
Source: https://developer.android.com/jetpack/androidx/releases/constraintlayout
Lint checks are available to suggest using `Dimension.percent(1f)` and `LayoutReference.withChainParams()` when typical patterns might lead to unpredictable behavior.
```kotlin
Dimension.percent(1f)
```
```kotlin
LayoutReference.withChainParams()
```
--------------------------------
### Initialize RuleController with Context and Resource ID
Source: https://developer.android.com/jetpack/androidx/releases/window
Replaces the older `SplitController.initialize()` method. Use `RuleController.getInstance(Context).setRules(RuleController.parse(Context, @ResId int))` to set rules from XML.
```kotlin
RuleController.getInstance(Context).setRules(RuleController.parse(Context, @ResId int))
```
--------------------------------
### Replace ProgressiveMediaSource.Factory setTag and setCustomCacheKey
Source: https://developer.android.com/jetpack/androidx/releases/media3
The `ProgressiveMediaSource.Factory#setTag` and `ProgressiveMediaSource.Factory#setCustomCacheKey` methods are removed. Use `MediaItem.Builder#setTag` and `MediaItem.Builder#setCustomCacheKey` instead.
```java
ProgressiveMediaSource.Factory#setTag
```
```java
ProgressiveMediaSource.Factory#setCustomCacheKey
```
```java
MediaItem.Builder#setTag
```
```java
MediaItem.Builder#setCustomCacheKey
```
--------------------------------
### Get Subscribed Controllers
Source: https://developer.android.com/jetpack/androidx/releases/media3?hl=bn
Adds `MediaLibrarySession.getSubscribedControllers(mediaId)` for convenience. This method allows easy retrieval of subscribed controllers for a given media ID.
```java
MediaLibrarySession.getSubscribedControllers(mediaId)
```
--------------------------------
### Configure Protobuf Serialization Plugin and Dependency (Groovy)
Source: https://developer.android.com/jetpack/androidx/releases/datastore
Apply the Protobuf plugin and add the Protobuf Kotlin Lite dependency for Protobuf serialization with DataStore. Configure protoc artifact and generation tasks.
```groovy
plugins {
id("com.google.protobuf") version "0.9.5"
}
dependencies {
implementation "com.google.protobuf:protobuf-kotlin-lite:4.32.1"
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:4.32.1"
}
generateProtoTasks {
all().forEach {
task ->
task.builtins {
create("java") {
option("lite")
}
create("kotlin")
}
}
}
}
```
--------------------------------
### Get NavController from FragmentContainerView
Source: https://developer.android.com/jetpack/androidx/releases/fragment
Use the getFragment() method on FragmentContainerView to retrieve the most recently added fragment, which can be useful for chaining calls to access its NavController.
```kotlin
val navController = binding.container.getFragment().navController
```
--------------------------------
### Replace ShadowMediaCodecConfig.withNoDefaultSupportedMimeTypes()
Source: https://developer.android.com/jetpack/androidx/releases/media3?hl=zh-cn
The deprecated `ShadowMediaCodecConfig.withNoDefaultSupportedMimeTypes()` method has been removed. Use `ShadowMediaCodecConfig.withNoDefaultSupportedCodecs()` instead.
```java
ShadowMediaCodecConfig.withNoDefaultSupportedCodecs()
```
--------------------------------
### Media Transformation and Effects for Media3
Source: https://developer.android.com/jetpack/androidx/releases/media3?hl=zh-cn
Include these dependencies for transforming media files and applying effects, such as Lottie effects, on video frames.
```gradle
// For transforming media files
implementation("androidx.media3:media3-transformer:$media3_version")
```
```gradle
// For applying effects on video frames
implementation("androidx.media3:media3-effect:$media3_version")
```
```gradle
// For applying Lottie effects on video frames
implementation("androidx.media3:media3-effect-lottie:$media3_version")
```
--------------------------------
### Get Target Frame Rate for VideoCapture
Source: https://developer.android.com/jetpack/androidx/releases/camera
Retrieves the target frame rate that has been set for VideoCapture. This can be used to confirm the configured frame rate.
```java
getTargetFramerate() API in VideoCapture
```
--------------------------------
### Register Custom DAO Return Type Converter
Source: https://developer.android.com/jetpack/androidx/releases/room3
Example of registering a `PagingSourceDaoReturnTypeConverter` using the `@DaoReturnTypeConverters` annotation to enable a DAO query to return a `PagingSource`.
```kotlin
@Dao
@DaoReturnTypeConverters(PagingSourceDaoReturnTypeConverter::class)
interface MusicDao {
@Query("SELECT * FROM Song)
fun getSongsPaginated(): PagingSource
}
```
--------------------------------
### Implement Navigation3 with NavDisplay
Source: https://developer.android.com/jetpack/androidx/releases/navigation3
Define navigation keys and use the NavDisplay composable to manage backstack state and screen content.
```kotlin
@Serialiable object Home : NavKey
@Serialiable object Chat : NavKey
val backStack = rememberNavBackStack(Home)
NavDisplay(backStack, entryProvider = entryProvider {
entry {
Column {
Text(“Home”)
Button(onClick = { backStack.add(Chat) } ) {
Text(“Go to Chat”)
}
}
}
entry { /* My Composable Content */ }
})
```
--------------------------------
### Tap-to-Focus Action Configuration
Source: https://developer.android.com/jetpack/androidx/releases/camera?hl=bn
Configure a tap-to-focus action using MeteringPointFactory, MeteringPoint, and FocusMeteringAction. Allows specifying focus and metering modes, and an optional auto-focus callback. Note the auto-cancellation duration.
```java
MeteringPointFactory factory = new SensorOrientedMeteringPointFactory(width, height);
MeteringPoint point = factory.createPoint(x, y);
FocusMeteringAction action = FocusMeteringAction.Builder.from(point,
MeteringMode.AF_ONLY)
.addPoint(point2, MeteringMode.AE_ONLY) // could have many
.setAutoFocusCallback(new OnAutoFocusListener(){
public void onFocusCompleted(boolean isSuccess) {
}
})
// auto calling cancelFocusAndMetering in 5 sec.
.setAutoCancelDuration(5, TimeUnit.Second)
.build();
```
--------------------------------
### Define ViewModelProvider.Factory using Kotlin DSL
Source: https://developer.android.com/jetpack/androidx/releases/lifecycle?hl=fa
Simplify factory creation by using the viewModelFactory DSL with lambda initializers.
```kotlin
val customFactory = viewModelFactory {
// The return type of the lambda automatically sets what class this lambda handles
initializer {
// Get the Application object from extras provided to the lambda
val application = checkNotNull(get(ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY))
HomeViewModel(application)
}
initializer {
val savedStateHandle = createSavedStateHandle()
DetailViewModel(savedStateHandle)
}
}
```
--------------------------------
### Start and Cancel Focus Metering
Source: https://developer.android.com/jetpack/androidx/releases/camera?hl=bn
Initiate a focus and metering operation using the configured action, or cancel an ongoing operation. These methods are part of the CameraControl API.
```java
getCameraControl(lensFacing).startFocusAndMetering(action);
```
```java
getCameraControl(lensFacing).cancelFocusAndMetering();
```
--------------------------------
### Get Pending Intent for Touch Event
Source: https://developer.android.com/jetpack/androidx/releases/wear-watchface
Use WatchFaceControlClient.getPendingIntentForTouchEvent to help watch faces launch intents in response to taps, working around framework limitations.
```java
PendingIntent pendingIntent = watchFaceControlClient.getPendingIntentForTouchEvent(event);
if (pendingIntent != null) {
// Launch intent
}
```
--------------------------------
### Navigate with NavOptions
Source: https://developer.android.com/jetpack/androidx/releases/navigation
Configures navigation options and executes a navigation action using the NavController.
```kotlin
.build();
navController.navigate(selectedBottomNavId, null, navOptions);
```
--------------------------------
### Retrieve SavedStateRegistry using View
Source: https://developer.android.com/jetpack/androidx/releases/savedstate
Use ViewTreeSavedStateRegistryOwner.get(View) to get the containing SavedStateRegistry from a View. Requires Activity 1.2.0-alpha05, Fragment 1.3.0-alpha05, and AppCompat 1.3.0-alpha01.
```java
ViewTreeSavedStateRegistryOwner.get(View)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.