From 7311f4905d9c7553abdccfc974656516dff3d4ab Mon Sep 17 00:00:00 2001 From: android-devrel-github-bot Date: Fri, 7 Aug 2026 14:24:00 +0000 Subject: [PATCH] Updates skills (2026-08-07 14:24) --- .claude-plugin/marketplace.json | 2 + .codex-plugin/plugin.json | 10 + build-system/agp/agp-9-upgrade/SKILL.md | 34 +- .../build/migrate-to-built-in-kotlin.md | 104 +-- .../build/releases/agp-9-0-0-release-notes.md | 316 ++------ .../agp-9-upgrade/references/buildconfig.md | 13 +- .../agp/agp-9-upgrade/references/ksp-kapt.md | 30 +- .../references/paparazzi-gradle-9.md | 17 +- .../agp/agp-9-upgrade/references/recipes.md | 18 +- camera/camerax/SKILL.md | 26 +- .../camerax/references/camera1-to-camerax.md | 27 +- .../camerax/references/camera2-to-camerax.md | 41 +- .../camerax/references/expert-blueprints.md | 7 +- camera/camerax/references/foldables.md | 21 +- camera/camerax/references/immutability.md | 11 +- camera/camerax/references/low-light.md | 16 +- camera/camerax/references/mlkit-spatial.md | 22 +- camera/camerax/references/modern-apis.md | 6 +- camera/camerax/references/testing.md | 21 +- camera/camerax/references/thermals.md | 14 +- camera/camerax/references/wear-os.md | 21 +- camera/camerax/references/xr.md | 10 +- device-ai/appfunctions/SKILL.md | 26 +- device-ai/appfunctions/context.md | 26 - .../references/adb-interaction-testing.md | 35 +- device-ai/appfunctions/references/context.md | 11 + .../references/feature-discovery-analysis.md | 33 +- .../implementation-configuration.md | 53 +- .../kdoc-refinement-optimization.md | 16 +- .../migrate-to-service-entry-point.md | 71 +- devtools/android-cli/SKILL.md | 123 ++- identity/verified-email/SKILL.md | 116 +-- .../identity/credential-manager/index.md | 35 +- .../credential-verifier.md | 27 +- .../email-verification-implementation.md | 106 +-- .../digital-credentials/email-verification.md | 78 +- .../identity/digital-credentials/index.md | 60 +- .../identity/passkeys/create-passkeys.md | 121 +-- .../sign-in/credential-manager-webview.md | 27 +- jetpack-compose/adaptive/SKILL.md | 96 +-- .../adaptive/flexbox/container-behavior.md | 49 +- .../layouts/adaptive/flexbox/get-started.md | 19 +- .../compose/layouts/adaptive/flexbox/index.md | 47 +- .../layouts/adaptive/flexbox/item-behavior.md | 65 +- .../adaptive/grid/container-properties.md | 94 +-- .../layouts/adaptive/grid/get-started.md | 13 +- .../ui/compose/layouts/adaptive/grid/index.md | 40 +- .../layouts/adaptive/grid/item-properties.md | 58 +- .../layouts/adaptive/mediaquery/index.md | 138 +--- .../develop/ui/compose/tooling/debug.md | 78 +- .../recipes/material-listdetail.md | 2 + .../SKILL.md | 63 +- .../analysis-of-the-project-and-layout.md | 29 +- .../migrate-xml-theme-to-compose.md | 50 +- .../interoperability-apis/compose-in-views.md | 79 +- .../interoperability-apis/views-in-compose.md | 92 +-- ...setup-compose-dependencies-and-compiler.md | 45 +- .../identify-optimal-xml-candidate.md | 10 +- .../references/xml-layout-migration.md | 12 +- jetpack-compose/theming/styles/SKILL.md | 40 +- .../ui/compose/designsystems/custom.md | 111 +-- .../develop/ui/compose/styles/fundamentals.md | 110 ++- .../ui/compose/styles/state-animations.md | 88 +-- .../ui/compose/styles/styles-vs-modifiers.md | 17 +- .../develop/ui/compose/styles/theming.md | 67 +- media/media3-cast-integration/SKILL.md | 224 ++++++ .../media/media3/cast/create-castplayer.md | 367 +++++++++ .../media3/cast/customize-castoptions.md | 88 +++ .../android/media/media3/cast/index.md | 13 + navigation/navigation-3/SKILL.md | 13 +- .../guide/navigation/navigation-3/index.md | 34 +- .../navigation-3/migration-guide.md | 165 ++-- .../navigation-3/recipes/animations.md | 2 + .../navigation/navigation-3/recipes/basic.md | 2 + .../navigation-3/recipes/basicdsl.md | 2 + .../navigation-3/recipes/basicsaveable.md | 2 + .../navigation-3/recipes/bottomsheet.md | 3 + .../navigation-3/recipes/common-ui.md | 2 + .../recipes/conditional-transitions.md | 184 +++++ .../navigation-3/recipes/conditional.md | 2 + .../navigation-3/recipes/deeplinks-basic.md | 744 ------------------ .../recipes/deeplinks-custommatcher.md | 178 +++++ .../recipes/deeplinks-staticuri.md | 143 ++++ ...ced.md => deeplinks-syntheticbackstack.md} | 68 +- .../recipes/deeplinks-uriarguments.md | 396 ++++++++++ .../navigation/navigation-3/recipes/dialog.md | 2 + .../navigation-3/recipes/lifecycle-owner.md | 187 +++++ .../recipes/material-listdetail.md | 2 + .../recipes/material-supportingpane.md | 2 + .../navigation-3/recipes/modular-hilt.md | 9 + .../navigation-3/recipes/modular-koin.md | 8 + .../recipes/multiple-backstacks.md | 74 +- .../navigation-3/recipes/passingarguments.md | 5 + .../navigation-3/recipes/results-event.md | 6 + .../navigation-3/recipes/results-state.md | 6 + .../navigation-3/recipes/scenes-listdetail.md | 4 + .../navigation-3/recipes/scenes-twopane.md | 4 + .../navigation/type-safe-destinations.md | 21 +- performance/r8-analyzer/SKILL.md | 38 +- .../references/CONFIGURATION-ANALYZER.md | 36 +- .../r8-analyzer/references/CONFIGURATION.md | 11 +- .../references/KEEP-RULES-IMPACT-HIERARCHY.md | 40 +- .../r8-analyzer/references/REDUNDANT-RULES.md | 109 +-- .../references/REFLECTION-GUIDE.md | 108 +-- .../r8-analyzer/references/REPORT_FORMAT.md | 14 +- .../enable-app-optimization.md | 119 +-- .../testing/other-components/ui-automator.md | 106 +-- play/engage-sdk-integration/SKILL.md | 18 +- .../android/guide/playcore/engage/faq.md | 215 ++--- .../android/guide/playcore/engage/food.md | 238 ++---- .../guide/playcore/engage/healthandfitness.md | 248 ++---- .../android/guide/playcore/engage/listen.md | 226 ++---- .../guide/playcore/engage/otherverticals.md | 280 ++----- .../android/guide/playcore/engage/read.md | 209 ++--- .../android/guide/playcore/engage/shopping.md | 269 ++----- .../android/guide/playcore/engage/social.md | 649 +++++++++++++++ .../android/guide/playcore/engage/travel.md | 293 ++----- .../engage/tv/continue-watching/index.md | 15 +- .../guide/playcore/engage/tv/entitlements.md | 101 +-- .../playcore/engage/tv/getting-started.md | 51 +- .../playcore/engage/tv/recommendations.md | 114 +-- .../android/guide/playcore/engage/watch.md | 220 ++---- .../references/patterns.md | 48 +- .../references/requests.md | 3 +- .../SKILL.md | 22 +- .../google/play/billing/release-notes.md | 559 +++---------- .../references/migration-logic.md | 20 +- .../references/version-checklist.md | 3 +- security/android-intent-security/SKILL.md | 83 +- system/edge-to-edge/SKILL.md | 82 +- testing/testing-setup/SKILL.md | 86 +- .../ui/compose/testing/common-patterns.md | 72 +- .../preview/compose-screenshot-testing.md | 93 +-- .../dependency-injection/hilt-testing.md | 156 +--- tv/leanback-to-compose-tv-migration/SKILL.md | 692 ++++++++++++++++ .../training/tv/get-started/navigation.md | 246 ++++++ .../training/tv/playback/compose/browse.md | 149 ++++ .../training/tv/playback/compose/index.md | 128 +++ wear/wear-compose-m3/SKILL.md | 184 +++-- .../wearables/compose/migrate-to-material3.md | 170 ++-- .../foundation/AmbientModeSample.kt.md.txt | 123 +++ .../foundation/CurvedWorldSample.kt.md.txt | 430 ++++++++++ .../foundation/ExpandableSample.kt.md.txt | 99 +++ .../HierarchicalFocusSample.kt.md.txt | 141 ++++ .../foundation/PagerSamples.kt.md.txt | 56 ++ .../foundation/RotarySamples.kt.md.txt | 153 ++++ .../ScalingLazyColumnSample.kt.md.txt | 131 +++ .../SwipeToDismissBoxSample.kt.md.txt | 168 ++++ .../foundation/SwipeToRevealSample.kt.md.txt | 282 +++++++ .../TransformingLazyColumnSample.kt.md.txt | 335 ++++++++ .../material3/AlertDialogSample.kt.md.txt | 377 +++++++++ .../material3/AnimatedTextSample.kt.md.txt | 165 ++++ .../material3/ButtonGroupSample.kt.md.txt | 91 +++ .../material3/ButtonSample.kt.md.txt | 496 ++++++++++++ .../references/material3/CardSample.kt.md.txt | 470 +++++++++++ .../material3/CheckboxButtonSample.kt.md.txt | 69 ++ .../ConfirmationDialogSample.kt.md.txt | 162 ++++ .../material3/CurvedTextSamples.kt.md.txt | 78 ++ .../material3/DatePickerSample.kt.md.txt | 131 +++ .../DynamicColorSchemeSample.kt.md.txt | 74 ++ .../material3/EdgeButtonSample.kt.md.txt | 63 ++ .../FadingExpandingLabelSample.kt.md.txt | 60 ++ .../material3/IconButtonSample.kt.md.txt | 125 +++ .../IconToggleButtonSample.kt.md.txt | 116 +++ .../material3/LevelIndicatorSample.kt.md.txt | 68 ++ .../LinearProgressIndicatorSample.kt.md.txt | 50 ++ .../material3/ListHeaderSample.kt.md.txt | 177 +++++ .../OneHandedGestureSamples.kt.md.txt | 651 +++++++++++++++ .../OpenOnPhoneDialogSample.kt.md.txt | 57 ++ .../material3/PageIndicatorSample.kt.md.txt | 110 +++ .../material3/PagerScaffoldSample.kt.md.txt | 204 +++++ .../material3/PickerGroupSample.kt.md.txt | 139 ++++ .../material3/PickerSample.kt.md.txt | 111 +++ .../material3/PlaceholderSample.kt.md.txt | 182 +++++ .../ProgressIndicatorSample.kt.md.txt | 263 +++++++ .../material3/RadioButtonSample.kt.md.txt | 109 +++ .../material3/ScaffoldSample.kt.md.txt | 146 ++++ .../material3/ScrollAwaySample.kt.md.txt | 97 +++ .../material3/ScrollIndicatorSample.kt.md.txt | 66 ++ .../material3/SliderSample.kt.md.txt | 86 ++ .../material3/StepperSample.kt.md.txt | 148 ++++ .../SurfaceTransformationSample.kt.md.txt | 165 ++++ .../SwipeToDismissBoxSample.kt.md.txt | 171 ++++ .../material3/SwipeToRevealSample.kt.md.txt | 364 +++++++++ .../material3/SwitchButtonSample.kt.md.txt | 68 ++ .../material3/TextButtonSample.kt.md.txt | 115 +++ .../TextToggleButtonSample.kt.md.txt | 71 ++ .../material3/TimePickerSample.kt.md.txt | 151 ++++ .../material3/TimeTextSample.kt.md.txt | 65 ++ .../TransformationSpecSample.kt.md.txt | 246 ++++++ ...ingLazyColumnNotificationsSample.kt.md.txt | 89 +++ .../TransformingLazyColumnSample.kt.md.txt | 309 ++++++++ .../SKILL.md | 99 +-- .../ai-glasses/guides/interaction/inputs.md | 16 +- .../access-hardware-projected-context.md | 311 ++++---- .../jetpack-compose-glimmer/buttons.md | 29 +- .../jetpack-compose-glimmer/cards.md | 23 +- .../jetpack-compose-glimmer/focus.md | 49 +- .../jetpack-compose-glimmer/icons.md | 20 +- .../jetpack-compose-glimmer/text.md | 25 +- .../jetpack-compose-glimmer/title-chips.md | 17 +- .../request-hardware-permissions.md | 196 ++--- .../references/button-samples-source.md | 6 +- .../references/button-source.md | 6 +- .../references/card-samples-source.md | 6 +- .../references/card-source.md | 6 +- .../references/deptheffect-source.md | 6 +- .../references/deptheffectlevels-source.md | 6 +- .../glimmersansflextypography-source.md | 6 +- .../references/glimmertheme-source.md | 6 +- .../references/icon-source.md | 6 +- .../references/iconbutton-source.md | 6 +- .../references/iconsizes-source.md | 6 +- .../references/list-source.md | 6 +- .../references/listitem-source.md | 6 +- .../references/liststate-source.md | 6 +- .../references/material-hct-source.md | 2 + .../references/projectedcontext-source.md | 6 +- .../references/stack-source.md | 6 +- .../references/stackitemscope-source.md | 6 +- .../references/stackstate-source.md | 6 +- .../references/surface-source.md | 6 +- .../references/titlechip-samples-source.md | 6 +- .../references/titlechip-source.md | 6 +- 224 files changed, 15705 insertions(+), 6829 deletions(-) delete mode 100644 device-ai/appfunctions/context.md create mode 100644 device-ai/appfunctions/references/context.md create mode 100644 media/media3-cast-integration/SKILL.md create mode 100644 media/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md create mode 100644 media/media3-cast-integration/references/android/media/media3/cast/customize-castoptions.md create mode 100644 media/media3-cast-integration/references/android/media/media3/cast/index.md create mode 100644 navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/conditional-transitions.md delete mode 100644 navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-basic.md create mode 100644 navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-custommatcher.md create mode 100644 navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-staticuri.md rename navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/{deeplinks-advanced.md => deeplinks-syntheticbackstack.md} (62%) create mode 100644 navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-uriarguments.md create mode 100644 navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/lifecycle-owner.md create mode 100644 play/engage-sdk-integration/references/android/guide/playcore/engage/social.md create mode 100644 tv/leanback-to-compose-tv-migration/SKILL.md create mode 100644 tv/leanback-to-compose-tv-migration/references/android/training/tv/get-started/navigation.md create mode 100644 tv/leanback-to-compose-tv-migration/references/android/training/tv/playback/compose/browse.md create mode 100644 tv/leanback-to-compose-tv-migration/references/android/training/tv/playback/compose/index.md create mode 100644 wear/wear-compose-m3/references/foundation/AmbientModeSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/foundation/CurvedWorldSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/foundation/ExpandableSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/foundation/HierarchicalFocusSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/foundation/PagerSamples.kt.md.txt create mode 100644 wear/wear-compose-m3/references/foundation/RotarySamples.kt.md.txt create mode 100644 wear/wear-compose-m3/references/foundation/ScalingLazyColumnSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/foundation/SwipeToDismissBoxSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/foundation/SwipeToRevealSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/foundation/TransformingLazyColumnSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/AlertDialogSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/AnimatedTextSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/ButtonGroupSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/ButtonSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/CardSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/CheckboxButtonSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/ConfirmationDialogSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/CurvedTextSamples.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/DatePickerSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/DynamicColorSchemeSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/EdgeButtonSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/FadingExpandingLabelSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/IconButtonSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/IconToggleButtonSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/LevelIndicatorSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/LinearProgressIndicatorSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/ListHeaderSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/OneHandedGestureSamples.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/OpenOnPhoneDialogSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/PageIndicatorSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/PagerScaffoldSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/PickerGroupSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/PickerSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/PlaceholderSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/ProgressIndicatorSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/RadioButtonSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/ScaffoldSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/ScrollAwaySample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/ScrollIndicatorSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/SliderSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/StepperSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/SurfaceTransformationSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/SwipeToDismissBoxSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/SwipeToRevealSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/SwitchButtonSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/TextButtonSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/TextToggleButtonSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/TimePickerSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/TimeTextSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/TransformationSpecSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/TransformingLazyColumnNotificationsSample.kt.md.txt create mode 100644 wear/wear-compose-m3/references/material3/TransformingLazyColumnSample.kt.md.txt diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index d8900b3..ba1297f 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -22,6 +22,7 @@ "./jetpack-compose/adaptive", "./jetpack-compose/migration/migrate-xml-views-to-jetpack-compose", "./jetpack-compose/theming/styles", + "./media/media3-cast-integration", "./navigation/navigation-3", "./performance/r8-analyzer", "./play/engage-sdk-integration", @@ -32,6 +33,7 @@ "./security/android-intent-security", "./system/edge-to-edge", "./testing/testing-setup", + "./tv/leanback-to-compose-tv-migration", "./wear/wear-compose-m3", "./xr/display-glasses-with-jetpack-compose-glimmer" ], diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index f28a37b..13f515a 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -55,6 +55,11 @@ "path": "./jetpack-compose/theming/styles" } }, + { + "source": { + "path": "./media/media3-cast-integration" + } + }, { "source": { "path": "./navigation/navigation-3" @@ -105,6 +110,11 @@ "path": "./testing/testing-setup" } }, + { + "source": { + "path": "./tv/leanback-to-compose-tv-migration" + } + }, { "source": { "path": "./wear/wear-compose-m3" diff --git a/build-system/agp/agp-9-upgrade/SKILL.md b/build-system/agp/agp-9-upgrade/SKILL.md index 247b6ee..8ad57ba 100644 --- a/build-system/agp/agp-9-upgrade/SKILL.md +++ b/build-system/agp/agp-9-upgrade/SKILL.md @@ -6,7 +6,7 @@ description: Upgrades, or migrates, an Android project to use Android Gradle Plu license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-23' + last-updated: '2026-08-06' keywords: - Android Gradle Plugin 9 - AGP 9 @@ -18,23 +18,13 @@ metadata: ## Migration guide -See the [AGP 9 migration guide](references/android/build/releases/agp-9-0-0-release-notes.md) for the major changes, many -breaking, in AGP 9 compared to AGP 8. +See the [AGP 9 migration guide](references/android/build/releases/agp-9-0-0-release-notes.md) for the major changes, many breaking, in AGP 9 compared to AGP 8. ## Requirements -If the user requests to update or migrate to AGP 9, first check the AGP version -used in the project. If it is lower than 9, stop and ask the user to run the AGP -Upgrade Assistant in Android Studio to update to the latest stable version of -AGP, and confirm when done. The user may also request that this requirement be -skipped; if this is the case, you should update the version of AGP to the latest -stable version as part of the AGP 9 migration. See the -[AGP 9 migration guide](references/android/build/releases/agp-9-0-0-release-notes.md) for how to do this. +If the user requests to update or migrate to AGP 9, first check the AGP version used in the project. If it is lower than 9, stop and ask the user to run the AGP Upgrade Assistant in Android Studio to update to the latest stable version of AGP, and confirm when done. The user may also request that this requirement be skipped; if this is the case, you should update the version of AGP to the latest stable version as part of the AGP 9 migration. See the [AGP 9 migration guide](references/android/build/releases/agp-9-0-0-release-notes.md) for how to do this. -Each version of AGP has its own set of compatibilities with other tools, such as -Gradle, JDK, and Kotlin. The release notes for each of these versions will -include a **Compatibility** table indicating the minimum versions for these -tools. +Each version of AGP has its own set of compatibilities with other tools, such as Gradle, JDK, and Kotlin. The release notes for each of these versions will include a **Compatibility** table indicating the minimum versions for these tools. Do not use this skill for KMP projects, as they are unsupported. @@ -44,8 +34,7 @@ If AGP is already at 9 or higher, then do the following: ### Step 1: Update dependencies -If KSP (`com.google.devtools.ksp`) is used in the project, ensure it is on -version 2.3.6 or higher. +If KSP (`com.google.devtools.ksp`) is used in the project, ensure it is on version 2.3.6 or higher. If Hilt is used in the project, ensure it is on version 2.59.2 or higher. @@ -57,19 +46,15 @@ See [the guide](references/android/build/migrate-to-built-in-kotlin.md) for deta See [the guide](references/android/build/releases/agp-9-0-0-release-notes.md) for detailed information. -See also [gradle-recipes](references/recipes.md) for examples on how to migrate old code to code -that is compatible with AGP 9 and the new DSL. +See also [gradle-recipes](references/recipes.md) for examples on how to migrate old code to code that is compatible with AGP 9 and the new DSL. ### Step 4. Migrate kapt to KSP or legacy-kapt -If KSP (`com.google.devtools.ksp`) or kapt (`org.jetbrains.kotlin.kapt`) are -used in the project, see [KSP, kapt, and legacy-kapt](references/ksp-kapt.md) for detailed migration -steps. +If KSP (`com.google.devtools.ksp`) or kapt (`org.jetbrains.kotlin.kapt`) are used in the project, see [KSP, kapt, and legacy-kapt](references/ksp-kapt.md) for detailed migration steps. ### Step 5. BuildConfig -If any Android module contains custom BuildConfig fields, see [BuildConfig](references/buildconfig.md) -for detailed information. +If any Android module contains custom BuildConfig fields, see [BuildConfig](references/buildconfig.md) for detailed information. ### Step 6. Update gradle.properties @@ -99,5 +84,4 @@ After migration, verify the following: ## Troubleshooting -Paparazzi v2.0.0-alpha04 and lower versions have issues with AGP 9. See -[references/paparazzi-gradle-9.md](references/paparazzi-gradle-9.md) for details. +Paparazzi v2.0.0-alpha04 and lower versions have issues with AGP 9. See [references/paparazzi-gradle-9.md](references/paparazzi-gradle-9.md) for details. diff --git a/build-system/agp/agp-9-upgrade/references/android/build/migrate-to-built-in-kotlin.md b/build-system/agp/agp-9-upgrade/references/android/build/migrate-to-built-in-kotlin.md index 7306e7b..820bf0f 100644 --- a/build-system/agp/agp-9-upgrade/references/android/build/migrate-to-built-in-kotlin.md +++ b/build-system/agp/agp-9-upgrade/references/android/build/migrate-to-built-in-kotlin.md @@ -1,33 +1,20 @@ -Android Gradle plugin 9.0 introduces built-in Kotlin support and enables it -by default. That means you no longer have to apply the -`org.jetbrains.kotlin.android` (or `kotlin-android`) plugin in your build files -to compile Kotlin source files. -With built-in Kotlin, your build files are simpler and you can avoid -compatibility issues between AGP and the `kotlin-android` plugin. +Android Gradle plugin 9.0 introduces built-in Kotlin support and enables it by default. That means you no longer have to apply the `org.jetbrains.kotlin.android` (or `kotlin-android`) plugin in your build files to compile Kotlin source files. With built-in Kotlin, your build files are simpler and you can avoid compatibility issues between AGP and the `kotlin-android` plugin. > [!NOTE] > **Note:** Built-in Kotlin replaces the `kotlin-android` plugin only. If you are writing a Kotlin Multiplatform (KMP) library module, you still need to apply the `org.jetbrains.kotlin.multiplatform` plugin and the [`com.android.kotlin.multiplatform.library`](https://developer.android.com/kotlin/multiplatform/plugin) plugin. Also, using the `org.jetbrains.kotlin.multiplatform` plugin together with the `com.android.library` or `com.android.application` plugin is no longer allowed when built-in Kotlin is enabled. ## Enable built-in Kotlin -You need AGP 9.0 or higher to have built-in Kotlin support. -AGP 9.0 already enables built-in Kotlin for all your modules where you apply -AGP, so you don't need to do anything to enable it. However, if you previously -[opted out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin) by setting `android.builtInKotlin=false` -in the `gradle.properties` file, you need to remove that setting or set it to -`true`. +You need AGP 9.0 or higher to have built-in Kotlin support. AGP 9.0 already enables built-in Kotlin for all your modules where you apply AGP, so you don't need to do anything to enable it. However, if you previously [opted out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin) by setting `android.builtInKotlin=false` in the `gradle.properties` file, you need to remove that setting or set it to `true`. > [!NOTE] > **Note:** You can also enable built-in Kotlin for [one module at a time](https://developer.android.com/build/migrate-to-built-in-kotlin#module-by-module-migration). -Built-in Kotlin requires some changes to your project, so after you -have built-in Kotlin enabled, follow the next steps to migrate your project. +Built-in Kotlin requires some changes to your project, so after you have built-in Kotlin enabled, follow the next steps to migrate your project. ## Migration steps -After you upgrade your project from an older AGP version to AGP 9.0 or after -you manually [enable built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#enable-built-in-kotlin), you might see the following error -message: +After you upgrade your project from an older AGP version to AGP 9.0 or after you manually [enable built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#enable-built-in-kotlin), you might see the following error message: Failed to apply plugin 'org.jetbrains.kotlin.android'. > Cannot add extension with name 'kotlin', as there is an extension already registered with that name. @@ -37,8 +24,7 @@ message: Failed to apply plugin 'com.jetbrains.kotlin.android' > The 'org.jetbrains.kotlin.android' plugin is no longer required for Kotlin support since AGP 9.0. -This error occurs because built-in Kotlin requires some changes to your project. -To resolve this error, follow these steps: +This error occurs because built-in Kotlin requires some changes to your project. To resolve this error, follow these steps: > [!NOTE] > **Note:** If you're not yet ready to migrate your project, you can also [opt out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin). @@ -50,10 +36,7 @@ To resolve this error, follow these steps: ### 1. Remove the `kotlin-android` plugin -Remove the `org.jetbrains.kotlin.android` (or `kotlin-android`) plugin from -the module-level build files where you apply it. -The exact code to remove depends on -whether you use [version catalogs](https://docs.gradle.org/current/userguide/version_catalogs.html) to declare plugins. +Remove the `org.jetbrains.kotlin.android` (or `kotlin-android`) plugin from the module-level build files where you apply it. The exact code to remove depends on whether you use [version catalogs](https://docs.gradle.org/current/userguide/version_catalogs.html) to declare plugins. ### With version catalogs @@ -137,8 +120,7 @@ plugins { } ``` -If you use version catalogs, also remove the plugin definition from the -version catalog TOML file (usually `gradle/libs.versions.toml`): +If you use version catalogs, also remove the plugin definition from the version catalog TOML file (usually `gradle/libs.versions.toml`): ```toml [plugins] @@ -147,16 +129,11 @@ kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "KOTLIN_VE ### 2. Migrate the `kotlin-kapt` plugin if necessary -The `org.jetbrains.kotlin.kapt` (or `kotlin-kapt`) plugin is incompatible with -built-in Kotlin. If you use `kapt`, we recommend that you -[migrate your project to KSP](https://developer.android.com/build/migrate-to-ksp). +The `org.jetbrains.kotlin.kapt` (or `kotlin-kapt`) plugin is incompatible with built-in Kotlin. If you use `kapt`, we recommend that you [migrate your project to KSP](https://developer.android.com/build/migrate-to-ksp). -If you can't migrate to KSP yet, replace the `kotlin-kapt` plugin with the -`com.android.legacy-kapt` plugin, using the same version as your Android Gradle -plugin. +If you can't migrate to KSP yet, replace the `kotlin-kapt` plugin with the `com.android.legacy-kapt` plugin, using the same version as your Android Gradle plugin. -For example, with version catalogs, update your version catalog TOML -file as follows: +For example, with version catalogs, update your version catalog TOML file as follows: ```toml [plugins] @@ -216,8 +193,7 @@ plugins { ### 3. Migrate the `android.kotlinOptions{}` DSL if necessary -If you use the `android.kotlinOptions{}` DSL, you need to -migrate it to the [`kotlin.compilerOptions{}`](https://kotlinlang.org/docs/gradle-compiler-options.html#migrate-from-kotlinoptions-to-compileroptions) DSL. +If you use the `android.kotlinOptions{}` DSL, you need to migrate it to the [`kotlin.compilerOptions{}`](https://kotlinlang.org/docs/gradle-compiler-options.html#migrate-from-kotlinoptions-to-compileroptions) DSL. For example, update this code: @@ -274,15 +250,9 @@ kotlin { ### 4. Migrate the `kotlin.sourceSets{}` DSL if necessary -When you use the `kotlin-android` plugin, AGP lets you add additional Kotlin -source directories using either the [`android.sourceSets{}`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/AndroidSourceSet) DSL or the -[`kotlin.sourceSets{}`](https://kotlinlang.org/api/kotlin-gradle-plugin/kotlin-gradle-plugin-api/org.jetbrains.kotlin.gradle.plugin/-kotlin-source-set/) DSL. -With the `android.sourceSets{}` DSL, you can add the directories to either the -`AndroidSourceSet.kotlin` set or the `AndroidSourceSet.java` set. +When you use the `kotlin-android` plugin, AGP lets you add additional Kotlin source directories using either the [`android.sourceSets{}`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/AndroidSourceSet) DSL or the [`kotlin.sourceSets{}`](https://kotlinlang.org/api/kotlin-gradle-plugin/kotlin-gradle-plugin-api/org.jetbrains.kotlin.gradle.plugin/-kotlin-source-set/) DSL. With the `android.sourceSets{}` DSL, you can add the directories to either the `AndroidSourceSet.kotlin` set or the `AndroidSourceSet.java` set. -With built-in Kotlin, the only supported option is to add the directories to the -`AndroidSourceSet.kotlin` set using the `android.sourceSets{}` DSL. -If you use unsupported options, migrate them as follows: +With built-in Kotlin, the only supported option is to add the directories to the `AndroidSourceSet.kotlin` set using the `android.sourceSets{}` DSL. If you use unsupported options, migrate them as follows: ### Kotlin @@ -322,10 +292,7 @@ android.sourceSets.named("main") { } ``` -If you want to add a Kotlin source directory to a specific variant or if the -directory is generated by a task, you can use the -[`addStaticSourceDirectory`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/SourceDirectories#addStaticSourceDirectory(kotlin.String)) or [`addGeneratedSourceDirectory`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/SourceDirectories#addGeneratedSourceDirectory(org.gradle.api.tasks.TaskProvider,kotlin.Function1)) methods -in the [variant API](https://developer.android.com/build/extend-agp#variant-api-artifacts-tasks): +If you want to add a Kotlin source directory to a specific variant or if the directory is generated by a task, you can use the [`addStaticSourceDirectory`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/SourceDirectories#addStaticSourceDirectory(kotlin.String)) or [`addGeneratedSourceDirectory`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/SourceDirectories#addGeneratedSourceDirectory(org.gradle.api.tasks.TaskProvider,kotlin.Function1)) methods in the [variant API](https://developer.android.com/build/extend-agp#variant-api-artifacts-tasks): ### Kotlin @@ -347,57 +314,36 @@ androidComponents.onVariants { variant -> ## Report issues -If you encounter issues after completing the previous steps, -review the known issues in [issue #438678642](https://issuetracker.google.com/438678642) and give us -feedback if needed. +If you encounter issues after completing the previous steps, review the known issues in [issue #438678642](https://issuetracker.google.com/438678642) and give us feedback if needed. ## Opt out of built-in Kotlin -If you are unable to migrate your project to use built-in Kotlin, set -`android.builtInKotlin=false` in the `gradle.properties` file to temporarily -disable it. -When you do that, the build shows a warning reminding you to migrate to built-in -Kotlin as you won't be able to disable built-in Kotlin in AGP 10.0. +If you are unable to migrate your project to use built-in Kotlin, set `android.builtInKotlin=false` in the `gradle.properties` file to temporarily disable it. When you do that, the build shows a warning reminding you to migrate to built-in Kotlin as you won't be able to disable built-in Kotlin in AGP 10.0. > [!NOTE] > **Note:** You also need to set `android.newDsl=false` to opt out of the [new DSL](https://developer.android.com/r/tools/new-dsl) because the `kotlin-android` plugin is not compatible with it. -Once you're ready to migrate your project, [enable built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#enable-built-in-kotlin) -and follow the [migration steps](https://developer.android.com/build/migrate-to-built-in-kotlin#migration-steps). +Once you're ready to migrate your project, [enable built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#enable-built-in-kotlin) and follow the [migration steps](https://developer.android.com/build/migrate-to-built-in-kotlin#migration-steps). ## Module-by-module migration -The `android.builtInKotlin` Gradle property lets you enable or disable built-in -Kotlin for all your modules where you apply AGP. +The `android.builtInKotlin` Gradle property lets you enable or disable built-in Kotlin for all your modules where you apply AGP. -If migrating all your modules at once is challenging, you can migrate one module -at a time: +If migrating all your modules at once is challenging, you can migrate one module at a time: -1. Set `android.builtInKotlin=false` in the `gradle.properties` file to - disable built-in Kotlin for all modules. +1. Set `android.builtInKotlin=false` in the `gradle.properties` file to disable built-in Kotlin for all modules. -2. Apply the `com.android.built-in-kotlin` plugin to the module - you want to enable built-in Kotlin, using the same version as your - Android Gradle plugin. +2. Apply the `com.android.built-in-kotlin` plugin to the module you want to enable built-in Kotlin, using the same version as your Android Gradle plugin. -3. Follow the previous [migration steps](https://developer.android.com/build/migrate-to-built-in-kotlin#migration-steps) to migrate this module to - built-in Kotlin. +3. Follow the previous [migration steps](https://developer.android.com/build/migrate-to-built-in-kotlin#migration-steps) to migrate this module to built-in Kotlin. -4. Once you've migrated all your modules, remove the - `android.builtInKotlin=false` setting in `gradle.properties` - and the `com.android.built-in-kotlin` plugin in your build files. +4. Once you've migrated all your modules, remove the `android.builtInKotlin=false` setting in `gradle.properties` and the `com.android.built-in-kotlin` plugin in your build files. ## Option to selectively disable built-in Kotlin -Android Gradle plugin 9.0 enables built-in Kotlin for all modules where it is -applied. -We recommend disabling built-in Kotlin selectively for modules that don't have -Kotlin sources in large projects. -This removes both the Kotlin compilation task, which has a small build -performance cost, and the automatic dependency on the Kotlin standard library. +Android Gradle plugin 9.0 enables built-in Kotlin for all modules where it is applied. We recommend disabling built-in Kotlin selectively for modules that don't have Kotlin sources in large projects. This removes both the Kotlin compilation task, which has a small build performance cost, and the automatic dependency on the Kotlin standard library. -To disable built-in Kotlin for a module, -set `enableKotlin = false` in that module's build file: +To disable built-in Kotlin for a module, set `enableKotlin = false` in that module's build file: ### Kotlin diff --git a/build-system/agp/agp-9-upgrade/references/android/build/releases/agp-9-0-0-release-notes.md b/build-system/agp/agp-9-upgrade/references/android/build/releases/agp-9-0-0-release-notes.md index d092353..40a5d58 100644 --- a/build-system/agp/agp-9-upgrade/references/android/build/releases/agp-9-0-0-release-notes.md +++ b/build-system/agp/agp-9-upgrade/references/android/build/releases/agp-9-0-0-release-notes.md @@ -1,25 +1,16 @@
-Android Gradle plugin 9.0 is a major release that brings API and behavior -changes. +Android Gradle plugin 9.0 is a major release that brings API and behavior changes. -To update to Android Gradle plugin 9.0.1, use the -[Android Gradle plugin Upgrade Assistant](https://developer.android.com/build/agp-upgrade-assistant). The AGP upgrade assistant helps -preserve existing behaviors when upgrading your project whenever appropriate, so -you can upgrade your project to use AGP 9.0 even if you're not ready to -adopt all the new defaults in AGP 9.0. +To update to Android Gradle plugin 9.0.1, use the [Android Gradle plugin Upgrade Assistant](https://developer.android.com/build/agp-upgrade-assistant). The AGP upgrade assistant helps preserve existing behaviors when upgrading your project whenever appropriate, so you can upgrade your project to use AGP 9.0 even if you're not ready to adopt all the new defaults in AGP 9.0. -There are also two agent skills available to make the upgrade process easier. -For a non-KMP app, try the [AGP 9 upgrade skill](https://github.com/android/skills/tree/main/build/agp/agp-9-upgrade) from the -Android skills repository. For a KMP app, try the [AGP 9 upgrade -skill](https://github.com/Kotlin/kotlin-agent-skills/tree/main/skills/kotlin-tooling-agp9-migration) from JetBrains. For more information about using skills -in Android Studio, see [Extend Agent Mode with skills](https://developer.android.com/studio/gemini/skills). +There are also two agent skills available to make the upgrade process easier. For a non-KMP app, try the [AGP 9 upgrade skill](https://github.com/android/skills/tree/main/build/agp/agp-9-upgrade) from the Android skills repository. For a KMP app, try the [AGP 9 upgrade skill](https://github.com/Kotlin/kotlin-agent-skills/tree/main/skills/kotlin-tooling-agp9-migration) from JetBrains. For more information about using skills in Android Studio, see [Extend Agent Mode with skills](https://developer.android.com/studio/gemini/skills). ## Compatibility -The maximum API level that Android Gradle plugin 9.0 supports is API level 36.1. -Here is other compatibility info: +The maximum API level that Android Gradle plugin 9.0 supports is API level 36.1. Here is other compatibility info: +
| | Minimum version | Default version | Notes | |---:|:---:|:---:|:---:| @@ -32,52 +23,25 @@ Here is other compatibility info: ## The `android` DSL classes now only implement the new public interfaces -Over the last several years, we have introduced -[new interfaces](https://developer.android.com/reference/tools/gradle-api) for our DSL and API in order to -better control which APIs are public. AGP versions -7.x and 8.x still used the old DSL types (for example `BaseExtension`) which -also implemented the new public interfaces, in order to maintain compatibility -as work progressed on the interfaces. +Over the last several years, we have introduced [new interfaces](https://developer.android.com/reference/tools/gradle-api) for our DSL and API in order to better control which APIs are public. AGP versions 7.x and 8.x still used the old DSL types (for example `BaseExtension`) which also implemented the new public interfaces, in order to maintain compatibility as work progressed on the interfaces. -AGP 9.0 uses our new DSL interfaces exclusively, -and the implementations have changed to new types that are fully hidden. This -also removes access to the old, deprecated variant API. +AGP 9.0 uses our new DSL interfaces exclusively, and the implementations have changed to new types that are fully hidden. This also removes access to the old, deprecated variant API. To update to AGP 9.0, you might need to do the following: -- **Ensure your project is compatible with [built-in - Kotlin](https://developer.android.com/build/releases/agp-9-0-0-release-notes#android-gradle-plugin-built-in-kotlin):** The `org.jetbrains.kotlin.android` plugin is not compatible with the new DSL. -- **Switch KMP projects to the - [Android Gradle Library Plugin for KMP](https://developer.android.com/kotlin/multiplatform/plugin):** - Using the `org.jetbrains.kotlin.multiplatform` plugin in the same Gradle - subproject as the `com.android.library` and `com.android.application` plugins - is not compatible with the new DSL. +- **Ensure your project is compatible with [built-in Kotlin](https://developer.android.com/build/releases/agp-9-0-0-release-notes#android-gradle-plugin-built-in-kotlin):** The `org.jetbrains.kotlin.android` plugin is not compatible with the new DSL. +- **Switch KMP projects to the [Android Gradle Library Plugin for KMP](https://developer.android.com/kotlin/multiplatform/plugin):** Using the `org.jetbrains.kotlin.multiplatform` plugin in the same Gradle subproject as the `com.android.library` and `com.android.application` plugins is not compatible with the new DSL. > [!NOTE] > **Note:** The new KMP integration does not support using KMP and the Android Application plugin in the same Gradle subproject. To migrate, extract your Android app to a separate subproject. -- **Update your build files:** - While the change of interfaces is meant to keep - the DSL as similar as possible, there might be - [some small changes](https://developer.android.com/build/releases/agp-9-0-0-release-notes#android-gradle-plugin-changed-dsl). +- **Update your build files:** While the change of interfaces is meant to keep the DSL as similar as possible, there might be [some small changes](https://developer.android.com/build/releases/agp-9-0-0-release-notes#android-gradle-plugin-changed-dsl). -- **Update your custom build logic to reference the new DSL and API:** - Replace any references to the internal DSL with the public DSL interfaces. - In most cases this will be a one-to-one replacement. - Replace any use of the `applicationVariants` and similar APIs with the new - [`androidComponents` API](https://developer.android.com/build/extend-agp#variant-api-artifacts-tasks). - This might be more complex, as the `androidComponents` API - is designed to be more stable to keep plugins compatible longer. Check our - [Gradle Recipes](https://github.com/android/gradle-recipes/tree/agp-9.0) - for examples. +- **Update your custom build logic to reference the new DSL and API:** Replace any references to the internal DSL with the public DSL interfaces. In most cases this will be a one-to-one replacement. Replace any use of the `applicationVariants` and similar APIs with the new [`androidComponents` API](https://developer.android.com/build/extend-agp#variant-api-artifacts-tasks). This might be more complex, as the `androidComponents` API is designed to be more stable to keep plugins compatible longer. Check our [Gradle Recipes](https://github.com/android/gradle-recipes/tree/agp-9.0) for examples. -- **Update third-party plugins:** - Some third-party plugins might still depend on interfaces or APIs that are - no longer exposed. Migrate to versions of those plugins which are compatible - with AGP 9.0. +- **Update third-party plugins:** Some third-party plugins might still depend on interfaces or APIs that are no longer exposed. Migrate to versions of those plugins which are compatible with AGP 9.0. -The switch to the new DSL interfaces prevents plugins and Gradle build scripts -using various deprecated APIs, including: +The switch to the new DSL interfaces prevents plugins and Gradle build scripts using various deprecated APIs, including: | Deprecated API in the `android` block | Function | Replacement | |---|---|---| @@ -90,73 +54,43 @@ using various deprecated APIs, including: | `generatePureSplits` | Generate configuration splits for instant apps. | The ability to ship configuration splits is now built in to Android app bundles. | | `aidlPackagedList` | AIDL files to package in the AAR to expose it as API for libraries and apps that depend on this library. | This is still exposed on [`LibraryExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/LibraryExtension) but not on the other extension types. | -If you update to AGP 9.0 and see the following error message, it means that -your project is still referencing some of the old types: +If you update to AGP 9.0 and see the following error message, it means that your project is still referencing some of the old types: java.lang.ClassCastException: class com.android.build.gradle.internal.dsl.ApplicationExtensionImpl$AgpDecorated_Decorated cannot be cast to class com.android.build.gradle.BaseExtension -If you are blocked by incompatible third-party plugins, you can opt out and -get back the old implementations for the DSL, as well as the old variant API. -While doing this, the new interfaces are also available, and you can still -update your own build logic to the new API. To opt out, include this line in -your `gradle.properties` file: +If you are blocked by incompatible third-party plugins, you can opt out and get back the old implementations for the DSL, as well as the old variant API. While doing this, the new interfaces are also available, and you can still update your own build logic to the new API. To opt out, include this line in your `gradle.properties` file: android.newDsl=false -Alternatively, for a more gradual migration, AGP 9.4 lets you opt out individual -modules. To learn how, see [Variant API module opt-out](https://developer.android.com/build/releases/agp-9-4-0-release-notes#new-dsl-opt-out). +Alternatively, for a more gradual migration, AGP 9.4 lets you opt out individual modules. To learn how, see [Variant API module opt-out](https://developer.android.com/build/releases/agp-9-4-0-release-notes#new-dsl-opt-out). -The previous classes are marked as deprecated in AGP 9.0. This means projects -that opt out of the `newDsl` flag will see deprecation warnings, including on -the `android` block itself. +The previous classes are marked as deprecated in AGP 9.0. This means projects that opt out of the `newDsl` flag will see deprecation warnings, including on the `android` block itself. > [!CAUTION] > **Caution:** The ability to opt-out will be removed in AGP 10.0 (mid-2026). -You can also start upgrading to the new APIs before upgrading to AGP 9.0. The -new interfaces have been present for many AGP versions and so you can have a mix -of new and old. The [AGP API reference docs](https://developer.android.com/reference/tools/gradle-api) show the API -surface for each AGP version, and when each class, method and field was -added. +You can also start upgrading to the new APIs before upgrading to AGP 9.0. The new interfaces have been present for many AGP versions and so you can have a mix of new and old. The [AGP API reference docs](https://developer.android.com/reference/tools/gradle-api) show the API surface for each AGP version, and when each class, method and field was added. -We're reaching out to the authors of commonly used plugins to help them adapt -and release plugins that are fully compatible with the new modes, and will -continue to enhance the AGP Upgrade Assistant in Android Studio to guide you -through the migration. +We're reaching out to the authors of commonly used plugins to help them adapt and release plugins that are fully compatible with the new modes, and will continue to enhance the AGP Upgrade Assistant in Android Studio to guide you through the migration. -If you find that the new DSL or Variant API are missing capabilities or -features, please file an [issue](https://issuetracker.google.com/issues/new?component=192708&template=840533) as soon as possible. +If you find that the new DSL or Variant API are missing capabilities or features, please file an [issue](https://issuetracker.google.com/issues/new?component=192708&template=840533) as soon as possible. ## Built-in Kotlin -Android Gradle plugin 9.0 introduces built-in Kotlin support and enables it -by default. That means you no longer have to apply the -`org.jetbrains.kotlin.android` (or `kotlin-android`) plugin in your build files -to compile Kotlin source files. -This simplifies the Kotlin integration with AGP, avoids the use of -deprecated APIs, and improves performance in some cases. +Android Gradle plugin 9.0 introduces built-in Kotlin support and enables it by default. That means you no longer have to apply the `org.jetbrains.kotlin.android` (or `kotlin-android`) plugin in your build files to compile Kotlin source files. This simplifies the Kotlin integration with AGP, avoids the use of deprecated APIs, and improves performance in some cases. -Therefore, when you upgrade your project to AGP 9.0, you need to also -[migrate to built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin) or [opt out](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin). +Therefore, when you upgrade your project to AGP 9.0, you need to also [migrate to built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin) or [opt out](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin). -You can also [selectively disable built-in Kotlin support](https://developer.android.com/build/migrate-to-built-in-kotlin#selectively-disable) for Gradle -subprojects that don't have Kotlin sources. +You can also [selectively disable built-in Kotlin support](https://developer.android.com/build/migrate-to-built-in-kotlin#selectively-disable) for Gradle subprojects that don't have Kotlin sources. ## Runtime dependency on Kotlin Gradle plugin -To provide [built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin) support, Android Gradle plugin 9.0 now has a -runtime dependency on Kotlin Gradle plugin (KGP) 2.2.10. -That means you no longer have to declare a KGP version, and if you use a KGP -version lower than 2.2.10, Gradle will automatically upgrade your KGP version to -2.2.10. -Likewise, if you use a KSP version lower than 2.2.10-2.0.2, AGP will upgrade it -to 2.2.10-2.0.2 to match the KGP version. +To provide [built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin) support, Android Gradle plugin 9.0 now has a runtime dependency on Kotlin Gradle plugin (KGP) 2.2.10. That means you no longer have to declare a KGP version, and if you use a KGP version lower than 2.2.10, Gradle will automatically upgrade your KGP version to 2.2.10. Likewise, if you use a KSP version lower than 2.2.10-2.0.2, AGP will upgrade it to 2.2.10-2.0.2 to match the KGP version. ### Upgrade to a higher KGP version -To use a higher version of KGP or KSP, add the following to your top-level build -file: +To use a higher version of KGP or KSP, add the following to your top-level build file: buildscript { dependencies { @@ -170,13 +104,9 @@ file: ### Downgrade to a lower KGP version -You can only downgrade the KGP version if you've -[opted out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin). -This is because AGP 9.0 enables built-in Kotlin by default, and built-in Kotlin -requires KGP 2.2.10 or higher. +You can only downgrade the KGP version if you've [opted out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin). This is because AGP 9.0 enables built-in Kotlin by default, and built-in Kotlin requires KGP 2.2.10 or higher. -To use a lower version of KGP or KSP, declare that version in your top-level -build file using a [strict version](https://docs.gradle.org/current/userguide/dependency_versions.html#sec:strict-version) declaration: +To use a lower version of KGP or KSP, declare that version in your top-level build file using a [strict version](https://docs.gradle.org/current/userguide/dependency_versions.html#sec:strict-version) declaration: buildscript { dependencies { @@ -199,17 +129,13 @@ Note that the minimum KGP version you can downgrade to is 2.0.0. ## IDE support for test fixtures -AGP 9.0 brings full Android Studio IDE support for -[test fixtures](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/TestFixtures). +AGP 9.0 brings full Android Studio IDE support for [test fixtures](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/TestFixtures). ## Fused Library Plugin -The Fused Library Plugin (Preview) lets you publish multiple -libraries as a single Android Library AAR. This can make it easier for your -users to depend on your published artifacts. +The Fused Library Plugin (Preview) lets you publish multiple libraries as a single Android Library AAR. This can make it easier for your users to depend on your published artifacts. -For information about getting started, see -[Publish multiple Android libraries as one with Fused Library](https://developer.android.com/build/publish-library/fused-library). +For information about getting started, see [Publish multiple Android libraries as one with Fused Library](https://developer.android.com/build/publish-library/fused-library). ## Behavior changes @@ -220,8 +146,7 @@ Android Gradle plugin 9.0 has the following new behaviors: | Android Gradle plugin 9.0 uses NDK version `r28c` by default. | Consider specifying the NDK version you want to use explicitly. | | Android Gradle plugin 9.0 by default requires consumers of a library to use the same or higher compile SDK version. | Use the same or higher compile SDK when consuming a library. If this is not possible, or you want to give consumers of a library you publish more time to switch, set [`AarMetadata.minCompileSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/AarMetadata#minCompileSdk()) explicitly. | -AGP 9.0 includes updates to the following Gradle properties' defaults. -This gives you the choice to preserve the AGP 8.13 behavior when upgrading: +AGP 9.0 includes updates to the following Gradle properties' defaults. This gives you the choice to preserve the AGP 8.13 behavior when upgrading: | Property | Function | Change from AGP 8.13 to AGP 9.0 | Recommendation | |---|---|---|---| @@ -236,7 +161,7 @@ This gives you the choice to preserve the AGP 8.13 behavior when upgrading: | `android.onlyEnableUnitTestForTheTestedBuildType` | Only creates unit test components for the tested build type. In the default project this results in a single unit test for debug, where the previous behavor was to have unit tests run for debug or release. | `false` → `true` | If your project doesn't require tests to run for both debug and release, no change is required. | | `android.proguard.failOnMissingFiles` | Fails the build with an error if any of the keep files specified in the AGP DSL don't exist on disk. Before this change typos in filenames would result in files being silently ignored. | `false` → `true` | Remove any invalid proguard files declarations | | `android.r8.optimizedResourceShrinking` | Allows R8 to keep fewer Android resources by considering classes and Android resources together. | `false` → `true` | If your project's keep rules are already complete, no change is required. | -| `android.r8.strictFullModeForKeepRules` | Allows R8 to keep less by not implicitly keeping the default constructor when a class is kept. That is, `-keep class A` no longer implies `-keep class A { (); }` | `false` → `true` | If your project's keep rules are already complete, no change is required.
Replace `-keep class A` with `-keep class A { (); }` in your project's keep rules for any cases where you need the default constructor to be kept. | +| `android.r8.strictFullModeForKeepRules` | Allows R8 to keep less by not implicitly keeping the default constructor when a class is kept. That is, `-keep class A` no longer implies `-keep class A { (); }` | `false` → `true` | If your project's keep rules are already complete, no change is required. Replace `-keep class A` with `-keep class A { (); }` in your project's keep rules for any cases where you need the default constructor to be kept. | | `android.defaults.buildfeatures.resvalues` | Enables [`resValues`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasAndroidResources#resValues()) in all subprojects | `true` → `false` | Enable `resValues` in only the subprojects that need it by setting the following in those projects' Gradle build files: ``` android { buildFeatures { resValues = true } } ``` | | `android.defaults.buildfeatures.shaders` | Enables [shader compilation](https://developer.android.com/ndk/guides/graphics/shader-compilers) in all subprojects | `true` → `false` | Enable shader compilation in only the subprojects that contain shaders to be compiled by setting the following in those projects' Gradle build files: ``` android { buildFeatures { shaders = true } } ``` | | `android.r8.proguardAndroidTxt.disallowed` | In AGP 9.0, `getDefaultProguardFile()` will only support `proguard-android-optimize.txt` rather than `proguard-android.txt`. This is to prevent accidental usage of the `­dontoptimize` flag, which is included in `proguard-android.txt`. | `false` → `true` | You can explicitly specify `­dontoptimize` in a custom proguardFile if you want to avoid optimization, alongside using `proguard-android-optimize.txt`. Make sure to remove the `­dontoptimize` flag from this file if possible, as it reduces R8 optimization benefits. If not, opt out by setting `android.r8.globalOptionsInConsumerRules.disallowed=false`. | @@ -260,16 +185,9 @@ Android Gradle plugin 9.0 has the following breaking DSL changes: - The parameterization of [`CommonExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/CommonExtension) has been removed. - In itself, this is only a source-level breaking change to help - avoid future source-level breaking changes, but it also means that - the block methods need to move from [`CommonExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/CommonExtension) to - [`ApplicationExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/ApplicationExtension), [`LibraryExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/LibraryExtension), - [`DynamicFeatureExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/DynamicFeatureExtension) and [`TestExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/TestExtension). + In itself, this is only a source-level breaking change to help avoid future source-level breaking changes, but it also means that the block methods need to move from [`CommonExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/CommonExtension) to [`ApplicationExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/ApplicationExtension), [`LibraryExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/LibraryExtension), [`DynamicFeatureExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/DynamicFeatureExtension) and [`TestExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/TestExtension). - When upgrading your project to AGP 9.0, refactor Gradle plugin code - which uses those parameters or the block methods. For example the following - plugin is updated to remove the type parameter and not rely on the - removed block methods: + When upgrading your project to AGP 9.0, refactor Gradle plugin code which uses those parameters or the block methods. For example the following plugin is updated to remove the type parameter and not rely on the removed block methods: **AGP 8.13** @@ -295,8 +213,7 @@ Android Gradle plugin 9.0 has the following breaking DSL changes: } } - For plugins which target a range of AGP versions, using the getter directly - is binary compatible with AGP versions lower than 9.0. + For plugins which target a range of AGP versions, using the getter directly is binary compatible with AGP versions lower than 9.0. ## Removed DSL @@ -304,50 +221,37 @@ Android Gradle plugin 9.0 removes: - [`AndroidSourceSet.jni`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/AndroidSourceSet#jni(kotlin.Function1)), because it was not functional. -- [`AndroidSourceSet.wearAppConfigurationName`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/AndroidSourceSet#wearAppConfigurationName()), as it relates to the - removed embedded Wear OS app support. +- [`AndroidSourceSet.wearAppConfigurationName`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/AndroidSourceSet#wearAppConfigurationName()), as it relates to the removed embedded Wear OS app support. - [`BuildType.isRenderscriptDebuggable`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/BuildType#isRenderscriptDebuggable()), because it was not functional. -- [`DependencyVariantSelection`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/DependencyVariantSelection). It is replaced By - [`DependencySelection`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/DependencySelection), which is exposed as - [`kotlin.android.localDependencySelection`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/KotlinMultiplatformAndroidLibraryExtension#localDependencySelection(kotlin.Function1)) +- [`DependencyVariantSelection`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/DependencyVariantSelection). It is replaced By [`DependencySelection`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/DependencySelection), which is exposed as [`kotlin.android.localDependencySelection`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/KotlinMultiplatformAndroidLibraryExtension#localDependencySelection(kotlin.Function1)) -- [`Installation.installOptions(String)`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/Installation#installOptions(kotlin.String)). It is replaced by the - mutable property of [`Installation.installOptions`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/Installation#installOptions()). +- [`Installation.installOptions(String)`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/Installation#installOptions(kotlin.String)). It is replaced by the mutable property of [`Installation.installOptions`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/Installation#installOptions()). - The experimental, but never stabilized [`PostProcessing`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/PostProcessing) block. -- [`ProductFlavor.setDimension`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/ProductFlavor#setDimension(kotlin.String)), which is replaced by the - [`dimension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/ProductFlavor#dimension()) property +- [`ProductFlavor.setDimension`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/ProductFlavor#setDimension(kotlin.String)), which is replaced by the [`dimension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/ProductFlavor#dimension()) property -- `LanguageSplitOptions`, which was only useful for - [Google Play Instant](https://developer.android.com/topic/google-play-instant), which is deprecated. +- `LanguageSplitOptions`, which was only useful for [Google Play Instant](https://developer.android.com/topic/google-play-instant), which is deprecated. -- [`DensitySplit`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/DensitySplit), because the feature is no longer supported. - Replacement is to use [App Bundles](https://developer.android.com/guide/app-bundle). +- [`DensitySplit`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/DensitySplit), because the feature is no longer supported. Replacement is to use [App Bundles](https://developer.android.com/guide/app-bundle). ## Removed APIs Android Gradle plugin 9.0 removes: -- [`AndroidComponentsExtension.finalizeDSl`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/AndroidComponentsExtension#finalizeDSl(org.gradle.api.Action)). It is replaced by - [`finalizeDsl`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DslLifecycle#finalizeDsl(kotlin.Function1)) +- [`AndroidComponentsExtension.finalizeDSl`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/AndroidComponentsExtension#finalizeDSl(org.gradle.api.Action)). It is replaced by [`finalizeDsl`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DslLifecycle#finalizeDsl(kotlin.Function1)) -- [`Component.transformClassesWith`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Component#transformClassesWith(java.lang.Class,com.android.build.api.instrumentation.InstrumentationScope,kotlin.Function1)). It is replaced by - [`Instrumentation.transformClassesWith`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/Instrumentation#transformClassesWith(java.lang.Class,com.android.build.api.instrumentation.InstrumentationScope,kotlin.Function1)) +- [`Component.transformClassesWith`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Component#transformClassesWith(java.lang.Class,com.android.build.api.instrumentation.InstrumentationScope,kotlin.Function1)). It is replaced by [`Instrumentation.transformClassesWith`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/Instrumentation#transformClassesWith(java.lang.Class,com.android.build.api.instrumentation.InstrumentationScope,kotlin.Function1)) -- [`Component.setAsmFramesComputationMode`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Component#setAsmFramesComputationMode(com.android.build.api.instrumentation.FramesComputationMode)). It is replaced by - [`Instrumentation.setAsmFramesComputationMode`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Instrumentation#setAsmFramesComputationMode(com.android.build.api.instrumentation.FramesComputationMode)) +- [`Component.setAsmFramesComputationMode`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Component#setAsmFramesComputationMode(com.android.build.api.instrumentation.FramesComputationMode)). It is replaced by [`Instrumentation.setAsmFramesComputationMode`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Instrumentation#setAsmFramesComputationMode(com.android.build.api.instrumentation.FramesComputationMode)) -- [`ComponentBuilder.enabled`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/ComponentBuilder#enabled()). It is replaced by - [`ComponentBuilder.enable`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/ComponentBuilder#enable()). +- [`ComponentBuilder.enabled`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/ComponentBuilder#enabled()). It is replaced by [`ComponentBuilder.enable`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/ComponentBuilder#enable()). -- [`DependenciesInfoBuilder.includedInApk`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/DependenciesInfoBuilder#includedInApk()). Is is replaced by - [`includeInApk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DependenciesInfoBuilder#includeInApk()) +- [`DependenciesInfoBuilder.includedInApk`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/DependenciesInfoBuilder#includedInApk()). Is is replaced by [`includeInApk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DependenciesInfoBuilder#includeInApk()) -- [`DependenciesInfoBuilder.includedInBundle`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/DependenciesInfoBuilder#includedInBundle()). Is is replaced by - [`includeInBundle`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DependenciesInfoBuilder#includeInBundle()) +- [`DependenciesInfoBuilder.includedInBundle`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/DependenciesInfoBuilder#includedInBundle()). Is is replaced by [`includeInBundle`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DependenciesInfoBuilder#includeInBundle()) - [`GeneratesApk.targetSdkVersion`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/GeneratesApk#targetSdkVersion()). Is is replaced by [`targetSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApk#targetSdk()) @@ -357,43 +261,25 @@ Android Gradle plugin 9.0 removes: - [`Variant.targetSdkVersion`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Variant#targetSdkVersion()). Is is replaced by [`targetSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/Variant#targetSdk()) -- [`Variant.unitTest`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Variant#unitTest()), as it was not applicable to the - [`com.android.test`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/gradle/TestPlugin) plugin. - `unitTest` is available on [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending - [`HasUnitTest`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTest). +- [`Variant.unitTest`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Variant#unitTest()), as it was not applicable to the [`com.android.test`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/gradle/TestPlugin) plugin. `unitTest` is available on [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending [`HasUnitTest`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTest). -- [`VariantBuilder.targetSdk`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#targetSdk()) and [`targetSdkPreview`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#targetSdkPreview()), - as they were not meaningful in libraries. Use - [`GeneratesApkBuilder.targetSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApkBuilder#targetSdk()) or - [`GeneratesApkBuilder.targetSdkPreview`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApkBuilder#targetSdkPreview()) - instead. +- [`VariantBuilder.targetSdk`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#targetSdk()) and [`targetSdkPreview`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#targetSdkPreview()), as they were not meaningful in libraries. Use [`GeneratesApkBuilder.targetSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApkBuilder#targetSdk()) or [`GeneratesApkBuilder.targetSdkPreview`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApkBuilder#targetSdkPreview()) instead. -- [`VariantBuilder.enableUnitTest`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#enableUnitTest()), as it was not applicable to the - [`com.android.test`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/gradle/TestPlugin) plugin. - `enableUnitTest` is available on [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending - [`HasUnitTestBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder). +- [`VariantBuilder.enableUnitTest`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#enableUnitTest()), as it was not applicable to the [`com.android.test`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/gradle/TestPlugin) plugin. `enableUnitTest` is available on [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending [`HasUnitTestBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder). -- [`VariantBuilder.unitTestEnabled`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#unitTestEnabled()) is removed in favor of the more - consistently - named [`enableUnitTest`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder#enableUnitTest()) on the [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes - extending [`HasUnitTestBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder). +- [`VariantBuilder.unitTestEnabled`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#unitTestEnabled()) is removed in favor of the more consistently named [`enableUnitTest`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder#enableUnitTest()) on the [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending [`HasUnitTestBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder). - [`VariantOutput.enable`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantOutput#enable()). Is is replaced by [`enabled`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantOutput#enabled()) - The deprecated and disabled `FeaturePlugin` and `FeatureExtension`. -- The deprecated and disabled `BaseExtension.registerTransform` APIs, which - only remained to allow compiling against the latest AGP version while - targeting running on AGP 4.2 or lower. +- The deprecated and disabled `BaseExtension.registerTransform` APIs, which only remained to allow compiling against the latest AGP version while targeting running on AGP 4.2 or lower. ## Removed Gradle properties -The following Gradle properties were initially added as ways to globally -disable features that were enabled by default. +The following Gradle properties were initially added as ways to globally disable features that were enabled by default. -These features have been disabled by default since AGP 8.0 or lower. Enable -these features in only the sub-projects that use them for a more efficient -build. +These features have been disabled by default since AGP 8.0 or lower. Enable these features in only the sub-projects that use them for a more efficient build. | Property | Function | Replacement | |---|---|---| @@ -404,8 +290,7 @@ build. AGP 9.0 throws an error if you set the following Gradle properties. -The [Android Gradle plugin Upgrade Assistant](https://developer.android.com/build/agp-upgrade-assistant) won't upgrade projects to -AGP 9.0 that use these properties. +The [Android Gradle plugin Upgrade Assistant](https://developer.android.com/build/agp-upgrade-assistant) won't upgrade projects to AGP 9.0 that use these properties. | Property | Function | |---|---| @@ -418,11 +303,7 @@ The following R8 changes are included in AGP 9.0.0. ### New configuration option `-processkotlinnullchecks` -We've added the new R8 option `-processkotlinnullchecks` to configure R8 for -processing Kotlin null checks. The option takes a mandatory argument that must -be one of the following three values: `keep`, `remove_message` and `remove`. -The option processes the following null checks added by the Kotlin -compiler: +We've added the new R8 option `-processkotlinnullchecks` to configure R8 for processing Kotlin null checks. The option takes a mandatory argument that must be one of the following three values: `keep`, `remove_message` and `remove`. The option processes the following null checks added by the Kotlin compiler: class kotlin.jvm.internal.Intrinsics { void checkNotNull(java.lang.Object); @@ -442,118 +323,73 @@ compiler: void checkNotNullParameter(java.lang.Object, java.lang.String); } -The option values, ordered from the weakest to the strongest, have the -following effect: +The option values, ordered from the weakest to the strongest, have the following effect: - `keep` doesn't change the checks. - `remove_message` rewrites each check method call to a call to `getClass()` on the first argument of the call (effectively keeping the null check, but without any message). - `remove` completely removes the checks. -By default R8 -uses `remove_message`. Any specification of `-processkotlinnullchecks` -will override that. If specified multiple times the strongest value is -used. +By default R8 uses `remove_message`. Any specification of `-processkotlinnullchecks` will override that. If specified multiple times the strongest value is used. ### Stop propagating keep info to companion methods -When keep rules match interface methods that are subject to desugaring, -R8 previously internally transferred the *disallow optimization* and *disallow -shrinking* bits to the synthesized companion methods. +When keep rules match interface methods that are subject to desugaring, R8 previously internally transferred the *disallow optimization* and *disallow shrinking* bits to the synthesized companion methods. -Starting with AGP 9.0, keep rules no longer apply to -companion methods. This is consistent with the fact that keep rules are -not applicable to other compiler synthesized fields/methods/classes. +Starting with AGP 9.0, keep rules no longer apply to companion methods. This is consistent with the fact that keep rules are not applicable to other compiler synthesized fields/methods/classes. -By transferring the *disallow optimization* and *disallow shrinking* bits to -the companion methods, the following use case was previously supported: +By transferring the *disallow optimization* and *disallow shrinking* bits to the companion methods, the following use case was previously supported: 1. Compile a library with `default`/`static`/`private` interface methods to DEX with `minSdk` \< 24 and rules that keep the interface methods. 2. Compile an app with the library on classpath and `-applymapping`. 3. Merge the app and the library. -Note that this only works with `-applymapping` since the `disallow -obfuscation` bit is not transferred to the companion methods---that is, the -companion classes generated from step 1 would have obfuscated method -names. +Note that this only works with `-applymapping` since the `disallow obfuscation` bit is not transferred to the companion methods---that is, the companion classes generated from step 1 would have obfuscated method names. -Going forward this use case is no longer supported for `minSdk` \< -24. The workaround is to do the following: +Going forward this use case is no longer supported for `minSdk` \< 24. The workaround is to do the following: 1. Desugar the library with `default`/`static`/`private` interface methods to class files with `minSdk` \< 24. 2. Compile the desugared artifact using R8 and rules that keep the interface methods on the companion classes. 3. Compile the app with the library on classpath. 4. Merge the app and the desugared artifact. -Another side effect of this is that it is no longer possible to keep the -inner class and enclosing method attributes for anonymous and local classes -inside interface companion methods. +Another side effect of this is that it is no longer possible to keep the inner class and enclosing method attributes for anonymous and local classes inside interface companion methods. ### Change the default emitted source file to `r8-map-id-` This change is in AGP starting from 8.12.0. -The default emitted source file attribute for a class changes from -`SourceFile` to `r8-map-id-` when retracing is required (that is, -when either obfuscation or optimization is enabled). +The default emitted source file attribute for a class changes from `SourceFile` to `r8-map-id-` when retracing is required (that is, when either obfuscation or optimization is enabled). -Given an obfuscated stack trace, the new source file attribute makes it -possible to extract the ID of the mapping file that is required for -retracing, which can be used to support -[automated retracing of stack traces in Logcat](https://developer.android.com/studio/preview/features#logcat-retrace). +Given an obfuscated stack trace, the new source file attribute makes it possible to extract the ID of the mapping file that is required for retracing, which can be used to support [automated retracing of stack traces in Logcat](https://developer.android.com/studio/preview/features#logcat-retrace). -If a custom source file attribute is used (`-renamesourcefileattribute`) -this custom source file attribute continues to take precedence. +If a custom source file attribute is used (`-renamesourcefileattribute`) this custom source file attribute continues to take precedence. -In ProGuard compatibility mode (when `gradle.properties` contains -`android.enableR8.fullMode=false`), emitting a source file attribute of -`r8-map-id-` only takes effect if the `SourceFile` -attribute is *not* kept. Apps that use ProGuard compatibility mode and want -to include the mapping file ID in their stack traces should remove -`-keepattributes SourceFile` (or migrate to R8 full mode). +In ProGuard compatibility mode (when `gradle.properties` contains `android.enableR8.fullMode=false`), emitting a source file attribute of `r8-map-id-` only takes effect if the `SourceFile` attribute is *not* kept. Apps that use ProGuard compatibility mode and want to include the mapping file ID in their stack traces should remove `-keepattributes SourceFile` (or migrate to R8 full mode). -The map ID used in `r8-map-id-` is the full map hash, and not a 7 -character prefix of the map hash which was previously used. +The map ID used in `r8-map-id-` is the full map hash, and not a 7 character prefix of the map hash which was previously used. ### Enable use of minimized synthetic names in L8 desugaring -The name of synthetic classes generated by D8 normally contains the substring -`$$ExternalSynthetic` that tells you that this is a synthetic generated by D8. -Moreover, the name of the synthetic also encodes the synthetic kind (for -example, `Backport`, `Lambda`). This has a negative impact on the resulting DEX -size, since the class names take up more space in the string pool. +The name of synthetic classes generated by D8 normally contains the substring `$$ExternalSynthetic` that tells you that this is a synthetic generated by D8. Moreover, the name of the synthetic also encodes the synthetic kind (for example, `Backport`, `Lambda`). This has a negative impact on the resulting DEX size, since the class names take up more space in the string pool. -AGP 9.0 configures L8 (core library desugaring) so that the DEX -file containing all `j$` classes uses a new shortened class name format -for synthetic classes. The new class name uses a numeric ID (for example, `$1`). +AGP 9.0 configures L8 (core library desugaring) so that the DEX file containing all `j$` classes uses a new shortened class name format for synthetic classes. The new class name uses a numeric ID (for example, `$1`). ### Remove support for `-addconfigurationdebugging` -AGP 9.0 removes support for `-addconfigurationdebugging`. The compiler now -reports a warning if the flag is used. +AGP 9.0 removes support for `-addconfigurationdebugging`. The compiler now reports a warning if the flag is used. ### Remove support for generating L8 rules from D8/R8 -This change is only relevant for developers using the D8/R8 command line or -APIs directly. +This change is only relevant for developers using the D8/R8 command line or APIs directly. -R8 9.0 removes support for generating keep rules for L8 from D8 and R8. -You should instead use `TraceReferences` for this purpose. +R8 9.0 removes support for generating keep rules for L8 from D8 and R8. You should instead use `TraceReferences` for this purpose. -More specifically, the methods -`D8Command.builder.setDesugaredLibraryKeepRuleConsumer` and -`R8Command.Builder.setDesugaredLibraryKeepRuleConsumer` are removed, and the -support for `--desugared-lib-pg-conf-output` is removed from the command line -options of D8 and R8. +More specifically, the methods `D8Command.builder.setDesugaredLibraryKeepRuleConsumer` and `R8Command.Builder.setDesugaredLibraryKeepRuleConsumer` are removed, and the support for `--desugared-lib-pg-conf-output` is removed from the command line options of D8 and R8. ## Fixed issues ### Android Gradle plugin 9.0.0 -| Fixed Issues || -|---|---| -| **Android Gradle Plugin** | |---| | [Issue #171293712](https://issuetracker.google.com/issues/171293712) Feature Request: Inject ideal AGP version as a property | | [Issue #443976533](https://issuetracker.google.com/issues/443976533) Stabilize SingleArtifact.VERSION_CONTROL_INFO_FILE | | [Issue #223643506](https://issuetracker.google.com/issues/223643506) androidTest connectedCheck logcat output is broken | | [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets | | [Issue #460094802](https://issuetracker.google.com/issues/460094802) missingDimensionStrategy prefers a flavor maching its own name even from an unrelated dimension | | [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets | | [Issue #471410336](https://issuetracker.google.com/issues/471410336) AGP 9.0.0-rc01 doesn't resolve Kotlin libraries via kotlin() function | | [Issue #450851465](https://issuetracker.google.com/issues/450851465) Built-in-kotlin does not publish kotlin-stdlib dependency constraint in maven pom | | [Issue #420592288](https://issuetracker.google.com/issues/420592288) Add a test case for divergence between compileSdk and targetSdk | | [Issue #449153004](https://issuetracker.google.com/issues/449153004) empty resConfigs value leads to obscure aapt error | | [Issue #447375921](https://issuetracker.google.com/issues/447375921) Pure Java project have dependency on kotlin stdlib. | | [Issue #368600704](https://issuetracker.google.com/issues/368600704) Remove deprecated KotlinMultiplatformAndroidCompilationBuilder properties in AGP 9.0 | | [Issue #445209309](https://issuetracker.google.com/issues/445209309) \`com.android.tools.build:gradle:9.0.0-alpha05\` should have an api dependency on KGP and gradle-api | | [Issue #452645779](https://issuetracker.google.com/issues/452645779) Rename com.android.experimental.built-in-kotlin Gradle plugin | | [Issue #446220448](https://issuetracker.google.com/issues/446220448) AGP9: \`variant.sources.kotlin!!.addGeneratedSourceDirectory()\` is not working | | [Issue #448450771](https://issuetracker.google.com/issues/448450771) Aar metadata checks on compile Sdk uses the old DSL | | [Issue #441523448](https://issuetracker.google.com/issues/441523448) Remove deprecated \`com.android.build.api.dsl.ManagedDevices.devices\` property | | [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets | | [Issue #433758231](https://issuetracker.google.com/issues/433758231) Fail android library publishing if consumer keep file contains -dontobfuscate | | [Issue #241955408](https://issuetracker.google.com/issues/241955408) No Options to Print Mapping for Optimized Resources | | [Issue #436595826](https://issuetracker.google.com/issues/436595826) Make it an error to call finalizeDsl after this phase has been passed | | [Issue #457089670](https://issuetracker.google.com/issues/457089670) AGP initializes jetifier config even when jetifier is disabled | | [Issue #452246814](https://issuetracker.google.com/issues/452246814) built in kotlin does not add kotlinStdlib as a compile time dependency when \`kotlin.stdlib.default.dependency\` is true to module and pom files | | [Issue #442250902](https://issuetracker.google.com/issues/442250902) New optimizaation DSL does not create configuration.txt by default | | [Issue #443587266](https://issuetracker.google.com/issues/443587266) AGP 8.13.0 fails to verify nav graph in a module | | [Issue #444260628](https://issuetracker.google.com/issues/444260628) AGP uses deprecated Gradle API: multi-string notation | | [Issue #347732357](https://issuetracker.google.com/issues/347732357) Warn users trying to use legacy multidex library with minSdkVersion \>=21 | | [Issue #333831734](https://issuetracker.google.com/issues/333831734) A build fails if there are code generation tasks | | [Issue #446123111](https://issuetracker.google.com/issues/446123111) With \`android.builtInKotlin=false\` and \`android.newDsl=false\` and \`android.enableLegacyVariantApi=false\`, using \`kotlin-android\` plugin will fail with "API 'applicationVariants' is obsolete" | | [Issue #443037365](https://issuetracker.google.com/issues/443037365) Built-in Kotlin fails to resolve unversioned kotlin-stdlib when kotlin.stdlib.default.dependency=false | | [Issue #445967244](https://issuetracker.google.com/issues/445967244) DexData opens a file without closing, preventing cleanup | | [Issue #368609737](https://issuetracker.google.com/issues/368609737) AndroidSourceDirectorySet should stop extending PatternFilterable in AGP 9.0 | | [Issue #389707041](https://issuetracker.google.com/issues/389707041) Test Fixture Error in test only modules | | [Issue #353249347](https://issuetracker.google.com/issues/353249347) Incorrect error when using context receivers in test fixtures | | [Issue #351046197](https://issuetracker.google.com/issues/351046197) Incorrect IDE errors for Kotlin code in testFixtures | | [Issue #446889652](https://issuetracker.google.com/issues/446889652) \`legacy-kapt\` plugin skips annotation processing unlike \`kotlin-kapt\` | | [Issue #446492061](https://issuetracker.google.com/issues/446492061) compileSdkSpec.minorApiLevel is not working with SettingsExtension | | [Issue #429253579](https://issuetracker.google.com/issues/429253579) \[fused lib - public\] Generated fused library does not include sources | | [Issue #149770867](https://issuetracker.google.com/issues/149770867) extractNativeLibs and useEmbeddedDex should not be coming from the manifest | | [Issue #449114518](https://issuetracker.google.com/issues/449114518) Warnings from R8 in AGP 9.0.0-alpha09 | | [Issue #368426598](https://issuetracker.google.com/issues/368426598) Remove deprecated AndroidSourceSet.jni in AGP 9.0 | | [Issue #368484483](https://issuetracker.google.com/issues/368484483) Remove Installation.installOptions() in AGP 9.0 | | [Issue #368482484](https://issuetracker.google.com/issues/368482484) Remove BuildType.isRenderscriptDebuggable in AGP 9.0. | | [Issue #428646179](https://issuetracker.google.com/issues/428646179) Remove android.defaults.buildfeatures.renderscript | | [Issue #436887358](https://issuetracker.google.com/issues/436887358) \`com.android.kotlin.multiplatform.library\` crashes with Gradle Managed Devices | | [Issue #428645763](https://issuetracker.google.com/issues/428645763) Remove \`android.defaults.buildfeatures.aidl\` defaults gradle.properties flags | | [Issue #294183018](https://issuetracker.google.com/issues/294183018) Fail build when proguard file does not exist | | [Issue #254305041](https://issuetracker.google.com/issues/254305041) remove buildconfig defaults gradle.properties flags | | [Issue #280674230](https://issuetracker.google.com/issues/280674230) Change the app's targetSdk default value to be based on compileSdk instead of minSdk | | [Issue #436878535](https://issuetracker.google.com/issues/436878535) When \`isIncludeAndroidResources\` is enabled, \`process{Variant}UnitTestManifest\` fails to merge tools:overrideLibrary usages in AGP 8.12.0 | | [Issue #411739086](https://issuetracker.google.com/issues/411739086) AGP causing deprecation warnings in Gradle for JVM test tasks | | [Issue #235457021](https://issuetracker.google.com/issues/235457021) DependencyReportTask is incompatible with the configuration cache | | [Issue #369246556](https://issuetracker.google.com/issues/369246556) Switch default source/target Java version from Java 8 to Java 11 in AGP 9.0 | | [Issue #258855275](https://issuetracker.google.com/issues/258855275) Flip android.useAndroidX default to true | | [Issue #442763200](https://issuetracker.google.com/issues/442763200) Better exception when applying kapt plugin with built-in Kotlin. | | [Issue #441679226](https://issuetracker.google.com/issues/441679226) android.proguard.failOnMissingFiles is not working for consumerProguardFiles | | [Issue #443051391](https://issuetracker.google.com/issues/443051391) Update Kotlin Gradle plugin dependency to 2.2.10 | | [Issue #429981132](https://issuetracker.google.com/issues/429981132) Create KotlinJvmAndroidCompilation using KGP API | | [Issue #442869731](https://issuetracker.google.com/issues/442869731) Kotlin explicit API mode applied to test sources | | -| **Lint** | |---| | [Issue #430991549](https://issuetracker.google.com/issues/430991549) AGP 8.11.0: lintAnalyzeRelease task crashes when applying .gradle.kts files with apply(from = "...") | | [Issue #441536820](https://issuetracker.google.com/issues/441536820) Lint ChecksSdkIntAtLeast Check does not check if the annotated value is correct | | [Issue #446696613](https://issuetracker.google.com/issues/446696613) Built-in Kotlin does not add .kotlin_module to META-INF | | [Issue #449031505](https://issuetracker.google.com/issues/449031505) Lint classpath contains duplicate classes at different versions | | [Issue #448148350](https://issuetracker.google.com/issues/448148350) Overriding private resources workaround not working (tools:override = "true") | | [Issue #405676712](https://issuetracker.google.com/issues/405676712) Bug: removal of unused resources doesn't also remove the translations of them, and doesn't ask about it either | | [Issue #440415636](https://issuetracker.google.com/issues/440415636) Lint throwing warning "Could not clean up K2 caches" | | [Issue #440415636](https://issuetracker.google.com/issues/440415636) Lint throwing warning "Could not clean up K2 caches" | | -| **Lint Integration** | |---| | [Issue #460068798](https://issuetracker.google.com/issues/460068798) AndroidLintAnalysisTask cache misses across different JDK vendors or minor versions due to systemPropertyInputs.javaVersion differences | | [Issue #444447002](https://issuetracker.google.com/issues/444447002) Lint automatically uses latest installed SDK despite compileSdk, doesn't register as task input and breaks caching | | -| **Shrinker (R8)** | |---| | [Issue #454927488](https://issuetracker.google.com/issues/454927488) R8 optimized resource shrinking silently fails if using final resource IDs | | +Fixed Issues **Android Gradle Plugin** [Issue #171293712](https://issuetracker.google.com/issues/171293712) Feature Request: Inject ideal AGP version as a property [Issue #443976533](https://issuetracker.google.com/issues/443976533) Stabilize SingleArtifact.VERSION_CONTROL_INFO_FILE [Issue #223643506](https://issuetracker.google.com/issues/223643506) androidTest connectedCheck logcat output is broken [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets [Issue #460094802](https://issuetracker.google.com/issues/460094802) missingDimensionStrategy prefers a flavor maching its own name even from an unrelated dimension [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets [Issue #471410336](https://issuetracker.google.com/issues/471410336) AGP 9.0.0-rc01 doesn't resolve Kotlin libraries via kotlin() function [Issue #450851465](https://issuetracker.google.com/issues/450851465) Built-in-kotlin does not publish kotlin-stdlib dependency constraint in maven pom [Issue #420592288](https://issuetracker.google.com/issues/420592288) Add a test case for divergence between compileSdk and targetSdk [Issue #449153004](https://issuetracker.google.com/issues/449153004) empty resConfigs value leads to obscure aapt error [Issue #447375921](https://issuetracker.google.com/issues/447375921) Pure Java project have dependency on kotlin stdlib. [Issue #368600704](https://issuetracker.google.com/issues/368600704) Remove deprecated KotlinMultiplatformAndroidCompilationBuilder properties in AGP 9.0 [Issue #445209309](https://issuetracker.google.com/issues/445209309) \`com.android.tools.build:gradle:9.0.0-alpha05\` should have an api dependency on KGP and gradle-api [Issue #452645779](https://issuetracker.google.com/issues/452645779) Rename com.android.experimental.built-in-kotlin Gradle plugin [Issue #446220448](https://issuetracker.google.com/issues/446220448) AGP9: \`variant.sources.kotlin!!.addGeneratedSourceDirectory()\` is not working [Issue #448450771](https://issuetracker.google.com/issues/448450771) Aar metadata checks on compile Sdk uses the old DSL [Issue #441523448](https://issuetracker.google.com/issues/441523448) Remove deprecated \`com.android.build.api.dsl.ManagedDevices.devices\` property [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets [Issue #433758231](https://issuetracker.google.com/issues/433758231) Fail android library publishing if consumer keep file contains -dontobfuscate [Issue #241955408](https://issuetracker.google.com/issues/241955408) No Options to Print Mapping for Optimized Resources [Issue #436595826](https://issuetracker.google.com/issues/436595826) Make it an error to call finalizeDsl after this phase has been passed [Issue #457089670](https://issuetracker.google.com/issues/457089670) AGP initializes jetifier config even when jetifier is disabled [Issue #452246814](https://issuetracker.google.com/issues/452246814) built in kotlin does not add kotlinStdlib as a compile time dependency when \`kotlin.stdlib.default.dependency\` is true to module and pom files [Issue #442250902](https://issuetracker.google.com/issues/442250902) New optimizaation DSL does not create configuration.txt by default [Issue #443587266](https://issuetracker.google.com/issues/443587266) AGP 8.13.0 fails to verify nav graph in a module [Issue #444260628](https://issuetracker.google.com/issues/444260628) AGP uses deprecated Gradle API: multi-string notation [Issue #347732357](https://issuetracker.google.com/issues/347732357) Warn users trying to use legacy multidex library with minSdkVersion \>=21 [Issue #333831734](https://issuetracker.google.com/issues/333831734) A build fails if there are code generation tasks [Issue #446123111](https://issuetracker.google.com/issues/446123111) With \`android.builtInKotlin=false\` and \`android.newDsl=false\` and \`android.enableLegacyVariantApi=false\`, using \`kotlin-android\` plugin will fail with "API 'applicationVariants' is obsolete" [Issue #443037365](https://issuetracker.google.com/issues/443037365) Built-in Kotlin fails to resolve unversioned kotlin-stdlib when kotlin.stdlib.default.dependency=false [Issue #445967244](https://issuetracker.google.com/issues/445967244) DexData opens a file without closing, preventing cleanup [Issue #368609737](https://issuetracker.google.com/issues/368609737) AndroidSourceDirectorySet should stop extending PatternFilterable in AGP 9.0 [Issue #389707041](https://issuetracker.google.com/issues/389707041) Test Fixture Error in test only modules [Issue #353249347](https://issuetracker.google.com/issues/353249347) Incorrect error when using context receivers in test fixtures [Issue #351046197](https://issuetracker.google.com/issues/351046197) Incorrect IDE errors for Kotlin code in testFixtures [Issue #446889652](https://issuetracker.google.com/issues/446889652) \`legacy-kapt\` plugin skips annotation processing unlike \`kotlin-kapt\` [Issue #446492061](https://issuetracker.google.com/issues/446492061) compileSdkSpec.minorApiLevel is not working with SettingsExtension [Issue #429253579](https://issuetracker.google.com/issues/429253579) \[fused lib - public\] Generated fused library does not include sources [Issue #149770867](https://issuetracker.google.com/issues/149770867) extractNativeLibs and useEmbeddedDex should not be coming from the manifest [Issue #449114518](https://issuetracker.google.com/issues/449114518) Warnings from R8 in AGP 9.0.0-alpha09 [Issue #368426598](https://issuetracker.google.com/issues/368426598) Remove deprecated AndroidSourceSet.jni in AGP 9.0 [Issue #368484483](https://issuetracker.google.com/issues/368484483) Remove Installation.installOptions() in AGP 9.0 [Issue #368482484](https://issuetracker.google.com/issues/368482484) Remove BuildType.isRenderscriptDebuggable in AGP 9.0. [Issue #428646179](https://issuetracker.google.com/issues/428646179) Remove android.defaults.buildfeatures.renderscript [Issue #436887358](https://issuetracker.google.com/issues/436887358) \`com.android.kotlin.multiplatform.library\` crashes with Gradle Managed Devices [Issue #428645763](https://issuetracker.google.com/issues/428645763) Remove \`android.defaults.buildfeatures.aidl\` defaults gradle.properties flags [Issue #294183018](https://issuetracker.google.com/issues/294183018) Fail build when proguard file does not exist [Issue #254305041](https://issuetracker.google.com/issues/254305041) remove buildconfig defaults gradle.properties flags [Issue #280674230](https://issuetracker.google.com/issues/280674230) Change the app's targetSdk default value to be based on compileSdk instead of minSdk [Issue #436878535](https://issuetracker.google.com/issues/436878535) When \`isIncludeAndroidResources\` is enabled, \`process{Variant}UnitTestManifest\` fails to merge tools:overrideLibrary usages in AGP 8.12.0 [Issue #411739086](https://issuetracker.google.com/issues/411739086) AGP causing deprecation warnings in Gradle for JVM test tasks [Issue #235457021](https://issuetracker.google.com/issues/235457021) DependencyReportTask is incompatible with the configuration cache [Issue #369246556](https://issuetracker.google.com/issues/369246556) Switch default source/target Java version from Java 8 to Java 11 in AGP 9.0 [Issue #258855275](https://issuetracker.google.com/issues/258855275) Flip android.useAndroidX default to true [Issue #442763200](https://issuetracker.google.com/issues/442763200) Better exception when applying kapt plugin with built-in Kotlin. [Issue #441679226](https://issuetracker.google.com/issues/441679226) android.proguard.failOnMissingFiles is not working for consumerProguardFiles [Issue #443051391](https://issuetracker.google.com/issues/443051391) Update Kotlin Gradle plugin dependency to 2.2.10 [Issue #429981132](https://issuetracker.google.com/issues/429981132) Create KotlinJvmAndroidCompilation using KGP API [Issue #442869731](https://issuetracker.google.com/issues/442869731) Kotlin explicit API mode applied to test sources **Lint** [Issue #430991549](https://issuetracker.google.com/issues/430991549) AGP 8.11.0: lintAnalyzeRelease task crashes when applying .gradle.kts files with apply(from = "...") [Issue #441536820](https://issuetracker.google.com/issues/441536820) Lint ChecksSdkIntAtLeast Check does not check if the annotated value is correct [Issue #446696613](https://issuetracker.google.com/issues/446696613) Built-in Kotlin does not add .kotlin_module to META-INF [Issue #449031505](https://issuetracker.google.com/issues/449031505) Lint classpath contains duplicate classes at different versions [Issue #448148350](https://issuetracker.google.com/issues/448148350) Overriding private resources workaround not working (tools:override = "true") [Issue #405676712](https://issuetracker.google.com/issues/405676712) Bug: removal of unused resources doesn't also remove the translations of them, and doesn't ask about it either [Issue #440415636](https://issuetracker.google.com/issues/440415636) Lint throwing warning "Could not clean up K2 caches" [Issue #440415636](https://issuetracker.google.com/issues/440415636) Lint throwing warning "Could not clean up K2 caches" **Lint Integration** [Issue #460068798](https://issuetracker.google.com/issues/460068798) AndroidLintAnalysisTask cache misses across different JDK vendors or minor versions due to systemPropertyInputs.javaVersion differences [Issue #444447002](https://issuetracker.google.com/issues/444447002) Lint automatically uses latest installed SDK despite compileSdk, doesn't register as task input and breaks caching **Shrinker (R8)** [Issue #454927488](https://issuetracker.google.com/issues/454927488) R8 optimized resource shrinking silently fails if using final resource IDs
\ No newline at end of file diff --git a/build-system/agp/agp-9-upgrade/references/buildconfig.md b/build-system/agp/agp-9-upgrade/references/buildconfig.md index e4e19b6..773fcd8 100644 --- a/build-system/agp/agp-9-upgrade/references/buildconfig.md +++ b/build-system/agp/agp-9-upgrade/references/buildconfig.md @@ -1,5 +1,4 @@ -When an Android module contains custom BuildConfig fields, the following steps -are necessary to ensure a correct build. +When an Android module contains custom BuildConfig fields, the following steps are necessary to ensure a correct build. ### Step 1: Enable the buildConfig build feature @@ -37,11 +36,9 @@ In custom build-logic using `CommonExtension`: ### Step 2: Migrate to the new API -Use the **addCustomBuildConfigFields** recipe from the [gradle-recipes](https://developer.android.com/agents/skills/build-system/agp/agp-9-upgrade/references/recipes) -repository. +Use the **addCustomBuildConfigFields** recipe from the [gradle-recipes](https://developer.android.com/agents/skills/build-system/agp/agp-9-upgrade/references/recipes) repository. -**IMPORTANT:** For `BuildConfigField`s with a type of `String`, the `value` field -*must* include quotation marks as part of the String. For example: +**IMPORTANT:** For `BuildConfigField`s with a type of `String`, the `value` field *must* include quotation marks as part of the String. For example: BuildConfigField( type = "String", @@ -49,6 +46,4 @@ repository. comment = "Optional comment", ) -It is an **error** if the `value` field doesn't include quotation marks as -part of the String. For example, `value = "Some value"` **is an error** . This is -because the `value` is written out literally. \ No newline at end of file +It is an **error** if the `value` field doesn't include quotation marks as part of the String. For example, `value = "Some value"` **is an error** . This is because the `value` is written out literally. \ No newline at end of file diff --git a/build-system/agp/agp-9-upgrade/references/ksp-kapt.md b/build-system/agp/agp-9-upgrade/references/ksp-kapt.md index e8a5d33..2dacb96 100644 --- a/build-system/agp/agp-9-upgrade/references/ksp-kapt.md +++ b/build-system/agp/agp-9-upgrade/references/ksp-kapt.md @@ -1,39 +1,23 @@ -When migrating to built-in Kotlin, it is important to consider usage of `kapt` -and the `org.jetbrains.kotlin.kapt` (also known as the `kotlin("kapt")`) plugin. -The goal is to migrate as many `kapt` usages to `ksp` as possible. +When migrating to built-in Kotlin, it is important to consider usage of `kapt` and the `org.jetbrains.kotlin.kapt` (also known as the `kotlin("kapt")`) plugin. The goal is to migrate as many `kapt` usages to `ksp` as possible. Follow these steps when migrating `kapt`: ## 1. Remove all references to the `org.jetbrains.kotlin.kapt` plugin -The `org.jetbrains.kotlin.kapt` (also known as `kotlin("kapt")`) plugin is -incompatible with built-in Kotlin. Remove it when migrating to built-in Kotlin. +The `org.jetbrains.kotlin.kapt` (also known as `kotlin("kapt")`) plugin is incompatible with built-in Kotlin. Remove it when migrating to built-in Kotlin. ## 2. Check each usage of `kapt` -Check each usage of `kapt` to see if it is compatible with `ksp`. To check if a -dependency is compatible with `ksp`, inspect the dependency's jar. For it to be -compatible with `ksp`, the jar must have a file, -`services/com.google.devtools.ksp.processing.SymbolProcessorProvider`. If it -does not, it is **incompatible** with `ksp`. +Check each usage of `kapt` to see if it is compatible with `ksp`. To check if a dependency is compatible with `ksp`, inspect the dependency's jar. For it to be compatible with `ksp`, the jar must have a file, `services/com.google.devtools.ksp.processing.SymbolProcessorProvider`. If it does not, it is **incompatible** with `ksp`. -For example, the `androidx.room:room-compiler` library is compatible with KSP -since version 2.3.0-beta02. We can verify this by finding the jar file in the -Gradle caches directory, which is typically located at -`~/.gradle/caches/modules-2/files-2.1/` on Linux and Mac. In this specific case, -the `androidx.room:room-compiler` dependency is located at -`~/.gradle/caches/modules-2/files-2.1/androidx.room/room-compiler/`. +For example, the `androidx.room:room-compiler` library is compatible with KSP since version 2.3.0-beta02. We can verify this by finding the jar file in the Gradle caches directory, which is typically located at `~/.gradle/caches/modules-2/files-2.1/` on Linux and Mac. In this specific case, the `androidx.room:room-compiler` dependency is located at `~/.gradle/caches/modules-2/files-2.1/androidx.room/room-compiler/`. -More generally, you can find a dependency by looking in -`~/.gradle/caches/modules-2/files-2.1/group-name/artifact-name/`. +More generally, you can find a dependency by looking in `~/.gradle/caches/modules-2/files-2.1/group-name/artifact-name/`. ## 3. Migrate to KSP where possible -For each usage of `kapt` that is compatible with `ksp`, use `ksp`. The prior -step explains how to check compatibility. +For each usage of `kapt` that is compatible with `ksp`, use `ksp`. The prior step explains how to check compatibility. ## 4. Apply legacy-kapt -If a Gradle module has `kapt` dependencies that cannot be migrated to `ksp` -because they are incompatible (see step 2), then leave that dependency alone and -apply the `com.android.legacy-kapt` plugin. \ No newline at end of file +If a Gradle module has `kapt` dependencies that cannot be migrated to `ksp` because they are incompatible (see step 2), then leave that dependency alone and apply the `com.android.legacy-kapt` plugin. \ No newline at end of file diff --git a/build-system/agp/agp-9-upgrade/references/paparazzi-gradle-9.md b/build-system/agp/agp-9-upgrade/references/paparazzi-gradle-9.md index a20da2a..97a65bc 100644 --- a/build-system/agp/agp-9-upgrade/references/paparazzi-gradle-9.md +++ b/build-system/agp/agp-9-upgrade/references/paparazzi-gradle-9.md @@ -1,19 +1,10 @@ -If Paparazzi is used in the project, update it to version 2.0.0-alpha04 or -higher. +If Paparazzi is used in the project, update it to version 2.0.0-alpha04 or higher. -Paparazzi version 2.0.0-alpha04 and lower is not fully compatible with Gradle -9, and Gradle 9 is required by AGP 9. This means that, without workarounds, -projects that use Paparazzi v2.0.0-alpha04 and lower cannot migrate to AGP 9. +Paparazzi version 2.0.0-alpha04 and lower is not fully compatible with Gradle 9, and Gradle 9 is required by AGP 9. This means that, without workarounds, projects that use Paparazzi v2.0.0-alpha04 and lower cannot migrate to AGP 9. -At time of writing, there are no higher versions of Paparazzi. That is, -v2.0.0-alpha04 is the latest release. +At time of writing, there are no higher versions of Paparazzi. That is, v2.0.0-alpha04 is the latest release. -The issue is due to Paparazzi using internal classes from Gradle that tend to -move in breaking ways without warning. This specific issue is related to HTML -test reports. To work around it, disable those HTML test reports. Here -are two examples of how to do this, one for Kotlin DSL and the other for Groovy -DSL. Any module that has the paparazzi plugin (`app.cash.paparazzi`) applied -must apply one of these two workarounds. +The issue is due to Paparazzi using internal classes from Gradle that tend to move in breaking ways without warning. This specific issue is related to HTML test reports. To work around it, disable those HTML test reports. Here are two examples of how to do this, one for Kotlin DSL and the other for Groovy DSL. Any module that has the paparazzi plugin (`app.cash.paparazzi`) applied must apply one of these two workarounds. Kotlin DSL: diff --git a/build-system/agp/agp-9-upgrade/references/recipes.md b/build-system/agp/agp-9-upgrade/references/recipes.md index d3ecc74..a5d9856 100644 --- a/build-system/agp/agp-9-upgrade/references/recipes.md +++ b/build-system/agp/agp-9-upgrade/references/recipes.md @@ -1,6 +1,4 @@ -When migrating to AGP's new DSL, any Gradle code (plugins or logic in build -scripts) that relied on the old DSL will stop working. Such code must be -migrated. +When migrating to AGP's new DSL, any Gradle code (plugins or logic in build scripts) that relied on the old DSL will stop working. Such code must be migrated. ## Guidelines @@ -8,14 +6,9 @@ migrated. - **DO NOT** use AGP internals in migrated code. - **DO** use only public APIs in migrated code. -In some cases, there is a one-to-one replacement for the old code. Some examples -are in [the AGP 9.0.0 release notes](https://developer.android.com/build/releases/agp-9-0-0-release-notes). +In some cases, there is a one-to-one replacement for the old code. Some examples are in [the AGP 9.0.0 release notes](https://developer.android.com/build/releases/agp-9-0-0-release-notes). -In other cases, there is no direct one-to-one replacement. For these situations, -the [gradle-recipes repo](https://github.com/android/gradle-recipes) is a great resource. You can checkout one of its -AGP 9.x branches, such as `agp-9.0`, `agp-9.1`, or `agp-9.2`. These branches -contain recipes for common situations in Android projects. The following table -lists the compatibility for recipes for each version of AGP. +In other cases, there is no direct one-to-one replacement. For these situations, the [gradle-recipes repo](https://github.com/android/gradle-recipes) is a great resource. You can checkout one of its AGP 9.x branches, such as `agp-9.0`, `agp-9.1`, or `agp-9.2`. These branches contain recipes for common situations in Android projects. The following table lists the compatibility for recipes for each version of AGP. ## Compatibility table @@ -56,7 +49,4 @@ In the old DSL, an APK could be renamed very simply. Here's an example: } } -However, with AGP 9 and the new DSL, `applicationVariants` is no longer -available. You must instead react to artifact creation using the -`androidComponents.onVariants` API. A complete example of this is available in -the **gradle-recipes** repository in the `listenToArtifacts` recipe. \ No newline at end of file +However, with AGP 9 and the new DSL, `applicationVariants` is no longer available. You must instead react to artifact creation using the `androidComponents.onVariants` API. A complete example of this is available in the **gradle-recipes** repository in the `listenToArtifacts` recipe. \ No newline at end of file diff --git a/camera/camerax/SKILL.md b/camera/camerax/SKILL.md index 6ae6ca1..b9ec31a 100644 --- a/camera/camerax/SKILL.md +++ b/camera/camerax/SKILL.md @@ -7,7 +7,7 @@ description: Provide technical guidance for Android camera development with Came license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-07' + last-updated: '2026-08-06' keywords: - recipe - Android @@ -26,20 +26,17 @@ metadata: - ImageAnalysis. --- -This skill provides procedural guidance and standard patterns for building -camera applications on Android, with a focus on CameraX, including its -`Camera2Interop` utilities, and Media3 integrations. +This skill provides procedural guidance and standard patterns for building camera applications on Android, with a focus on CameraX, including its `Camera2Interop` utilities, and Media3 integrations. ## Core workflows ### Handling immutable API patterns -Various Android camera and media APIs, especially CameraX `VideoCapture`, use a -**fluent, immutable builder-like pattern** where methods return a new instance. -Failing to reassign these results in settings, such as audio, being ignored. +Various Android camera and media APIs, especially CameraX `VideoCapture`, use a **fluent, immutable builder-like pattern** where methods return a new instance. Failing to reassign these results in settings, such as audio, being ignored. **Pattern: Reassignment is required** +
```kotlin // WRONG @@ -62,6 +59,7 @@ run { pending = pending.withAudioEnabled() // Reassignment val active = pending.start(exec, listener) } + ```
@@ -77,9 +75,7 @@ When migrating legacy camera codebases to the CameraX Jetpack library: ### Comprehensive feature blueprinting -For multi-step features that involve multiple files and hardware-level wiring, -follow the [Structural Blueprinting](references/expert-blueprints.md) approach to avoid -system timeouts. Such complex features include: +For multi-step features that involve multiple files and hardware-level wiring, follow the [Structural Blueprinting](references/expert-blueprints.md) approach to avoid system timeouts. Such complex features include: - **Manual controls** : Break down into the `ViewModel` state, the controller layer, and the `Camera2Interop` wiring in the session. - **RAW capture**: Separate JPEG and RAW output configurations into discrete build steps. @@ -106,20 +102,16 @@ See [modern-apis](references/modern-apis.md) for current recommendations. ### Code quality and architectural rules -Adhere to the following Android ecosystem standard patterns when building your -camera implementations: +Adhere to the following Android ecosystem standard patterns when building your camera implementations: - **Testing, fakes over mocks** : Avoid mocking libraries like `Mockito`, especially for multi-step CameraX interfaces like `ImageProxy`. Build "Fakes" to verify state rather than unreliable implementation details. - **Google Truth assertions** : Use `assertThat` over standard `JUnit` assertions like `assertEquals` for improved readability. - **Explicit test runners** : Always define an explicit `@RunWith` for test classes to ensure the CI environment executes them correctly. -- **Semantic UI merging** : When building custom camera controls in Compose, such as a button with an `Icon` and `Text`, use `semantics { - mergeDescendants = true }` to ensure screen readers announce them as a single, coherent unit. +- **Semantic UI merging** : When building custom camera controls in Compose, such as a button with an `Icon` and `Text`, use `semantics { mergeDescendants = true }` to ensure screen readers announce them as a single, coherent unit. ## Hardware and device diversity -Camera apps run on a wide variety of hardware, from mobile phones and -foldables to tablets, laptops, and even smart appliances. Have consideration -for the specific hardware the app is running on. +Camera apps run on a wide variety of hardware, from mobile phones and foldables to tablets, laptops, and even smart appliances. Have consideration for the specific hardware the app is running on. - **Form factors**: Account for screen size and orientation changes on foldables and tablets. - **Multi-camera arrays**: Some devices have a rear-facing camera and a front-facing camera. Other devices have multiple rear-facing cameras, such as wide-angle and telephoto lenses. diff --git a/camera/camerax/references/camera1-to-camerax.md b/camera/camerax/references/camera1-to-camerax.md index 9c6e80e..03bfee5 100644 --- a/camera/camerax/references/camera1-to-camerax.md +++ b/camera/camerax/references/camera1-to-camerax.md @@ -7,9 +7,9 @@ ## Initialize `ProcessCameraProvider` -Request the `ProcessCameraProvider` and bind use cases to the Activity or -Fragment lifecycle. +Request the `ProcessCameraProvider` and bind use cases to the Activity or Fragment lifecycle. +
```kotlin val context = LocalContext.current @@ -36,6 +36,7 @@ LaunchedEffect(context, lifecycleOwner) { ) val cameraControl = camera.cameraControl } + ```
@@ -50,21 +51,25 @@ Use `androidx.camera.view.PreviewView`. 1. **Set up preview**: +
```kotlin preview.setSurfaceProvider(previewView.surfaceProvider) + ```
2. **Handle tap-to-focus**: +
```kotlin val factory = previewView.meteringPointFactory val point = factory.createPoint(x, y) // x, y from touch event val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF).build() cameraControl?.startFocusAndMetering(action) + ```
@@ -75,6 +80,7 @@ Use `androidx.camera.compose.CameraXViewfinder`. 1. **Set up preview and SurfaceRequest**: +
```kotlin var surfaceRequest by remember { mutableStateOf(null) } @@ -83,12 +89,14 @@ Use `androidx.camera.compose.CameraXViewfinder`. setSurfaceProvider { request -> surfaceRequest = request } } } + ```
2. **Render viewfinder**: +
```kotlin surfaceRequest?.let { request -> @@ -98,12 +106,14 @@ Use `androidx.camera.compose.CameraXViewfinder`. modifier = Modifier ) } + ```
3. **Handle tap-to-focus in Compose**: +
```kotlin // Inside your tap gesture handler... @@ -115,12 +125,14 @@ Use `androidx.camera.compose.CameraXViewfinder`. val point = factory.createPoint(surfaceCoords.x, surfaceCoords.y) val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF).build() cameraControl?.startFocusAndMetering(action) + ```
4. **Update target rotation for Compose**: +
```kotlin LaunchedEffect(configuration) { @@ -130,15 +142,16 @@ Use `androidx.camera.compose.CameraXViewfinder`. preview.targetRotation = rotation } } + ```
## Capture a photo -Use the `ImageCapture` use case to take the picture. The `ImageProxy` handles -rotation directly. +Use the `ImageCapture` use case to take the picture. The `ImageProxy` handles rotation directly. +
```kotlin imageCapture.takePicture( @@ -170,15 +183,16 @@ imageCapture.takePicture( } } ) + ```
## Switch cameras -To flip between front and rear cameras, change the `CameraSelector` and -retrigger the `ProcessCameraProvider` logic. +To flip between front and rear cameras, change the `CameraSelector` and retrigger the `ProcessCameraProvider` logic. +
```kotlin lensFacing = if (lensFacing == CameraSelector.LENS_FACING_BACK) { @@ -186,6 +200,7 @@ lensFacing = if (lensFacing == CameraSelector.LENS_FACING_BACK) { } else { CameraSelector.LENS_FACING_BACK } + ```
diff --git a/camera/camerax/references/camera2-to-camerax.md b/camera/camerax/references/camera2-to-camerax.md index 5b21f87..eee1510 100644 --- a/camera/camerax/references/camera2-to-camerax.md +++ b/camera/camerax/references/camera2-to-camerax.md @@ -1,10 +1,6 @@ -Camera2 offers granular control but introduces boilerplate: managing -`CameraDevice` states, `CameraCaptureSession` lifecycles, background threads, -`HandlerThread`, and manual orientation calculations. +Camera2 offers granular control but introduces boilerplate: managing `CameraDevice` states, `CameraCaptureSession` lifecycles, background threads, `HandlerThread`, and manual orientation calculations. -CameraX simplifies this by binding high-level `UseCase`s such as `Preview`, -`ImageCapture`, and `ImageAnalysis` directly to Android lifecycles, handling -thread management and device-specific workarounds automatically. +CameraX simplifies this by binding high-level `UseCase`s such as `Preview`, `ImageCapture`, and `ImageAnalysis` directly to Android lifecycles, handling thread management and device-specific workarounds automatically. *** ** * ** *** @@ -21,10 +17,9 @@ Migrating to CameraX removes manual setup code: ## Initialize `ProcessCameraProvider` -Request the `ProcessCameraProvider` and bind your use cases to the -`LifecycleOwner` activity or fragment. This replaces the -`CameraManager.openCamera` flow. +Request the `ProcessCameraProvider` and bind your use cases to the `LifecycleOwner` activity or fragment. This replaces the `CameraManager.openCamera` flow. +
```kotlin val context = LocalContext.current @@ -56,6 +51,7 @@ LaunchedEffect(context, lifecycleOwner) { imageAnalysis ) } + ```
@@ -64,17 +60,17 @@ LaunchedEffect(context, lifecycleOwner) { ## Implement the preview and tap-to-focus -CameraX handles surface configuration automatically. Choose based on your UI -toolkit: +CameraX handles surface configuration automatically. Choose based on your UI toolkit: ### Option A: For Android Views -Use `androidx.camera.view.PreviewView` in your layout, and bind it to the -`Preview` use case. +Use `androidx.camera.view.PreviewView` in your layout, and bind it to the `Preview` use case. +
```kotlin preview.setSurfaceProvider(previewView.surfaceProvider) + ```
@@ -83,6 +79,7 @@ preview.setSurfaceProvider(previewView.surfaceProvider) Use `androidx.camera.compose.CameraXViewfinder`. +
```kotlin var surfaceRequest by remember { mutableStateOf(null) } @@ -91,6 +88,7 @@ val preview = remember { setSurfaceProvider { request -> surfaceRequest = request } } } + ```
@@ -99,10 +97,9 @@ val preview = remember { ## Capture a photo -Replace `ImageReader` capture flows and -`CaptureRequest.Builder.TEMPLATE_STILL_CAPTURE` with the `ImageCapture` use -case. CameraX handles the rotation natively using the returned `ImageProxy`. +Replace `ImageReader` capture flows and `CaptureRequest.Builder.TEMPLATE_STILL_CAPTURE` with the `ImageCapture` use case. CameraX handles the rotation natively using the returned `ImageProxy`. +
```kotlin imageCapture.takePicture( @@ -134,6 +131,7 @@ imageCapture.takePicture( } } ) + ```
@@ -142,9 +140,9 @@ imageCapture.takePicture( ## Implement image analysis -If you were using `ImageReader` in Camera2 to access raw frames, e.g., for QR -scanning or ML,, replace it with the CameraX `ImageAnalysis` use case. +If you were using `ImageReader` in Camera2 to access raw frames, e.g., for QR scanning or ML,, replace it with the CameraX `ImageAnalysis` use case. +
```kotlin imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy -> @@ -157,6 +155,7 @@ imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy -> imageProxy.close() } } + ```
@@ -165,10 +164,9 @@ imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy -> ## Use Camera2 interop -If your app requires specific Camera2 configuration options, such as custom -exposure modes or flash settings, that aren't exposed directly in CameraX, -use `Camera2Interop` to apply them to your CameraX use cases. +If your app requires specific Camera2 configuration options, such as custom exposure modes or flash settings, that aren't exposed directly in CameraX, use `Camera2Interop` to apply them to your CameraX use cases. +
```kotlin // Use Camera2Interop to set Camera2-specific capture options @@ -180,6 +178,7 @@ extender.setCaptureRequestOption( CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH ) + ```
diff --git a/camera/camerax/references/expert-blueprints.md b/camera/camerax/references/expert-blueprints.md index e1f2f25..753347b 100644 --- a/camera/camerax/references/expert-blueprints.md +++ b/camera/camerax/references/expert-blueprints.md @@ -1,6 +1,4 @@ -Complex camera features often fail due to "Agent Stall" or timeouts when -attempted in a single turn. Use these blueprints to break tasks into manageable -phases. +Complex camera features often fail due to "Agent Stall" or timeouts when attempted in a single turn. Use these blueprints to break tasks into manageable phases. ## Manual controls @@ -54,5 +52,4 @@ phases. ## Low-light capture -For guidance on Night Mode Extensions and Low Light Boost, -[low-light.md](https://developer.android.com/agents/skills/camera/camerax/references/low-light). \ No newline at end of file +For guidance on Night Mode Extensions and Low Light Boost, [low-light.md](https://developer.android.com/agents/skills/camera/camerax/references/low-light). \ No newline at end of file diff --git a/camera/camerax/references/foldables.md b/camera/camerax/references/foldables.md index 22d378a..f0dd882 100644 --- a/camera/camerax/references/foldables.md +++ b/camera/camerax/references/foldables.md @@ -1,6 +1,4 @@ -Foldable devices introduce unique challenges for camera applications, including -dynamic layout changes, multiple display orientations, and physical device -postures, such as tabletop and book modes. +Foldable devices introduce unique challenges for camera applications, including dynamic layout changes, multiple display orientations, and physical device postures, such as tabletop and book modes. ## Manage fold states and postures @@ -16,9 +14,9 @@ postures, such as tabletop and book modes. ### Detect posture changes -Use the Jetpack WindowManager library to observe the device's hinge state and -fold layout. +Use the Jetpack WindowManager library to observe the device's hinge state and fold layout. +
```kotlin lifecycleScope.launch { @@ -33,15 +31,14 @@ lifecycleScope.launch { } } } + ```
### Handle tabletop mode -In Tabletop mode, horizontal fold, you should move the viewfinder to the top -half of the screen and the controls to the bottom half to prevent the user from -seeing a "bent" image. +In Tabletop mode, horizontal fold, you should move the viewfinder to the top half of the screen and the controls to the bottom half to prevent the user from seeing a "bent" image. - **Identify orientation:** Check `FoldingFeature.orientation`. - **Calculate geometry:** Use `FoldingFeature.bounds` to identify the hinge's physical location on the screen. @@ -49,9 +46,9 @@ seeing a "bent" image. ### Coordinate mapping and `Viewport` -When the UI layout changes due to a fold, you **must** update the `Viewport` to -ensure that tap-to-focus and image capture coordinates remain accurate. +When the UI layout changes due to a fold, you **must** update the `Viewport` to ensure that tap-to-focus and image capture coordinates remain accurate. +
```kotlin val viewport = ViewPort.Builder(Rational(viewfinder.width, viewfinder.height), display.rotation) @@ -62,14 +59,14 @@ val useCaseGroup = UseCaseGroup.Builder() .addUseCase(preview) .setViewPort(viewport) .build() + ```
### Rear display mode -Some foldables allow using the rear camera with the cover display while the -device is unfolded. +Some foldables allow using the rear camera with the cover display while the device is unfolded. - **Verification:** If available through OEM SDKs or Android 14 (API level 34) or higher, check `DeviceState.REAR_DISPLAY_STATE`. - **Logic:** Handle preview detachment and reattachment on different display surfaces with varying aspect ratios. diff --git a/camera/camerax/references/immutability.md b/camera/camerax/references/immutability.md index 1dade21..30e11f6 100644 --- a/camera/camerax/references/immutability.md +++ b/camera/camerax/references/immutability.md @@ -1,11 +1,8 @@ -Many Android APIs are designed with immutability in mind to prevent race -conditions in async environments. However, this often trips up developers used -to mutable builder patterns. +Many Android APIs are designed with immutability in mind to prevent race conditions in async environments. However, this often trips up developers used to mutable builder patterns. ## Common immutable classes -The following classes use fluent APIs that **return a new instance**. You must -reassign the variable. +The following classes use fluent APIs that **return a new instance**. You must reassign the variable. | Class | Methods that return a new instance | Result if not reassigned | |---|---|---| @@ -20,6 +17,7 @@ reassign the variable. To set up video recording, use the following code: +
```kotlin // WRONG @@ -42,6 +40,7 @@ run { pending = pending.withAudioEnabled() // Reassignment val active = pending.start(exec, listener) } + ```
@@ -50,11 +49,13 @@ run { To set up the viewport, use the following code: +
```kotlin val viewport = ViewPort.Builder(Rational(width, height), displayRotation) .setScaleType(ViewPort.FILL_CENTER) .build() + ```
\ No newline at end of file diff --git a/camera/camerax/references/low-light.md b/camera/camerax/references/low-light.md index e03e00c..3650fa5 100644 --- a/camera/camerax/references/low-light.md +++ b/camera/camerax/references/low-light.md @@ -1,5 +1,4 @@ -This guide covers implementing low-light features using **Night mode -extensions** and **Low Light Boost (LLB)**. +This guide covers implementing low-light features using **Night mode extensions** and **Low Light Boost (LLB)**. ## Choosing the right tool @@ -13,13 +12,13 @@ extensions** and **Low Light Boost (LLB)**. ## Night mode extension -CameraX Extensions provide access to the device's built-in computational -photography pipeline. +CameraX Extensions provide access to the device's built-in computational photography pipeline. ### Basic setup To set up the extension, initialize the extension manager: +
```kotlin // Use ListenableFuture.await() extension function for coroutine support @@ -30,6 +29,7 @@ if (extensionsManager.isExtensionAvailable(cameraSelector, ExtensionMode.NIGHT)) ) cameraProvider.bindToLifecycle(lifecycleOwner, nightSelector, imageCapture, preview) } + ```
@@ -42,6 +42,7 @@ if (extensionsManager.isExtensionAvailable(cameraSelector, ExtensionMode.NIGHT)) val imageCapture = ImageCapture.Builder() .setPostviewEnabled(true) .build() + ``` - **Extension strength** : Let users control the intensity of the night effect. @@ -50,6 +51,7 @@ if (extensionsManager.isExtensionAvailable(cameraSelector, ExtensionMode.NIGHT)) val extensionsManager = ExtensionsManager.getInstanceAsync(context, cameraProvider).await() val extensionsControl = extensionsManager.getCameraExtensionsControl(camera.cameraControl) extensionsControl?.setExtensionStrength(strength) + ``` - **Capture progress** : Show a UI progress bar for long exposures. @@ -61,6 +63,7 @@ if (extensionsManager.isExtensionAvailable(cameraSelector, ExtensionMode.NIGHT)) } catch (e: ImageCaptureException) { // Handle capture failure } + ``` *** ** * ** *** @@ -71,8 +74,7 @@ LLB is designed for preview and video streams where you prefer high frame rates. ### AE mode -The built-in CameraX way to prioritize brightness. It modifies the hardware's -auto-exposure algorithm. +The built-in CameraX way to prioritize brightness. It modifies the hardware's auto-exposure algorithm. - **Activation** : Use `CameraControl.enableLowLightBoostAsync`. - **Implementation** : @@ -80,6 +82,7 @@ auto-exposure algorithm. ```kotlin // Enable Low Light Boost (LLB) natively in CameraX 1.4+ camera.cameraControl.enableLowLightBoostAsync(true) + ``` - **Monitoring** : Observe `CameraInfo.lowLightBoostState` to track when the hardware actively applies the enhancement. @@ -112,6 +115,7 @@ To implement Google Play services LLB, follow these core steps: .addUseCase(videoCapture) .addEffect(effect) .build() + ``` 4. **Scene detection** : Use `session.setSceneDetectorCallback` to receive `boostStrength` updates for real-time UI indicators. diff --git a/camera/camerax/references/mlkit-spatial.md b/camera/camerax/references/mlkit-spatial.md index 833daf1..0b29bb2 100644 --- a/camera/camerax/references/mlkit-spatial.md +++ b/camera/camerax/references/mlkit-spatial.md @@ -1,6 +1,4 @@ -When you use ML Kit for features such as face mesh, object detection, or pose -detection, the most common failure point is the coordinate disparity between the -analysis image and the viewfinder UI. +When you use ML Kit for features such as face mesh, object detection, or pose detection, the most common failure point is the coordinate disparity between the analysis image and the viewfinder UI. ## The mapping mindset @@ -16,25 +14,23 @@ analysis image and the viewfinder UI. ### Coordinate transformation matrix -Android provides the `Viewport` and `UseCaseGroup` APIs to calculate the -transformation matrix automatically. **Don't** calculate aspect ratio scaling -manually. +Android provides the `Viewport` and `UseCaseGroup` APIs to calculate the transformation matrix automatically. **Don't** calculate aspect ratio scaling manually. +
```kotlin val transform = previewView.viewPort?.let { viewPort -> // Use CameraX's built-in coordinate mapper viewPort.getTransformationMatrix(imageProxy.imageInfo.rotationDegrees) } + ```
### Handling the "double rotation" bug -ML Kit results, bounding boxes, are relative to the **rotated buffer**. If the -device is in portrait, the buffer is often 480x640, landscape, but the screen -is 1080x1920. +ML Kit results, bounding boxes, are relative to the **rotated buffer**. If the device is in portrait, the buffer is often 480x640, landscape, but the screen is 1080x1920. To map the coordinates, use the following workflow: @@ -44,20 +40,20 @@ To map the coordinates, use the following workflow: ### Face mesh and pose normalization -For high-precision spatial analysis, for example, "Is the user's hand at a -specific screen button?", use **normalized coordinates from 0.0 to 1.0**. +For high-precision spatial analysis, for example, "Is the user's hand at a specific screen button?", use **normalized coordinates from 0.0 to 1.0**. +
```kotlin // Example: Converting a Pose landmark to a Screen Coordinate val screenX = landmark.position.x / analysisWidth * screenWidth val screenY = landmark.position.y / analysisHeight * screenHeight + ```
-**Warning** : Always account for **mirrored lenses** . If the `LENS_FACING_FRONT` -is used, you must flip the X-coordinate: `actualX = screenWidth - screenX`. +**Warning** : Always account for **mirrored lenses** . If the `LENS_FACING_FRONT` is used, you must flip the X-coordinate: `actualX = screenWidth - screenX`. ### Overlays and canvas clipping diff --git a/camera/camerax/references/modern-apis.md b/camera/camerax/references/modern-apis.md index 616d549..32f0d56 100644 --- a/camera/camerax/references/modern-apis.md +++ b/camera/camerax/references/modern-apis.md @@ -1,5 +1,4 @@ -Always prefer these various abstractions over legacy Camera2 or early CameraX -implementations. +Always prefer these various abstractions over legacy Camera2 or early CameraX implementations. ## Compare APIs @@ -38,5 +37,4 @@ Add the following dependencies to your `libs.versions.toml` file: androidx-camera-extensions = { group = "androidx.camera", name = "camera-extensions", version.ref = "camerax" } -Refer to the official [CameraX Release Notes](https://developer.android.com/jetpack/androidx/releases/camera) for the -stable versions. \ No newline at end of file +Refer to the official [CameraX Release Notes](https://developer.android.com/jetpack/androidx/releases/camera) for the stable versions. \ No newline at end of file diff --git a/camera/camerax/references/testing.md b/camera/camerax/references/testing.md index 972f285..2c24bc3 100644 --- a/camera/camerax/references/testing.md +++ b/camera/camerax/references/testing.md @@ -1,6 +1,4 @@ -Automated testing for camera features is notoriously difficult because you -can't easily mock physical hardware, lighting, or motion. This guide provides -patterns for reliable, hermetic camera tests. +Automated testing for camera features is notoriously difficult because you can't easily mock physical hardware, lighting, or motion. This guide provides patterns for reliable, hermetic camera tests. ## Develop a testing mindset @@ -17,42 +15,41 @@ patterns for reliable, hermetic camera tests. ### Fakes over mocks -**Don't use Mockito.** Relying on mocks for complex, rapidly changing interfaces -like `ImageProxy` or `CameraInfo` makes tests brittle. Instead, build "Fake" -implementations that verify state rather than behavior. +**Don't use Mockito.** Relying on mocks for complex, rapidly changing interfaces like `ImageProxy` or `CameraInfo` makes tests brittle. Instead, build "Fake" implementations that verify state rather than behavior. +
```kotlin // Create a Fake ImageProxy for ML Testing (Fakes over Mocks) val fakeImage = FakeImageProxy(w = 640, h = 480) // Feed the fake buffer into your analyzer + ```
### Mock camera capabilities -Use `FakeAppConfig` from `androidx.camera:camera-testing` to simulate specific -hardware constraints in tests, such as a device without a flash. +Use `FakeAppConfig` from `androidx.camera:camera-testing` to simulate specific hardware constraints in tests, such as a device without a flash. +
```kotlin // Use awaitInstance() extension function for coroutine-based provider retrieval val cameraProvider = ProcessCameraProvider.awaitInstance(context) + ```
### Use Truth assertions -Use Google Truth, `assertThat`, instead of standard JUnit assertions. It -provides more readable assertion chains and useful failure messages. +Use Google Truth, `assertThat`, instead of standard JUnit assertions. It provides more readable assertion chains and useful failure messages. ### Test asynchronous lifecycles -Camera initialization is asynchronous. Use `IdlingResource` to ensure -your test waits for the `UseCase` to be bound before asserting. +Camera initialization is asynchronous. Use `IdlingResource` to ensure your test waits for the `UseCase` to be bound before asserting. To test asynchronous lifecycles, use the following pattern: diff --git a/camera/camerax/references/thermals.md b/camera/camerax/references/thermals.md index 41cfe19..0447f27 100644 --- a/camera/camerax/references/thermals.md +++ b/camera/camerax/references/thermals.md @@ -1,6 +1,4 @@ -Camera operations are among the most power-intensive tasks on mobile devices. -Without proactive management, the system throttle hardware, drop frames, or -force-close the camera app. +Camera operations are among the most power-intensive tasks on mobile devices. Without proactive management, the system throttle hardware, drop frames, or force-close the camera app. ## The thermal management strategy @@ -16,9 +14,9 @@ force-close the camera app. ### Stream use case optimization -Android 13 (API level 33) introduced `StreamUseCase`. This is the **single most -effective** way to tell the hardware how to balance quality versus power. +Android 13 (API level 33) introduced `StreamUseCase`. This is the **single most effective** way to tell the hardware how to balance quality versus power. +
```kotlin // In CameraX: Set the hint on your Use Case @@ -30,6 +28,7 @@ val preview = Preview.Builder() ) } .build() + ```
@@ -43,9 +42,9 @@ Review the following key use cases for stream optimization: ### Monitor thermal status -Don't wait for a crash. Monitor the `PowerManager` status and react before -`THERMAL_STATUS_CRITICAL`. +Don't wait for a crash. Monitor the `PowerManager` status and react before `THERMAL_STATUS_CRITICAL`. +
```kotlin val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager @@ -63,6 +62,7 @@ powerManager.addThermalStatusListener { status -> } } } + ```
diff --git a/camera/camerax/references/wear-os.md b/camera/camerax/references/wear-os.md index 4a942db..11ae45f 100644 --- a/camera/camerax/references/wear-os.md +++ b/camera/camerax/references/wear-os.md @@ -1,6 +1,4 @@ -Developing camera features for Wear OS is rarely about the watch's own lens, if -it even has one. It's almost always about creating a **Remote Viewfinder** to -control the phone's camera. +Developing camera features for Wear OS is rarely about the watch's own lens, if it even has one. It's almost always about creating a **Remote Viewfinder** to control the phone's camera. ## The Wear OS remote mindset @@ -17,8 +15,7 @@ control the phone's camera. ### The circular UI challenge -Wear OS devices are often round. Standard rectangular layouts clip corner -buttons. +Wear OS devices are often round. Standard rectangular layouts clip corner buttons. Follow these blueprint recommendations: @@ -30,6 +27,7 @@ Follow these blueprint recommendations: You can't send a raw 60 fps stream over Bluetooth. compress and throttle. +
```kotlin // Example: Sending a viewfinder frame to the watch @@ -41,30 +39,31 @@ if (bitmap != null) { } Wearable.getDataClient(context).putDataItem(request.asPutDataRequest()) } + + ```
-**Optimization** : Cap the watch preview at **10-15 fps** to preserve battery and -bandwidth. +**Optimization** : Cap the watch preview at **10-15 fps** to preserve battery and bandwidth. ### Remote triggers and syncing -Use the `MessageClient` for low-latency commands like "Take Photo" or "Switch -Camera." +Use the `MessageClient` for low-latency commands like "Take Photo" or "Switch Camera." +
```kotlin // Watch sends a trigger to the phone Wearable.getMessageClient(context).sendMessage(nodeId, "/camera/capture", null) + ```
### Rotary input support -On devices that support it, use the physical crown, Rotary Input, to control -**Zoom** or **Exposure**. +On devices that support it, use the physical crown, Rotary Input, to control **Zoom** or **Exposure**. *** ** * ** *** diff --git a/camera/camerax/references/xr.md b/camera/camerax/references/xr.md index 59fae32..1edfddf 100644 --- a/camera/camerax/references/xr.md +++ b/camera/camerax/references/xr.md @@ -1,5 +1,4 @@ -Developing camera features for XR devices, headsets, and AR glasses requires a -shift from 2D pixel-pushing to 3D spatial awareness. +Developing camera features for XR devices, headsets, and AR glasses requires a shift from 2D pixel-pushing to 3D spatial awareness. ## Understand the XR development mindset @@ -15,8 +14,7 @@ shift from 2D pixel-pushing to 3D spatial awareness. ### API selection -On XR devices, standard `CameraX` implementations are often restricted or -insufficient. Always use spatial software development kits (SDKs): +On XR devices, standard `CameraX` implementations are often restricted or insufficient. Always use spatial software development kits (SDKs): - **ARCore**: Use ARCore for plane detection, depth sensing, and motion tracking. - **OpenXR**: Use OpenXR as the cross-platform standard for VR and AR rendering and input. @@ -26,13 +24,13 @@ insufficient. Always use spatial software development kits (SDKs): Unlike a 2D viewport, XR passthrough is often system-managed. -**\[Key requirement\] Frame synchronization**: Synchronize your application's -frame clock with the headset's head-mounted display (HMD) pose. +**\[Key requirement\] Frame synchronization**: Synchronize your application's frame clock with the headset's head-mounted display (HMD) pose. ```kotlin // Example: Querying the spatial pose for the current camera frame val headPose = xrSession.getHeadPose(frameTime) val projectionMatrix = headPose.getProjectionMatrix(eyeIndex) + ```
diff --git a/device-ai/appfunctions/SKILL.md b/device-ai/appfunctions/SKILL.md index ad75915..5ad96e6 100644 --- a/device-ai/appfunctions/SKILL.md +++ b/device-ai/appfunctions/SKILL.md @@ -9,7 +9,7 @@ description: Analyzes Android apps to identify key user workflows for AppFunctio license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-28' + last-updated: '2026-08-06' keywords: - AppFunctions - Kotlin @@ -20,29 +20,19 @@ metadata: - MCP --- -Analyzes Android apps to identify key user workflows for AppFunctions such as -creating a note, playing media, or sending an automated or AI agent triggered -message, voice commands, or system shortcuts, without needing to open the app -UI. +Analyzes Android apps to identify key user workflows for AppFunctions such as creating a note, playing media, or sending an automated or AI agent triggered message, voice commands, or system shortcuts, without needing to open the app UI. -Generates Kotlin code to expose these workflows to the Android system, -allowing agents to discover and execute them on-device. +Generates Kotlin code to expose these workflows to the Android system, allowing agents to discover and execute them on-device. -Also refines KDoc documentation to ensure AI agents correctly -understand and use the provided functionality. +Also refines KDoc documentation to ensure AI agents correctly understand and use the provided functionality. ## Prerequisites -The app must **`targetSdk 36`** or newer and use **`compileSdk 37`** or newer as -AppFunctions, part of the Android platform API, are available from Android 16 -onwards. -Always use the Jetpack library because it handles backward compatibility. +The app must **`targetSdk 36`** or newer and use **`compileSdk 37`** or newer as AppFunctions, part of the Android platform API, are available from Android 16 onwards. Always use the Jetpack library because it handles backward compatibility. ## Workflows -This skill enables the caller to discover features that will be provided to -system agents, implement these with AppFunctions, improve function description -for agents, and use ADB commands for local evaluation and testing. +This skill enables the caller to discover features that will be provided to system agents, implement these with AppFunctions, improve function description for agents, and use ADB commands for local evaluation and testing. The full AppFunction development flow consists of these four steps: @@ -55,7 +45,7 @@ If users request a subset of steps, you must encourage them to use all steps. If they apply, you must load the following references: -- *[Context and terminology](context.md)*: Defines the ubiquitous language, architecture definitions, and design patterns across the AppFunctions skill suite. Load when you need to understand core architecture terminology or check the distinctions between modern and legacy AppFunctions APIs. +- *[Context and terminology](references/context.md)*: Defines the ubiquitous language, architecture definitions, and design patterns across the AppFunctions skill suite. Load when you need to understand core architecture terminology or check the distinctions between modern and legacy AppFunctions APIs. - *[Migration to service entry point](references/migrate-to-service-entry-point.md)* : Documents the systematic procedure for migrating Android applications using AppFunctions versions 1.0.0-alpha09 and lower to `AppFunctionServiceEntryPoint` architecture introduced in version 1.0.0-alpha10. Load when a user asks to migrate or upgrade existing AppFunctions code, or when you encounter legacy `AppFunctionConfiguration.Provider` implementations. ## Critical constraints @@ -67,5 +57,5 @@ If they apply, you must load the following references: - If you encounter build-time errors such as Kotlin Symbol Processing (KSP) issues, see [Implementation and configuration](references/implementation-configuration.md). - If you encounter runtime errors such as missing services or execution failures, see [Testing and debugging](references/adb-interaction-testing.md). -- If you need architecture definitions and vocabulary, see [Context and terminology](context.md). +- If you need architecture definitions and vocabulary, see [Context and terminology](references/context.md). - If you encounter issues when upgrading legacy configurations, see [Migration to service entry point](references/migrate-to-service-entry-point.md). diff --git a/device-ai/appfunctions/context.md b/device-ai/appfunctions/context.md deleted file mode 100644 index dc49d25..0000000 --- a/device-ai/appfunctions/context.md +++ /dev/null @@ -1,26 +0,0 @@ -Defines the ubiquitous language for the Android AppFunctions skill suite. - -## Architecture and versioning - -`AppFunctionServiceEntryPoint` API: -This compile-time AppFunctions architecture was introduced in version -1.0.0-alpha10. You annotate a wrapper service extending -`AppFunctionService` with `@AppFunctionServiceEntryPoint`. KSP then generates -XML metadata and routes services at compile time. - -Legacy manual provider API: -This deprecated AppFunctions architecture applies to version -1.0.0-alpha09 and earlier. Applications implement -`AppFunctionConfiguration.Provider` on the `Application` class. Methods -require `AppFunctionContext` as the first parameter. Projects depend on -a standalone `appfunctions-service` library. - -## Patterns - -Service entry point pattern: -Version 1.0.0-alpha10 introduced this architectural pattern. You -declare `@AppFunction` methods directly inside an abstract class extending -`AppFunctionService`. This class uses `@AppFunctionServiceEntryPoint` and -`@AndroidEntryPoint` annotations. These annotations let you inject data -sources or repositories directly, without an intermediate business logic -delegation layer. \ No newline at end of file diff --git a/device-ai/appfunctions/references/adb-interaction-testing.md b/device-ai/appfunctions/references/adb-interaction-testing.md index b487923..b7fac4a 100644 --- a/device-ai/appfunctions/references/adb-interaction-testing.md +++ b/device-ai/appfunctions/references/adb-interaction-testing.md @@ -1,16 +1,13 @@ -Provides commands to interact with AppFunctions on a connected device or -emulator using ADB for AppFunction testing and debugging. +Provides commands to interact with AppFunctions on a connected device or emulator using ADB for AppFunction testing and debugging. ## Instructions ### Scenario 1: List app functions -Use this scenario when you want to see which app functions are registered on -the device. +Use this scenario when you want to see which app functions are registered on the device. 1. **List all functions** : To view all registered app functions in JSON format, run `adb shell cmd app_function list-app-functions`. -2. **Filter by package** : To view functions for a specific package, pipe the output to `grep` or a JSON tool: `adb shell cmd app_function - list-app-functions | grep `. +2. **Filter by package** : To view functions for a specific package, pipe the output to `grep` or a JSON tool: `adb shell cmd app_function list-app-functions | grep `. ### Scenario 2: Invoke app functions @@ -19,38 +16,28 @@ If you want to test the execution of an app function, use this scenario. 1. **Analyze description** : Before invoking, you must read the `description` field for the function in the `list-app-functions` output. This often contains critical usage constraints, required workflows, or disambiguation rules. 2. **Follow constraints**: Follow all instructions in the description, such as asking the user to disambiguate or calling another tool first. 3. **Format parameters** : Format the `--parameters` argument as a valid JSON string that represents the function's input arguments. -4. **Execute function** : Use `adb shell cmd app_function execute-app-function - --package --function - --parameters ''`. +4. **Execute function** : Use `adb shell cmd app_function execute-app-function --package --function --parameters ''`. 5. **Handle response** : The command returns the result as a JSON string. To get brief YAML output, use `--brief-yaml`. ### Scenario 3: Manage function state If you need to enable or disable an app function for testing, use this scenario. -1. **Set enabled state** : Use `adb shell cmd app_function set-enabled - --package - --function - --state `. +1. **Set enabled state** : Use `adb shell cmd app_function set-enabled --package --function --state `. ## Critical constraints ### Follow metadata descriptions -**Mandatory** : The `description` field in the app function metadata is a set of -instructions for the LLM. If a description says to "disambiguate with the user" -or "call another function first," you must perform those steps before execution. +**Mandatory** : The `description` field in the app function metadata is a set of instructions for the LLM. If a description says to "disambiguate with the user" or "call another function first," you must perform those steps before execution. ### JSON escaping -**Critical** : When passing JSON using `adb shell`, always wrap the JSON string -in single quotes to prevent the shell from interpreting special characters or -spaces. Example: `--parameters '{"key": "value"}'`. +**Critical** : When passing JSON using `adb shell`, always wrap the JSON string in single quotes to prevent the shell from interpreting special characters or spaces. Example: `--parameters '{"key": "value"}'`. ### Device availability -The `app_function` service must be available on the device. If `cmd: Can't find -service: app_function` is returned, the device doesn't support this feature. +The `app_function` service must be available on the device. If `cmd: Can't find service: app_function` is returned, the device doesn't support this feature. ## Examples @@ -58,8 +45,7 @@ service: app_function` is returned, the device doesn't support this feature. adb shell cmd app_function help -If executing the preceding command returns a help page, use the commands and -parameters provided to guide the ADB interaction testing tool interactions. +If executing the preceding command returns a help page, use the commands and parameters provided to guide the ADB interaction testing tool interactions. ### Example 2: List all registered app functions @@ -91,5 +77,4 @@ parameters provided to guide the ADB interaction testing tool interactions. **Cause**: The function ID or package name is incorrect. -**Solution** : Run `list-app-functions` and search for the relevant identifiers -in the JSON output. \ No newline at end of file +**Solution** : Run `list-app-functions` and search for the relevant identifiers in the JSON output. \ No newline at end of file diff --git a/device-ai/appfunctions/references/context.md b/device-ai/appfunctions/references/context.md new file mode 100644 index 0000000..9d18e2c --- /dev/null +++ b/device-ai/appfunctions/references/context.md @@ -0,0 +1,11 @@ +Defines the ubiquitous language for the Android AppFunctions skill suite. + +## Architecture and versioning + +`AppFunctionServiceEntryPoint` API: This compile-time AppFunctions architecture was introduced in version 1.0.0-alpha10. You annotate a wrapper service extending `AppFunctionService` with `@AppFunctionServiceEntryPoint`. KSP then generates XML metadata and routes services at compile time. + +Legacy manual provider API: This deprecated AppFunctions architecture applies to version 1.0.0-alpha09 and earlier. Applications implement `AppFunctionConfiguration.Provider` on the `Application` class. Methods require `AppFunctionContext` as the first parameter. Projects depend on a standalone `appfunctions-service` library. + +## Patterns + +Service entry point pattern: Version 1.0.0-alpha10 introduced this architectural pattern. You declare `@AppFunction` methods directly inside an abstract class extending `AppFunctionService`. This class uses `@AppFunctionServiceEntryPoint` and `@AndroidEntryPoint` annotations. These annotations let you inject data sources or repositories directly, without an intermediate business logic delegation layer. \ No newline at end of file diff --git a/device-ai/appfunctions/references/feature-discovery-analysis.md b/device-ai/appfunctions/references/feature-discovery-analysis.md index 583f67c..4adb255 100644 --- a/device-ai/appfunctions/references/feature-discovery-analysis.md +++ b/device-ai/appfunctions/references/feature-discovery-analysis.md @@ -13,15 +13,11 @@ Analyzes Android codebases to identify and recommend high-value AppFunctions. ### Tool-first thinking -Avoid recommending functions that are purely informational or redundant with -existing system actions. Focus on "mutations" (writing data) or "rich queries" -(finding specific entities). +Avoid recommending functions that are purely informational or redundant with existing system actions. Focus on "mutations" (writing data) or "rich queries" (finding specific entities). ### Security and privacy -Don't recommend exposing functions that handle raw credentials, financial -secrets, or irreversible destructive actions without explicit user confirmation -steps. +Don't recommend exposing functions that handle raw credentials, financial secrets, or irreversible destructive actions without explicit user confirmation steps. ## Examples @@ -29,9 +25,7 @@ steps. **Recommended AppFunction** : `playArtistRadio` -**Rationale**: Lets you start a personalized music stream using a voice -command, bypassing several layers of navigation in the "Search" and "Artist" -menus. +**Rationale**: Lets you start a personalized music stream using a voice command, bypassing several layers of navigation in the "Search" and "Artist" menus. **Input required** : `artistName` as a `String`. @@ -39,33 +33,22 @@ menus. **Recommended AppFunction** : `searchContacts` -**Rationale** : Serves as a "rich query" to resolve a human-readable contact -name, email, or chat group to a unique identifier (`endpointValue`), which is a -prerequisite before executing actions like sending messages or -initiating calls. Also allows retrieving recently contacted entities when given -a blank query. +**Rationale** : Serves as a "rich query" to resolve a human-readable contact name, email, or chat group to a unique identifier (`endpointValue`), which is a prerequisite before executing actions like sending messages or initiating calls. Also allows retrieving recently contacted entities when given a blank query. -**Input required** : Query as a `String`, and Filter Type as a `String` -constrained to `"INDIVIDUAL"` or `"GROUP"`. +**Input required** : Query as a `String`, and Filter Type as a `String` constrained to `"INDIVIDUAL"` or `"GROUP"`. ### Example 3: Chat app message sending **Recommended AppFunction** : `send` -**Rationale**: This mutation function lets you send text messages and -optional image attachments to a contact or group using natural language -commands, for example, "Tell Alice I'm running 5 minutes late." This -eliminates multi-step UI navigation across contact lists and conversation -threads. +**Rationale**: This mutation function lets you send text messages and optional image attachments to a contact or group using natural language commands, for example, "Tell Alice I'm running 5 minutes late." This eliminates multi-step UI navigation across contact lists and conversation threads. -**Input required** : Endpoint Value as a `String`, Message Body as a `String`, -and Image URIs as an optional `List` of URIs. +**Input required** : Endpoint Value as a `String`, Message Body as a `String`, and Image URIs as an optional `List` of URIs. ### Example 4: Chat app voice calling **Recommended AppFunction** : `makeCall` -**Rationale**: Lets you initiate voice calls hands-free to a contact or -group using an AI agent without navigating the app's UI. +**Rationale**: Lets you initiate voice calls hands-free to a contact or group using an AI agent without navigating the app's UI. **Input required** : `endpointValue` as a `String`. \ No newline at end of file diff --git a/device-ai/appfunctions/references/implementation-configuration.md b/device-ai/appfunctions/references/implementation-configuration.md index fb9292c..4f8260e 100644 --- a/device-ai/appfunctions/references/implementation-configuration.md +++ b/device-ai/appfunctions/references/implementation-configuration.md @@ -1,19 +1,19 @@ -Specialized instructions for generating Kotlin implementations of AppFunctions, -handling system-wide configuration, and managing build dependencies. +Specialized instructions for generating Kotlin implementations of AppFunctions, handling system-wide configuration, and managing build dependencies. ## Instructions ### Step 1: Configure Gradle dependencies and KSP -Add the following to `build.gradle.kts`. App Functions requires the KSP (Kotlin -Symbol Processing) plugin. +Add the following to `build.gradle.kts`. App Functions requires the KSP (Kotlin Symbol Processing) plugin. 1. **Version check** : Use library version `1.0.0-alpha10` or later from maven.google.com. +
```kotlin implementation(libs.androidx.appfunctions) ksp(libs.androidx.appfunctions.compiler) + ```
@@ -24,9 +24,9 @@ ksp(libs.androidx.appfunctions.compiler) ### Step 2: Set up app metadata XML -Describe the app's capabilities to the LLM by defining -`res/xml/app_metadata.xml`. +Describe the app's capabilities to the LLM by defining `res/xml/app_metadata.xml`. +
```xml + ```
-Register the service and reference the app metadata in `AndroidManifest.xml` -within the `` tag: +Register the service and reference the app metadata in `AndroidManifest.xml` within the `` tag: +
```xml ` tag: + ```
@@ -96,16 +98,13 @@ When generating Kotlin code for AppFunctions, you MUST adhere to these rules: ### Step 4: Set up dependency injection and service entry points -In version 1.0.0-alpha10 and later, App Functions use the compile-time -`@AppFunctionServiceEntryPoint` architecture. Create an abstract class extending -`AppFunctionService` annotated with `@AppFunctionServiceEntryPoint`. KSP -generates the concrete service class and XML schema. +In version 1.0.0-alpha10 and later, App Functions use the compile-time `@AppFunctionServiceEntryPoint` architecture. Create an abstract class extending `AppFunctionService` annotated with `@AppFunctionServiceEntryPoint`. KSP generates the concrete service class and XML schema. #### Recommended approach with Hilt -Annotate your service with `@AndroidEntryPoint` and inject your data -repositories or use cases using standard `@Inject internal lateinit var`: +Annotate your service with `@AndroidEntryPoint` and inject your data repositories or use cases using standard `@Inject internal lateinit var`: +
```kotlin @RequiresApi(36) @@ -126,19 +125,16 @@ abstract class BaseAppFunctionServiceHeader : AppFunctionService() { return messageRepository.send(name, endpointValue, messageBody) } } + ```
#### Framework-agnostic approach with alternative dependency injection or service locators -While Hilt is recommended, many Android applications implement AppFunctions with -alternative dependency injection frameworks (like Koin, Anvil, or manual Service -Locators). Because `AppFunctionService` inherits from Android -`android.app.Service` (and therefore `Context`), you are able access your -application's DI container directly through `applicationContext` in property -getters or during service lifecycle execution: +While Hilt is recommended, many Android applications implement AppFunctions with alternative dependency injection frameworks (like Koin, Anvil, or manual Service Locators). Because `AppFunctionService` inherits from Android `android.app.Service` (and therefore `Context`), you are able access your application's DI container directly through `applicationContext` in property getters or during service lifecycle execution: +
```kotlin @RequiresApi(36) @@ -163,16 +159,14 @@ abstract class BaseAppFunctionServiceLocator : AppFunctionService() { return messageRepository.send(name, endpointValue, messageBody) } } + ```
### Step 5: Architectural cleanliness -Don't attempt to make an `AppFunction` class or method OS-agnostic---App Functions are inherently part of the Android platform integration in `androidx.appfunctions`. For architectural cleanliness, use existing -application functionality (such as existing repositories, use cases, or domain -orchestrators) to execute the behavior within your `@AppFunction` methods rather -than creating redundant abstraction layers around the OS service. +Don't attempt to make an `AppFunction` class or method OS-agnostic---App Functions are inherently part of the Android platform integration in `androidx.appfunctions`. For architectural cleanliness, use existing application functionality (such as existing repositories, use cases, or domain orchestrators) to execute the behavior within your `@AppFunction` methods rather than creating redundant abstraction layers around the OS service.
@@ -180,19 +174,17 @@ than creating redundant abstraction layers around the OS service. ### KSP compliance for serializables -**Critical constraints** : For `@AppFunctionSerializable` data classes, KSP -only extracts documentation if it's written as inline KDoc directly for each -property definition. Don't use class-level `@param` or `@property` tags. +**Critical constraints** : For `@AppFunctionSerializable` data classes, KSP only extracts documentation if it's written as inline KDoc directly for each property definition. Don't use class-level `@param` or `@property` tags. ### Package integrity -Configuration APIs and the `@AppFunction` annotation are located in -`androidx.appfunctions`. +Configuration APIs and the `@AppFunction` annotation are located in `androidx.appfunctions`. ## Examples ### Example: Serializable with inline KDoc +
```kotlin /** The parameter to create the task. */ @@ -214,6 +206,7 @@ data class Task( /** The content of the task. */ val content: String, ) + ```
@@ -222,6 +215,7 @@ data class Task( ### Example: Implementation detail +
```kotlin @RequiresApi(36) @@ -262,6 +256,7 @@ abstract class BaseTaskAppFunctionService : AppFunctionService() { // Maps internal TaskEntity private fun TaskEntity.toTask() = Task(id = id, title = title, content = description) } + ```
diff --git a/device-ai/appfunctions/references/kdoc-refinement-optimization.md b/device-ai/appfunctions/references/kdoc-refinement-optimization.md index c0a3209..38ce18e 100644 --- a/device-ai/appfunctions/references/kdoc-refinement-optimization.md +++ b/device-ai/appfunctions/references/kdoc-refinement-optimization.md @@ -5,8 +5,7 @@ Optimizes AppFunction KDoc for AI agents and Model Context Protocol. ### Workflow: Agent-centric documentation 1. **Identify the core outcome** : Start the description with a strong imperative verb, for example, "Search", "Create", or "Update". Focus on the *user benefit*, not the code implementation. -2. **Workflow dependencies** : Explicitly state if another function must be called first using the standard phrase: **Required workflow: Call "Function - A" first to "Objective"**. +2. **Workflow dependencies** : Explicitly state if another function must be called first using the standard phrase: **Required workflow: Call "Function A" first to "Objective"**. 3. **Parameter documentation** : - For **functions** : Use specific `@param` tags. Isolate validation rules and default values here. - For **serializables** : Use inline KDoc directly for each property declaration. KSP **won't** extract documentation from class-level tags. @@ -14,8 +13,7 @@ Optimizes AppFunction KDoc for AI agents and Model Context Protocol. ### Workflow: Global app description for server instructions -When writing the `appfn:description` for `app_metadata.xml`, follow these -instructions: +When writing the `appfn:description` for `app_metadata.xml`, follow these instructions: 1. **Capture cross-function relationships**: Explain dependencies or sequences between tools, for example, "Always call 'authenticate' before fetching data.". 2. **Document operational patterns**: Guide the LLM on token-conserving usage, for example, "Use 'batch_update' over multiple 'update' calls." @@ -29,19 +27,15 @@ instructions: ### Descriptive, not imperative -Describe what the function *does* , not what the LLM *must* do. Avoid phrases -like "You must call this..." in favor of "This function provides...". +Describe what the function *does* , not what the LLM *must* do. Avoid phrases like "You must call this..." in favor of "This function provides...". ### No "fluff" -Remove conversational padding like "This method is used to..." or "Helpful -for...". Be concise and technical. +Remove conversational padding like "This method is used to..." or "Helpful for...". Be concise and technical. ### Inline KDoc for serializables -**Mandatory** : For `@AppFunctionSerializable` classes, documentation must be -inline for each property. KSP ignores class-level `@param` or `@property` tags -for these classes. +**Mandatory** : For `@AppFunctionSerializable` classes, documentation must be inline for each property. KSP ignores class-level `@param` or `@property` tags for these classes. ## Examples diff --git a/device-ai/appfunctions/references/migrate-to-service-entry-point.md b/device-ai/appfunctions/references/migrate-to-service-entry-point.md index f350f61..a0528e9 100644 --- a/device-ai/appfunctions/references/migrate-to-service-entry-point.md +++ b/device-ai/appfunctions/references/migrate-to-service-entry-point.md @@ -1,7 +1,4 @@ -Follow this systematic procedure to migrate Android applications that use the -AppFunctions API in version 1.0.0-alpha09 and lower to the compile-time -`@AppFunctionServiceEntryPoint` architecture introduced in version -`1.0.0-alpha10`. +Follow this systematic procedure to migrate Android applications that use the AppFunctions API in version 1.0.0-alpha09 and lower to the compile-time `@AppFunctionServiceEntryPoint` architecture introduced in version `1.0.0-alpha10`. *** ** * ** *** @@ -23,9 +20,7 @@ In version `1.0.0-alpha10` featuring `@AppFunctionServiceEntryPoint`: ### Strict migration requirements from 1.0.0-alpha09 to 1.0.0-alpha10 -When focusing solely on the mandatory API changes required by the new -`@AppFunctionServiceEntryPoint` architecture, the migration consists of four -strict requirements that you must complete: +When focusing solely on the mandatory API changes required by the new `@AppFunctionServiceEntryPoint` architecture, the migration consists of four strict requirements that you must complete: 1. **Build dependency consolidation** : Remove the merged `appfunctions-service` dependency while retaining core `appfunctions` and the KSP compiler. 2. **Service wrapper creation** : Replace the legacy `AppFunctionConfiguration.Provider` on the `Application` class with an abstract class extending `AppFunctionService`, annotated with `@AppFunctionServiceEntryPoint`. @@ -38,10 +33,7 @@ strict requirements that you must complete: ### Consolidate AppFunctions build dependencies -Remove the standalone `appfunctions-service` library from your module build -files like `build.gradle.kts` and version catalog like `libs.versions.toml`. In -version `1.0.0-alpha10`, all core service capabilities are consolidated directly -within the main `appfunctions` artifact. +Remove the standalone `appfunctions-service` library from your module build files like `build.gradle.kts` and version catalog like `libs.versions.toml`. In version `1.0.0-alpha10`, all core service capabilities are consolidated directly within the main `appfunctions` artifact. // build.gradle.kts dependencies { @@ -66,16 +58,13 @@ within the main `appfunctions` artifact. ### Create a dedicated wrapper service extending `AppFunctionService` -Instead of annotating standalone business logic classes or implementing manual -configuration providers, create an abstract service wrapper across your project, -for example `BaseAppFunctionService`, extending `AppFunctionService` and -annotated with `@AppFunctionServiceEntryPoint`. +Instead of annotating standalone business logic classes or implementing manual configuration providers, create an abstract service wrapper across your project, for example `BaseAppFunctionService`, extending `AppFunctionService` and annotated with `@AppFunctionServiceEntryPoint`. #### Recommended approach using Hilt -Annotate your service with `@AndroidEntryPoint` and inject your data -repositories or use cases using standard `@Inject internal lateinit var`: +Annotate your service with `@AndroidEntryPoint` and inject your data repositories or use cases using standard `@Inject internal lateinit var`: +
```kotlin @RequiresApi(36) @@ -96,19 +85,16 @@ abstract class BaseAppFunctionService : AppFunctionService() { return messageRepository.send(name, endpointValue, messageBody) } } + ```
#### Framework-agnostic approach using alternative dependency injection or a service locator -While Hilt is recommended, many Android applications implement AppFunctions with -alternative dependency injection frameworks like Koin, Anvil, or manual Service -Locators. Because `AppFunctionService` inherits from Android -`android.app.Service` and therefore `Context`, you are able access your -application's DI container directly through `applicationContext` in property -getters or during service lifecycle execution: +While Hilt is recommended, many Android applications implement AppFunctions with alternative dependency injection frameworks like Koin, Anvil, or manual Service Locators. Because `AppFunctionService` inherits from Android `android.app.Service` and therefore `Context`, you are able access your application's DI container directly through `applicationContext` in property getters or during service lifecycle execution: +
```kotlin @RequiresApi(36) @@ -133,6 +119,7 @@ abstract class ServiceLocatorBaseAppFunctionService : AppFunctionService() { return messageRepository.send(name, endpointValue, messageBody) } } + ```
@@ -144,10 +131,7 @@ abstract class ServiceLocatorBaseAppFunctionService : AppFunctionService() { ### Simplify method signatures and decouple context -Remove legacy `AppFunctionContext` parameters from your core methods. When a -method requires an Android `Context`, for example when constructing a -`PendingIntent`, access `this` directly from your `AppFunctionService` wrapper -because the wrapper inherently extends `android.content.Context`. +Remove legacy `AppFunctionContext` parameters from your core methods. When a method requires an Android `Context`, for example when constructing a `PendingIntent`, access `this` directly from your `AppFunctionService` wrapper because the wrapper inherently extends `android.content.Context`. - suspend fun makeCall(appFunctionContext: AppFunctionContext, contactName: String?): PendingIntent + suspend fun makeCall(contactName: String?): PendingIntent @@ -156,8 +140,7 @@ because the wrapper inherently extends `android.content.Context`. ### Remove legacy configuration provider -Update your `Application` class by removing -`AppFunctionConfiguration.Provider` and its associated builder entry points: +Update your `Application` class by removing `AppFunctionConfiguration.Provider` and its associated builder entry points: - abstract class BaseChatApplication : Application(), AppFunctionConfiguration.Provider { ... } + abstract class BaseChatApplication : Application() @@ -166,21 +149,15 @@ Update your `Application` class by removing ### Avoid redundant abstraction layers -Don't attempt to make an `AppFunction` class or method OS-agnostic---AppFunctions -are inherently part of the Android platform integration through the -`androidx.appfunctions` package. For architectural cleanliness, use existing -application functionality, such as existing repositories, use cases, or domain -orchestrators, to execute the behavior within your `@AppFunction` methods rather -than creating redundant abstraction layers around the OS service. +Don't attempt to make an `AppFunction` class or method OS-agnostic---AppFunctions are inherently part of the Android platform integration through the `androidx.appfunctions` package. For architectural cleanliness, use existing application functionality, such as existing repositories, use cases, or domain orchestrators, to execute the behavior within your `@AppFunction` methods rather than creating redundant abstraction layers around the OS service. *** ** * ** *** ### Consolidate service and metadata manifest declarations -Register the KSP-generated service declaration and `app_metadata` property -inside your module manifest, for example in `src/main/AndroidManifest.xml` -within the `` tag: +Register the KSP-generated service declaration and `app_metadata` property inside your module manifest, for example in `src/main/AndroidManifest.xml` within the `` tag: +
```xml ` tag: + ```
@@ -209,18 +187,7 @@ within the `` tag: ## Verification and troubleshooting -1. **Clean rebuild and deploy** : `bash - ./gradlew clean installDebug` -2. **Verify AppSearch discovery / indexing** : Run the following ADB command to - confirm the OS successfully discovered and indexed your functions: - `bash - adb shell cmd app_function list-app-functions` - *If your package doesn't appear, confirm that `android.app.appfunctions.v2` - matches the exact asset name generated in `assets/`.* +1. **Clean rebuild and deploy** : `bash ./gradlew clean installDebug` +2. **Verify AppSearch discovery / indexing** : Run the following ADB command to confirm the OS successfully discovered and indexed your functions: `bash adb shell cmd app_function list-app-functions` *If your package doesn't appear, confirm that `android.app.appfunctions.v2` matches the exact asset name generated in `assets/`.* -3. **Verify execution using ADB** : - `bash - adb shell "cmd app_function execute-app-function \ - --package com.example.chatapp \ - --function 'com.example.chatapp.appfunctions.BaseAppFunctionService#send' \ - --parameters '{\"name\": \"Alice\", \"endpointValue\": \"1\", \"messageBody\": \"Hello Alice!\"}'"` \ No newline at end of file +3. **Verify execution using ADB** : `bash adb shell "cmd app_function execute-app-function \ --package com.example.chatapp \ --function 'com.example.chatapp.appfunctions.BaseAppFunctionService#send' \ --parameters '{\"name\": \"Alice\", \"endpointValue\": \"1\", \"messageBody\": \"Hello Alice!\"}'"` \ No newline at end of file diff --git a/devtools/android-cli/SKILL.md b/devtools/android-cli/SKILL.md index adb7fad..af4320b 100644 --- a/devtools/android-cli/SKILL.md +++ b/devtools/android-cli/SKILL.md @@ -80,30 +80,45 @@ Update the Android CLI using the `android update` command. # `android help` output -Usage: android [-hV] [--sdk=PARAM] [COMMAND] +Usage: android [-hvV] [--sdk=PARAM] [COMMAND] -h, --help Show this help message and exit. --sdk=PARAM Path to the Android SDK + -v, --verbose Enable verbose output for troubleshooting -V, --version Print version information and exit. Commands: - create Create a new Android project + create Create a new Android project from available templates. Allows + specifying project name, output directory, minSdk, and dry-run + execution. describe Analyzes an Android project to generate descriptive metadata. - docs Android documentation commands - emulator Emulator commands + docs Android documentation commands for searching and fetching developer + documentation from the official knowledge base. + emulator Manage Android Virtual Devices (AVDs). Includes commands to start, + stop, list, and view details about emulators. help Shows the help of all commands - info Print environment information (SDK Location, etc.) - init Initializes the environment (eg. skills) for Android CLI. + info Print environment information including SDK location, connected + devices, and configuration variables. Use specific fields to + narrow the output. + init Initializes the environment for the Android CLI. Sets up required + configurations, directories, and default skills. + install Install an Android Application (one or more APKs) to a connected + device or emulator without activating any components using + incremental optimizations for faster deployment than adb. layout Returns the layout tree of an application - run Deploy an Android Application + run Build, deploy, and launch an Android application on a connected + device or emulator. screen Commands to view the device - sdk Download and list SDK packages - skills Manage skills + sdk Manage the Android SDK installation. Includes commands to install, + update, remove, and list available and installed SDK packages. + skills Manage Android CLI skills. Includes commands to install, remove, + list, and search for skills by keyword. studio Android Studio commands - update Update the Android CLI + update Update the Android CLI to the latest version. create Usage: android create [-h] [--verbose] [--list] [--minSdk=api] --name=applicationName [-o=dest-path] [template-name] - Create a new Android project + Create a new Android project from available templates. Allows specifying + project name, output directory, minSdk, and dry-run execution. [template-name] The template name -h, --help Show this help message and exit. --minSdk=api The 'minSdk' supported by the application (default @@ -128,15 +143,17 @@ describe docs Usage: android docs [-h] [COMMAND] - Android documentation commands + Android documentation commands for searching and fetching developer + documentation from the official knowledge base. -h, --help Show this help message and exit. Commands: - search Search Android documentation - fetch Fetch Android documentation + search Search Android documentation. Enclose keywords in quotes. + fetch Fetch an Android documentation article from a URL (kb://...) emulator Usage: android emulator [-h] [COMMAND] - Emulator commands + Manage Android Virtual Devices (AVDs). Includes commands to start, stop, list, + and view details about emulators. -h, --help Show this help message and exit. Commands: create Creates a virtual device @@ -153,12 +170,33 @@ help info Usage: android info - Print environment information (SDK Location, etc.) + Print environment information including SDK location, connected devices, and + configuration variables. Use specific fields to narrow the output. The specific field to print the value of. If omitted print all. init Usage: android init - Initializes the environment (eg. skills) for Android CLI. + Initializes the environment for the Android CLI. Sets up required + configurations, directories, and default skills. + +install + Usage: android install [-hv] [--use-delta-install] [--device=PARAM] + [--apks=PARAM[,PARAM...]]... [--install-options=PARAM[, + PARAM...]]... + Install an Android Application (one or more APKs) to a connected device or + emulator without activating any components using incremental optimizations for + faster deployment than adb. + --apks=PARAM[,PARAM...] + The paths to the APKs + --device=PARAM The device serial number + -h, --help Show this help message and exit. + --install-options=PARAM[,PARAM...] + Additional options/flags to pass to package manager + install (e.g. -g,-d) + --use-delta-install Use fast delta install (speeds up incremental + updates by transferring only modified code and + resources; default: true) + -v, --verbose Enable verbose logging layout Usage: android layout [-dhp] [--device=PARAM] [-o=PARAM] @@ -173,16 +211,26 @@ layout -p, --pretty Pretty-prints the returned JSON run - Usage: android run [-h] [--debug] [--activity=PARAM] [--device=PARAM] - [--type=PARAM] [--apks=PARAM[,PARAM...]]... - Deploy an Android Application - --activity=PARAM The activity name + Usage: android run [-hv] [--debug] [--use-delta-install] [--activity=PARAM] + [--device=PARAM] [--type=PARAM] [--apks=PARAM[,PARAM...]]... + [--install-options=PARAM[,PARAM...]]... + Build, deploy, and launch an Android application on a connected device or + emulator. + --activity=PARAM The activity name --apks=PARAM[,PARAM...] - The paths to the APKs - --debug Run in debug mode - --device=PARAM The device serial number - -h, --help Show this help message and exit. - --type=PARAM The component type (ACTIVITY, SERVICE, etc.) + The paths to the APKs + --debug Run in debug mode + --device=PARAM The device serial number + -h, --help Show this help message and exit. + --install-options=PARAM[,PARAM...] + Additional options/flags to pass to package manager + install (e.g. -g,-d) + --type=PARAM The component type (ACTIVITY, WATCH_FACE, TILE, + COMPLICATION, DECLARATIVE_WATCH_FACE, WEAR_WIDGET) + --use-delta-install Use fast delta install (speeds up incremental + updates by transferring only modified code and + resources; default: false) + -v, --verbose Enable verbose logging screen Usage: android screen [-h] [COMMAND] @@ -194,21 +242,25 @@ screen sdk Usage: android sdk [COMMAND] - Download and list SDK packages + Manage the Android SDK installation. Includes commands to install, update, + remove, and list available and installed SDK packages. Commands: install Install SDK packages update Update one or all packages to the latest version - remove Remove a package from the SDK + remove Remove packages from the SDK list List installed and available SDK packages skills - Usage: android skills [COMMAND] - Manage skills + Usage: android skills [-h] [COMMAND] + Manage Android CLI skills. Includes commands to install, remove, list, and + search for skills by keyword. + -h, --help Show this help message and exit. Commands: - add Install a skill - remove Remove a skill - list List available skills - find Find skills by keyword + add [id] Install a specific skill by its ID to your environment + remove [id] Remove an installed skill by its ID + list List installed and available skills + find [keyword] Search for available skills in the repository matching a + keyword studio Usage: android studio [-h] [COMMAND] @@ -227,5 +279,6 @@ studio update Usage: android update [--url=PARAM] - Update the Android CLI + Update the Android CLI to the latest version. --url=PARAM The URL to download the update from + diff --git a/identity/verified-email/SKILL.md b/identity/verified-email/SKILL.md index 784038e..0b8b191 100644 --- a/identity/verified-email/SKILL.md +++ b/identity/verified-email/SKILL.md @@ -8,7 +8,7 @@ description: Provides a complete workflow for implementing verified email retrie license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-02' + last-updated: '2026-08-06' keywords: - implementation - Android @@ -57,15 +57,11 @@ Email verification is applicable for the following use cases: ### Scope \& Pre-requisites -**Crucial** : This skill focuses exclusively on the **Android client-side -integration** . It does **not** implement the app's server-side cryptographic -validation logic. Server-side validation of the returned credential is required -for security and must be implemented in your backend. +**Crucial** : This skill focuses exclusively on the **Android client-side integration** . It does **not** implement the app's server-side cryptographic validation logic. Server-side validation of the returned credential is required for security and must be implemented in your backend. ## Codebase exploration for Use Cases -Get started with the following queries in project source code to find relevant -screens with different use cases to implement verified email: +Get started with the following queries in project source code to find relevant screens with different use cases to implement verified email: - `SignUpScreen` - `"Email address"` @@ -76,14 +72,11 @@ screens with different use cases to implement verified email: ## Identifying Integration Points -To implement this feature effectively, you must first locate the relevant -flows in your codebase. To initiate, start with the following strategies to -cater to different use cases using verified email: +To implement this feature effectively, you must first locate the relevant flows in your codebase. To initiate, start with the following strategies to cater to different use cases using verified email: ### 1. Search for Navigation Routes -If your app uses Navigation, search for routes or destinations related -to authentication: +If your app uses Navigation, search for routes or destinations related to authentication: Look for: @@ -92,16 +85,14 @@ Look for: ### 2. Locate Authentication ViewModels -Find the business logic handling user attributes and account creation, account -recovery: +Find the business logic handling user attributes and account creation, account recovery: - **Keywords** : `SignUpViewModel`, `AuthViewModel`, `RegistrationRepository`. - **Code Pattern** : Look for methods like `onCreateAccount`, `onRecoverAccount`, or `validateEmail`. ### 3. Find instances of reauthentication for sensitive actions -For reauthentication use cases, find areas where users perform sensitive -actions: +For reauthentication use cases, find areas where users perform sensitive actions: - **Keywords** : `ChangePassword`, `UpdatePayment`, `DeleteAccount`, `UpdateDetails`, `EditUserDetails` @@ -117,21 +108,20 @@ actions: - Leave a TODO for developers to handle the app's server-side validation and parsing. - Direct users to the home screen after API call success and show a snackbar with user details for reference purpose only. -This guide describes how to implement verified email retrieval using the -[Digital Credentials Verifier API](references/android/identity/digital-credentials/credential-verifier.md) through an [OpenID for Verifiable -Presentations (OpenID4VP)](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html) request. +## Overview + +This guide describes how to implement verified email retrieval using the [Digital Credentials Verifier API](references/android/identity/digital-credentials/credential-verifier.md) through an [OpenID for Verifiable Presentations (OpenID4VP)](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html) request. ## Add dependencies -In your app's `build.gradle` file, add the following dependencies for Credential -Manager: +In your app's `build.gradle` file, add the following dependencies for Credential Manager: ### Kotlin ```kotlin dependencies { - implementation("androidx.credentials:credentials:1.7.0-alpha02") - implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha02") + implementation("androidx.credentials:credentials:1.7.0-alpha03") + implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha03") } ``` @@ -139,8 +129,8 @@ dependencies { ```groovy dependencies { - implementation "androidx.credentials:credentials:1.7.0-alpha02" - implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha02" + implementation "androidx.credentials:credentials:1.7.0-alpha03" + implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha03" } ``` @@ -154,14 +144,9 @@ Use your app or activity context to create a `CredentialManager` object. ## Construct the Digital Credential request -To request a verified email, construct a [`GetCredentialRequest`](https://developer.android.com/reference/android/credentials/GetCredentialRequest) -containing a [`GetDigitalCredentialOption`](https://developer.android.com/reference/androidx/credentials/GetDigitalCredentialOption). This option requires a -`requestJson` string formatted as an OpenID for Verifiable Presentations -(OpenID4VP) request. +To request a verified email, construct a [`GetCredentialRequest`](https://developer.android.com/reference/android/credentials/GetCredentialRequest) containing a [`GetDigitalCredentialOption`](https://developer.android.com/reference/androidx/credentials/GetDigitalCredentialOption). This option requires a `requestJson` string formatted as an OpenID for Verifiable Presentations (OpenID4VP) request. -The OpenID4VP request JSON must follow a specific structure. The current -providers support a JSON structure with an outer `"digital": {"requests": -[...]}` wrapper. +The OpenID4VP request JSON must follow a specific structure. The current providers support a JSON structure with an outer `"digital": {"requests": [...]}` wrapper. val nonce = generateSecureRandomNonce() @@ -206,26 +191,19 @@ providers support a JSON structure with an outer `"digital": {"requests": The request contains the following key information: -- **DCQL query** : The `dcql_query` specifies the credential type and the - claims being requested (`email_verified`). You can request other claims to - determine the level of verification. A few possible claims are as follows: +- **DCQL query** : The `dcql_query` specifies the credential type and the claims being requested (`email_verified`). You can request other claims to determine the level of verification. A few possible claims are as follows: - `email_verified`: In the response, this is a Boolean that indicates whether the email is verified. - `hd` (hosted domain): In the response, this is empty. > [!NOTE] - > **Note:** If `email_verified` is `true` and `hd` is empty in the response, it implies that the account is an authorized Google Account. Google does not issue [verifiable credentials](references/android/identity/digital-credentials/index.md) for Google Workspace Accounts. However, the `hd` field is present in verifiable credentials issued for non-workspace accounts. You are encouraged to implement handling this field to future-proof your app. If the email is non-@gmail.com, Google verified this email when the Google Account was created, but there is no freshness claim. Therefore, for non-Google emails, you should consider an additional challenge, such as an OTP, to verify the user. To understand the schema of the credential and the specific rules for validating fields like `email_verified`, refer to the [Google - > Identity guides](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token). + > **Note:** If `email_verified` is `true` and `hd` is empty in the response, it implies that the account is an authorized Google Account. Google does not issue [verifiable credentials](references/android/identity/digital-credentials/index.md) for Google Workspace Accounts. However, the `hd` field is present in verifiable credentials issued for non-workspace accounts. You are encouraged to implement handling this field to future-proof your app. If the email is non-@gmail.com, Google verified this email when the Google Account was created, but there is no freshness claim. Therefore, for non-Google emails, you should consider an additional challenge, such as an OTP, to verify the user. To understand the schema of the credential and the specific rules for validating fields like `email_verified`, refer to the [Google Identity guides](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token). -- **nonce**: A unique, cryptographically secure random value is generated for - each request. This is critical for security, as it prevents replay attacks. +- **nonce**: A unique, cryptographically secure random value is generated for each request. This is critical for security, as it prevents replay attacks. -- `UserInfoCredential`: This value implies a specific type of digital - credential that contains user attributes. Including this in the request is - pivotal to distinguish the email verification use case. +- `UserInfoCredential`: This value implies a specific type of digital credential that contains user attributes. Including this in the request is pivotal to distinguish the email verification use case. -Next, wrap the `openId4vpRequest` JSON in a `GetDigitalCredentialOption`, create -a `GetCredentialRequest`, and call `getCredential()`. +Next, wrap the `openId4vpRequest` JSON in a `GetDigitalCredentialOption`, create a `GetCredentialRequest`, and call `getCredential()`. > [!NOTE] > **Note:** The `hd` and `email_verified` fields are hidden from users in Credential Manager's built-in UI. You cannot make a request with only these hidden fields- in case of such requests, the response is the [`GetCredentialCancellationException`](https://developer.android.com/reference/kotlin/androidx/credentials/exceptions/GetCredentialCancellationException). @@ -261,15 +239,12 @@ Present the user with the request, using the Credential Manager built-in UI. ## Parse the response on the client -After receiving the response, you can perform a preliminary parse on the client. -This is useful for immediately updating the UI, for example, by showing the -user's name. +After receiving the response, you can perform a preliminary parse on the client. This is useful for immediately updating the UI, for example, by showing the user's name. > [!IMPORTANT] > **Important:** This step is not for validation. Full cryptographic verification must be performed on your server. -The following code extracts the raw [Selective Disclosure JWT -(SD-JWT)](https://datatracker.ietf.org/doc/rfc9901/) and uses a helper to decode its claims. +The following code extracts the raw [Selective Disclosure JWT (SD-JWT)](https://datatracker.ietf.org/doc/rfc9901/) and uses a helper to decode its claims. // 1. Parse the outer JSON wrapper to get the `vp_token` val responseData = JSONObject(responseJsonString) @@ -294,12 +269,9 @@ The following code extracts the raw [Selective Disclosure JWT ## Handle the response -The Credential Manager API will return a [`DigitalCredential`](https://developer.android.com/reference/androidx/credentials/DigitalCredential) -response. +The Credential Manager API will return a [`DigitalCredential`](https://developer.android.com/reference/androidx/credentials/DigitalCredential) response. -The following is an example of what the raw `responseJsonString` looks like, and -what the claims look like after parsing the inner SD-JWT where you get -additional metadata as well along with verified email: +The following is an example of what the raw `responseJsonString` looks like, and what the claims look like after parsing the inner SD-JWT where you get additional metadata as well along with verified email: /* // Example of the raw JSON response from credential.credentialJson: @@ -337,18 +309,11 @@ additional metadata as well along with verified email: ## Server-side validation for account creation -Since the retrieved email is cryptographically verified, you can omit the email -OTP verification step, significantly reducing sign-up friction and potentially -increasing conversion. This process is best handled on your server. The client -sends the raw response (containing the `vp_token`) and the original nonce to a -new server endpoint. +Since the retrieved email is cryptographically verified, you can omit the email OTP verification step, significantly reducing sign-up friction and potentially increasing conversion. This process is best handled on your server. The client sends the raw response (containing the `vp_token`) and the original nonce to a new server endpoint. -For verification, your application must send the full `responseJsonString` to -your server for cryptographic validation before creating an account or logging -the user in. +For verification, your application must send the full `responseJsonString` to your server for cryptographic validation before creating an account or logging the user in. -The digital credential provides two critical levels of verification for your -server: +The digital credential provides two critical levels of verification for your server: - **Authenticity of the data** : Verifying the issuer (`iss`) URL and the `SD-JWT` signature proves that a trusted authority issued this data. - **Identity of the presenter** : Verifying the `cnf` field and the Key Binding (`kb`) signature confirms that the credential is being shared by the same device it was originally issued to, preventing it from being intercepted or used on another device. @@ -359,15 +324,11 @@ The validation on the server must achieve the following: - **Verify signature**: Check the signature of the SD-JWT using the public keys (JWKs) available at https://verifiablecredentials-pa.googleapis.com/.well-known/vc-public-jwks. > [!NOTE] -> **Note:** Use a standard library (such as [@sd-jwt/sd-jwt-vc](https://datatracker.ietf.org/doc/rfc9901/) for Node.js) to perform the verification steps as outlined in the [OpenID for Verifiable -> Presentations specification](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html). +> **Note:** Use a standard library (such as [@sd-jwt/sd-jwt-vc](https://datatracker.ietf.org/doc/rfc9901/) for Node.js) to perform the verification steps as outlined in the [OpenID for Verifiable Presentations specification](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html). -For full security, make sure that you also validate the `nonce` to prevent -replay attacks. +For full security, make sure that you also validate the `nonce` to prevent replay attacks. -By combining these steps, your server can validate both the authenticity of the -data and the identity of the presenter, ensuring the credential wasn't -intercepted or spoofed before provisioning the new account. +By combining these steps, your server can validate both the authenticity of the data and the identity of the presenter, ensuring the credential wasn't intercepted or spoofed before provisioning the new account. try { // Send the raw credential response and the original nonce to your server. @@ -390,17 +351,11 @@ intercepted or spoofed before provisioning the new account. ## Passkey creation -An optional but highly recommended next step after provisioning an account is to -immediately [create a passkey](references/android/identity/passkeys/create-passkeys.md) for that account. This provides a secure, -passwordless method for the user to sign in. This flow is identical to a -standard passkey registration. +An optional but highly recommended next step after provisioning an account is to immediately [create a passkey](references/android/identity/passkeys/create-passkeys.md) for that account. This provides a secure, passwordless method for the user to sign in. This flow is identical to a standard passkey registration. ## WebView support -For the flow to work on a [`WebView`](https://developer.android.com/reference/android/webkit/WebView), developers should implement a -[JavaScript bridge](references/android/identity/sign-in/credential-manager-webview.md) (JS Bridge) to facilitate the handoff. This bridge -allows the `WebView` object to signal the native app, which can then perform the -actual call to the Credential Manager API. +For the flow to work on a [`WebView`](https://developer.android.com/reference/android/webkit/WebView), developers should implement a [JavaScript bridge](references/android/identity/sign-in/credential-manager-webview.md) (JS Bridge) to facilitate the handoff. This bridge allows the `WebView` object to signal the native app, which can then perform the actual call to the Credential Manager API. ## See also @@ -409,8 +364,7 @@ actual call to the Credential Manager API. ## Critical Security Guidelines -To maintain the integrity of the email verification flow, the following security -requirements are mandatory: +To maintain the integrity of the email verification flow, the following security requirements are mandatory: - **Server-side Validation** : Never trust claims parsed on the client for security-sensitive operations like account creation. Send the complete, raw `responseJsonString` and the original `nonce` to the app's server for full verification. - **Nonce Integrity** : Generate a unique, cryptographically secure nonce for every request and **never** reuse a nonce across multiple requests to prevent replay attacks. diff --git a/identity/verified-email/references/android/identity/credential-manager/index.md b/identity/verified-email/references/android/identity/credential-manager/index.md index c646f19..d11d29b 100644 --- a/identity/verified-email/references/android/identity/credential-manager/index.md +++ b/identity/verified-email/references/android/identity/credential-manager/index.md @@ -1,21 +1,15 @@ -[Credential Manager](https://developer.android.com/reference/kotlin/androidx/credentials/package-summary) is the recommended Jetpack API for credential exchange -in Android apps. The Credential Manager API streamlines credential exchange -across form factors for use cases spanning authentication and authorization. You -can also use Credential Manager to handle digital credentials and restore user -credentials on new Android devices. +[Credential Manager](https://developer.android.com/reference/kotlin/androidx/credentials/package-summary) is the recommended Jetpack API for credential exchange in Android apps. The Credential Manager API streamlines credential exchange across form factors for use cases spanning authentication and authorization. You can also use Credential Manager to handle digital credentials and restore user credentials on new Android devices. ## Credential Manager features -Credential Manager streamlines the sign-in process and enhances security by -offering a robust set of capabilities, including: +Credential Manager streamlines the sign-in process and enhances security by offering a robust set of capabilities, including: - **Support for various authentication mechanisms** : Enables users to sign up or sign in to your app using: - [Passkeys](https://developer.android.com/identity/passkeys) - [Sign-in with Google](https://developer.android.com/identity/sign-in/credential-manager-siwg) and other federated sign-in mechanisms - [Passwords](https://developer.android.com/identity/passwords) - [Digital credentials](https://developer.android.com/identity/digital-credentials) -- **Cross-device credential restore** : Provides integration with [Restore - Credentials](https://developer.android.com/identity/sign-in/restore-credentials), allowing users to seamlessly start using your app on a new device. +- **Cross-device credential restore** : Provides integration with [Restore Credentials](https://developer.android.com/identity/sign-in/restore-credentials), allowing users to seamlessly start using your app on a new device. - **Seamless integration with credential providers** : Offers support for [credential providers](https://developer.android.com/identity/sign-in/credential-provider), including password managers such as Google Password Manager. - **Credential management**: Enables updating the metadata for user credentials, helping to keep credentials consistent across your app and credential providers. - **WebView compatibility** : Works with apps that use [WebView](https://developer.android.com/identity/sign-in/credential-manager-webview). @@ -23,12 +17,10 @@ offering a robust set of capabilities, including: ## Benefits of using Credential Manager -Adopting Credential Manager provides several key advantages for both your -application and your users: +Adopting Credential Manager provides several key advantages for both your application and your users: - **Enhanced security**: Passkeys offer enhanced security and protect users from phishing attempts. -- **Support for various form factors** : The APIs work across Android [form - factors](https://developer.android.com/identity/form-factors), including mobile, Android XR, and Wear OS devices. +- **Support for various form factors** : The APIs work across Android [form factors](https://developer.android.com/identity/form-factors), including mobile, Android XR, and Wear OS devices. - **Simplified authentication across use cases** : [Digital credentials](https://developer.android.com/identity/digital-credentials), such as digital driver's licenses, corporate IDs, and national ID cards, enable authentication across various use cases, including those requiring [phone number verification](https://developer.android.com/identity/digital-credentials/phone-number-verification). - **Improved user experience**: Credential Manager's unified interface gives users a familiar and consistent experience and improves registration and sign-in speeds. The bottom sheet UI appears inline to your app's content, so your users remain within your app's context during sign-in. The following image shows Credential Manager's built-in UI: @@ -36,8 +28,7 @@ application and your users: ## Authentication terminology -An entity that requires authentication for its users is known as a **relying -party**. An authentication workflow typically includes the following components: +An entity that requires authentication for its users is known as a **relying party**. An authentication workflow typically includes the following components: - **Relying party client app**: The client---in this case, your Android app---that handles the user interface to create and use passkeys. - **Relying party server**: An app server that helps with the creation, storage, and verification of passkeys. @@ -45,21 +36,13 @@ party**. An authentication workflow typically includes the following components: ## Credential storage -Credential providers, such as Google Password Manager, provide a centralized and -secure location for users to manage credentials across their devices, further -simplifying the authentication process. To integrate with Credential Manager as -a credential provider, see -[Implement authentication as a credential provider](https://developer.android.com/identity/sign-in/credential-provider). +Credential providers, such as Google Password Manager, provide a centralized and secure location for users to manage credentials across their devices, further simplifying the authentication process. To integrate with Credential Manager as a credential provider, see [Implement authentication as a credential provider](https://developer.android.com/identity/sign-in/credential-provider). -For more information about how Google Password Manager keeps your credentials -secure, see -[Security of Passkeys in the Google Password Manager](https://security.googleblog.com/2022/10/SecurityofPasskeysintheGooglePasswordManager.html). +For more information about how Google Password Manager keeps your credentials secure, see [Security of Passkeys in the Google Password Manager](https://security.googleblog.com/2022/10/SecurityofPasskeysintheGooglePasswordManager.html). ## Migrate to Credential Manager -Credential Manager is intended to replace legacy Android authentication APIs and -local FIDO2 credentials. For more information about migrating to Credential -Manager, see the following guides: +Credential Manager is intended to replace legacy Android authentication APIs and local FIDO2 credentials. For more information about migrating to Credential Manager, see the following guides: - [Google Sign-In](https://developer.android.com/identity/sign-in/legacy-gsi-migration) - [One Tap](https://developer.android.com/identity/legacy/one-tap) diff --git a/identity/verified-email/references/android/identity/digital-credentials/credential-verifier.md b/identity/verified-email/references/android/identity/digital-credentials/credential-verifier.md index 3f7f9c9..082ada7 100644 --- a/identity/verified-email/references/android/identity/digital-credentials/credential-verifier.md +++ b/identity/verified-email/references/android/identity/digital-credentials/credential-verifier.md @@ -1,14 +1,6 @@ -Digital credential verification within Android apps can be used to authenticate -and authorize a user's identity (such as a government ID), properties about that -user (such as a driver's license, academic degree, or attributes such as age or -address), or other scenarios where a credential needs to be issued and verified -to assert the authenticity of an entity. +Digital credential verification within Android apps can be used to authenticate and authorize a user's identity (such as a government ID), properties about that user (such as a driver's license, academic degree, or attributes such as age or address), or other scenarios where a credential needs to be issued and verified to assert the authenticity of an entity. -Digital Credentials is a public W3C standard that specifies how to access a -user's verifiable digital credentials from a digital wallet, and is implemented -for web use cases with the [W3C Credential Management API](https://www.w3.org/TR/credential-management-1/). On -Android, Credential Manager's [`DigitalCredential`](https://developer.android.com/reference/kotlin/androidx/credentials/DigitalCredential) API is used for -verifying digital credentials. +Digital Credentials is a public W3C standard that specifies how to access a user's verifiable digital credentials from a digital wallet, and is implemented for web use cases with the [W3C Credential Management API](https://www.w3.org/TR/credential-management-1/). On Android, Credential Manager's [`DigitalCredential`](https://developer.android.com/reference/kotlin/androidx/credentials/DigitalCredential) API is used for verifying digital credentials. ### Android version compatibility @@ -37,8 +29,7 @@ Next, Initialize an instance of the `CredentialManager` class. #### Construct a digital credential request -Construct a digital credential request and use it to initialize a -`DigitalCredentialOption`. +Construct a digital credential request and use it to initialize a `DigitalCredentialOption`. // The request in the JSON format to conform with // the JSON-ified Credential Manager - Verifier API request definition. @@ -51,8 +42,7 @@ Construct a digital credential request and use it to initialize a listOf(digitalCredentialOption) ) -Here is an example of an OpenId4Vp request. A full reference can be found at -this [website](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html). +Here is an example of an OpenId4Vp request. A full reference can be found at this [website](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html). { "requests": [ @@ -100,14 +90,9 @@ this [website](https://openid.net/specs/openid-4-verifiable-presentations-1_0.ht #### Get the credential -Launch the `getCredential` flow with the constructed request. You will receive -either a successful `GetCredentialResponse`, or a `GetCredentialException` if -the request fails. +Launch the `getCredential` flow with the constructed request. You will receive either a successful `GetCredentialResponse`, or a `GetCredentialException` if the request fails. -The `getCredential` flow triggers Android system dialogs to present the user's -available credential options and collect their selection. Next, the wallet app -that contains the chosen credential option will display UIs to collect consent -and perform actions needed to generate a digital credential response. +The `getCredential` flow triggers Android system dialogs to present the user's available credential options and collect their selection. Next, the wallet app that contains the chosen credential option will display UIs to collect consent and perform actions needed to generate a digital credential response. coroutineScope.launch { try { diff --git a/identity/verified-email/references/android/identity/digital-credentials/email-verification-implementation.md b/identity/verified-email/references/android/identity/digital-credentials/email-verification-implementation.md index 9305e92..048f11b 100644 --- a/identity/verified-email/references/android/identity/digital-credentials/email-verification-implementation.md +++ b/identity/verified-email/references/android/identity/digital-credentials/email-verification-implementation.md @@ -1,22 +1,31 @@ -> [!IMPORTANT] -> **Important:** We released an agent skill to help you implement email verification with the Digital Credentials API. Try out the skill from the [Android skills -> repository](https://github.com/android/skills). +
-This guide describes how to implement verified email retrieval using the -[Digital Credentials Verifier API](https://developer.android.com/identity/digital-credentials/credential-verifier) through an [OpenID for Verifiable -Presentations (OpenID4VP)](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html) request. +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/identity/verified-email) + +### Retrieve verified email + +Use an Android skill to integrate a secure, OTP-less email verification flow into your app. To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill verified-email + +
+ +## Overview + +This guide describes how to implement verified email retrieval using the [Digital Credentials Verifier API](https://developer.android.com/identity/digital-credentials/credential-verifier) through an [OpenID for Verifiable Presentations (OpenID4VP)](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html) request. ## Add dependencies -In your app's `build.gradle` file, add the following dependencies for Credential -Manager: +In your app's `build.gradle` file, add the following dependencies for Credential Manager: ### Kotlin ```kotlin dependencies { - implementation("androidx.credentials:credentials:1.7.0-alpha02") - implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha02") + implementation("androidx.credentials:credentials:1.7.0-alpha03") + implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha03") } ``` @@ -24,8 +33,8 @@ dependencies { ```groovy dependencies { - implementation "androidx.credentials:credentials:1.7.0-alpha02" - implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha02" + implementation "androidx.credentials:credentials:1.7.0-alpha03" + implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha03" } ``` @@ -39,14 +48,9 @@ Use your app or activity context to create a `CredentialManager` object. ## Construct the Digital Credential request -To request a verified email, construct a [`GetCredentialRequest`](https://developer.android.com/reference/android/credentials/GetCredentialRequest) -containing a [`GetDigitalCredentialOption`](https://developer.android.com/reference/androidx/credentials/GetDigitalCredentialOption). This option requires a -`requestJson` string formatted as an OpenID for Verifiable Presentations -(OpenID4VP) request. +To request a verified email, construct a [`GetCredentialRequest`](https://developer.android.com/reference/android/credentials/GetCredentialRequest) containing a [`GetDigitalCredentialOption`](https://developer.android.com/reference/androidx/credentials/GetDigitalCredentialOption). This option requires a `requestJson` string formatted as an OpenID for Verifiable Presentations (OpenID4VP) request. -The OpenID4VP request JSON must follow a specific structure. The current -providers support a JSON structure with an outer `"digital": {"requests": -[...]}` wrapper. +The OpenID4VP request JSON must follow a specific structure. The current providers support a JSON structure with an outer `"digital": {"requests": [...]}` wrapper. val nonce = generateSecureRandomNonce() @@ -91,26 +95,19 @@ providers support a JSON structure with an outer `"digital": {"requests": The request contains the following key information: -- **DCQL query** : The `dcql_query` specifies the credential type and the - claims being requested (`email_verified`). You can request other claims to - determine the level of verification. A few possible claims are as follows: +- **DCQL query** : The `dcql_query` specifies the credential type and the claims being requested (`email_verified`). You can request other claims to determine the level of verification. A few possible claims are as follows: - `email_verified`: In the response, this is a Boolean that indicates whether the email is verified. - `hd` (hosted domain): In the response, this is empty. > [!NOTE] - > **Note:** If `email_verified` is `true` and `hd` is empty in the response, it implies that the account is an authorized Google Account. Google does not issue [verifiable credentials](https://developer.android.com/identity/digital-credentials#verifiable-credentials) for Google Workspace Accounts. However, the `hd` field is present in verifiable credentials issued for non-workspace accounts. You are encouraged to implement handling this field to future-proof your app. If the email is non-@gmail.com, Google verified this email when the Google Account was created, but there is no freshness claim. Therefore, for non-Google emails, you should consider an additional challenge, such as an OTP, to verify the user. To understand the schema of the credential and the specific rules for validating fields like `email_verified`, refer to the [Google - > Identity guides](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token). + > **Note:** If `email_verified` is `true` and `hd` is empty in the response, it implies that the account is an authorized Google Account. Google does not issue [verifiable credentials](https://developer.android.com/identity/digital-credentials#verifiable-credentials) for Google Workspace Accounts. However, the `hd` field is present in verifiable credentials issued for non-workspace accounts. You are encouraged to implement handling this field to future-proof your app. If the email is non-@gmail.com, Google verified this email when the Google Account was created, but there is no freshness claim. Therefore, for non-Google emails, you should consider an additional challenge, such as an OTP, to verify the user. To understand the schema of the credential and the specific rules for validating fields like `email_verified`, refer to the [Google Identity guides](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token). -- **nonce**: A unique, cryptographically secure random value is generated for - each request. This is critical for security, as it prevents replay attacks. +- **nonce**: A unique, cryptographically secure random value is generated for each request. This is critical for security, as it prevents replay attacks. -- `UserInfoCredential`: This value implies a specific type of digital - credential that contains user attributes. Including this in the request is - pivotal to distinguish the email verification use case. +- `UserInfoCredential`: This value implies a specific type of digital credential that contains user attributes. Including this in the request is pivotal to distinguish the email verification use case. -Next, wrap the `openId4vpRequest` JSON in a `GetDigitalCredentialOption`, create -a `GetCredentialRequest`, and call `getCredential()`. +Next, wrap the `openId4vpRequest` JSON in a `GetDigitalCredentialOption`, create a `GetCredentialRequest`, and call `getCredential()`. > [!NOTE] > **Note:** The `hd` and `email_verified` fields are hidden from users in Credential Manager's built-in UI. You cannot make a request with only these hidden fields- in case of such requests, the response is the [`GetCredentialCancellationException`](https://developer.android.com/reference/kotlin/androidx/credentials/exceptions/GetCredentialCancellationException). @@ -146,15 +143,12 @@ Present the user with the request, using the Credential Manager built-in UI. ## Parse the response on the client -After receiving the response, you can perform a preliminary parse on the client. -This is useful for immediately updating the UI, for example, by showing the -user's name. +After receiving the response, you can perform a preliminary parse on the client. This is useful for immediately updating the UI, for example, by showing the user's name. > [!IMPORTANT] > **Important:** This step is not for validation. Full cryptographic verification must be performed on your server. -The following code extracts the raw [Selective Disclosure JWT -(SD-JWT)](https://datatracker.ietf.org/doc/rfc9901/) and uses a helper to decode its claims. +The following code extracts the raw [Selective Disclosure JWT (SD-JWT)](https://datatracker.ietf.org/doc/rfc9901/) and uses a helper to decode its claims. // 1. Parse the outer JSON wrapper to get the `vp_token` val responseData = JSONObject(responseJsonString) @@ -179,12 +173,9 @@ The following code extracts the raw [Selective Disclosure JWT ## Handle the response -The Credential Manager API will return a [`DigitalCredential`](https://developer.android.com/reference/androidx/credentials/DigitalCredential) -response. +The Credential Manager API will return a [`DigitalCredential`](https://developer.android.com/reference/androidx/credentials/DigitalCredential) response. -The following is an example of what the raw `responseJsonString` looks like, and -what the claims look like after parsing the inner SD-JWT where you get -additional metadata as well along with verified email: +The following is an example of what the raw `responseJsonString` looks like, and what the claims look like after parsing the inner SD-JWT where you get additional metadata as well along with verified email: /* // Example of the raw JSON response from credential.credentialJson: @@ -222,18 +213,11 @@ additional metadata as well along with verified email: ## Server-side validation for account creation -Since the retrieved email is cryptographically verified, you can omit the email -OTP verification step, significantly reducing sign-up friction and potentially -increasing conversion. This process is best handled on your server. The client -sends the raw response (containing the `vp_token`) and the original nonce to a -new server endpoint. +Since the retrieved email is cryptographically verified, you can omit the email OTP verification step, significantly reducing sign-up friction and potentially increasing conversion. This process is best handled on your server. The client sends the raw response (containing the `vp_token`) and the original nonce to a new server endpoint. -For verification, your application must send the full `responseJsonString` to -your server for cryptographic validation before creating an account or logging -the user in. +For verification, your application must send the full `responseJsonString` to your server for cryptographic validation before creating an account or logging the user in. -The digital credential provides two critical levels of verification for your -server: +The digital credential provides two critical levels of verification for your server: - **Authenticity of the data** : Verifying the issuer (`iss`) URL and the `SD-JWT` signature proves that a trusted authority issued this data. - **Identity of the presenter** : Verifying the `cnf` field and the Key Binding (`kb`) signature confirms that the credential is being shared by the same device it was originally issued to, preventing it from being intercepted or used on another device. @@ -244,15 +228,11 @@ The validation on the server must achieve the following: - **Verify signature**: Check the signature of the SD-JWT using the public keys (JWKs) available at https://verifiablecredentials-pa.googleapis.com/.well-known/vc-public-jwks. > [!NOTE] -> **Note:** Use a standard library (such as [@sd-jwt/sd-jwt-vc](https://datatracker.ietf.org/doc/rfc9901/) for Node.js) to perform the verification steps as outlined in the [OpenID for Verifiable -> Presentations specification](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html). +> **Note:** Use a standard library (such as [@sd-jwt/sd-jwt-vc](https://datatracker.ietf.org/doc/rfc9901/) for Node.js) to perform the verification steps as outlined in the [OpenID for Verifiable Presentations specification](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html). -For full security, make sure that you also validate the `nonce` to prevent -replay attacks. +For full security, make sure that you also validate the `nonce` to prevent replay attacks. -By combining these steps, your server can validate both the authenticity of the -data and the identity of the presenter, ensuring the credential wasn't -intercepted or spoofed before provisioning the new account. +By combining these steps, your server can validate both the authenticity of the data and the identity of the presenter, ensuring the credential wasn't intercepted or spoofed before provisioning the new account. try { // Send the raw credential response and the original nonce to your server. @@ -275,17 +255,11 @@ intercepted or spoofed before provisioning the new account. ## Passkey creation -An optional but highly recommended next step after provisioning an account is to -immediately [create a passkey](https://developer.android.com/identity/passkeys/create-passkeys) for that account. This provides a secure, -passwordless method for the user to sign in. This flow is identical to a -standard passkey registration. +An optional but highly recommended next step after provisioning an account is to immediately [create a passkey](https://developer.android.com/identity/passkeys/create-passkeys) for that account. This provides a secure, passwordless method for the user to sign in. This flow is identical to a standard passkey registration. ## WebView support -For the flow to work on a [`WebView`](https://developer.android.com/reference/android/webkit/WebView), developers should implement a -[JavaScript bridge](https://developer.android.com/identity/sign-in/credential-manager-webview) (JS Bridge) to facilitate the handoff. This bridge -allows the `WebView` object to signal the native app, which can then perform the -actual call to the Credential Manager API. +For the flow to work on a [`WebView`](https://developer.android.com/reference/android/webkit/WebView), developers should implement a [JavaScript bridge](https://developer.android.com/identity/sign-in/credential-manager-webview) (JS Bridge) to facilitate the handoff. This bridge allows the `WebView` object to signal the native app, which can then perform the actual call to the Credential Manager API. ## See also diff --git a/identity/verified-email/references/android/identity/digital-credentials/email-verification.md b/identity/verified-email/references/android/identity/digital-credentials/email-verification.md index 2134577..66a5f1a 100644 --- a/identity/verified-email/references/android/identity/digital-credentials/email-verification.md +++ b/identity/verified-email/references/android/identity/digital-credentials/email-verification.md @@ -1,7 +1,4 @@ -This document describes using Credential Manager to get a cryptographically -verified email address from a user's device. This process removes the need for -your app users to verify their email with one-time passwords (OTPs) or magic -links. +This document describes using Credential Manager to get a cryptographically verified email address from a user's device. This process removes the need for your app users to verify their email with one-time passwords (OTPs) or magic links. This document explains the following areas: @@ -19,90 +16,66 @@ This guide assumes you are familiar with the following concepts: ## Android compatibility -This feature is supported on mobiles, tablets, and foldable devices running -Android 9 (API level 28) and higher. The minimum version of Google Play services -(GMS) required is 25.49.x. +This feature is supported on mobiles, tablets, and foldable devices running Android 9 (API level 28) and higher. The minimum version of Google Play services (GMS) required is 25.49.x. ## User experience -The following sections describe the user experience during the verification -flow, the need to include fallback verification methods, as well as the -recommended user experience for various use cases. +The following sections describe the user experience during the verification flow, the need to include fallback verification methods, as well as the recommended user experience for various use cases. ### The verification flow The user experience for sharing a verified email is as follows: -1. The user either focuses on an input field or taps a button that calls the - Credential Manager API. Depending on the design of the screen, you can also - call the API on your app's screen load. +1. The user either focuses on an input field or taps a button that calls the Credential Manager API. Depending on the design of the screen, you can also call the API on your app's screen load. -2. A bottom sheet appears, showing the information that will be shared with the - app. If no information is available on that device, the user sees a generic - error message. +2. A bottom sheet appears, showing the information that will be shared with the app. If no information is available on that device, the user sees a generic error message. -3. After the user taps **Agree and Continue**, display a success or failure - message. +3. After the user taps **Agree and Continue**, display a success or failure message. > [!NOTE] > **Note:** If the verified email you receive does not match what you expect, inform the user about the mismatch and either ask them to try again with a different credential or provide an alternate verification method, such as through OTPs. -4. (Optional, recommended) If the user is signing up for your service, you - should prompt the user to [create](https://developer.android.com/identity/passkeys/create-passkeys) a [passkey](https://developer.android.com/identity/passkeys) to make it easier for - them to sign in subsequently. +4. (Optional, recommended) If the user is signing up for your service, you should prompt the user to [create](https://developer.android.com/identity/passkeys/create-passkeys) a [passkey](https://developer.android.com/identity/passkeys) to make it easier for them to sign in subsequently. > [!NOTE] > **Note:** The email verification process doesn't automatically trigger passkey creation. However, it is highly recommended to include the steps for passkey creation. Passkeys help users by making it easier and more secure for them to sign in, and remove the need for the conventional username and password interaction. ### Include primary and fallback flows -To ensure a streamlined user experience, include the following options on -screens that require email verification: +To ensure a streamlined user experience, include the following options on screens that require email verification: - **Primary verification option**: An email field or button to trigger the Credential Manager API flow for quick verification. - **Alternate verification options**: A link or button for users to "Verify another way" or with "Other options" for manual email entry in case of failures, such as no information available on the device, or a mismatch between the retrieved and expected email. This should allow users to try verification with a different credential or by providing a manual OTP. ### Use cases -The following sections describe the recommended use cases, as well as the -suggested user experience, for email verification. +The following sections describe the recommended use cases, as well as the suggested user experience, for email verification. #### Sign up -Users can immediately create an account with a verified email without a separate -verification step. Optionally, prompt the user to add a passkey. If they opt to -add a passkey, trigger the [passkey creation](https://developer.android.com/identity/passkeys/create-passkeys) flow. +Users can immediately create an account with a verified email without a separate verification step. Optionally, prompt the user to add a passkey. If they opt to add a passkey, trigger the [passkey creation](https://developer.android.com/identity/passkeys/create-passkeys) flow. ![Using email verification during sign up, and then creating passkeys](https://developer.android.com/static/identity/digital-credentials/images/signup_ux.png) Email verification during sign up #### Account recovery -To eliminate the frustration of users searching for recovery codes in their spam -folders, allow them to recover their account using the verified email securely -stored on their device. Additionally, suggest that they create a passkey for -future use. +To eliminate the frustration of users searching for recovery codes in their spam folders, allow them to recover their account using the verified email securely stored on their device. Additionally, suggest that they create a passkey for future use. ![Using email verification during account recovery](https://developer.android.com/static/identity/digital-credentials/images/account_recovery_ux.png) Email verification during account recovery #### Reauthentication for sensitive actions -Protect sensitive user actions, such as changing settings or updating profile -details, by requiring a quick reauthentication step. +Protect sensitive user actions, such as changing settings or updating profile details, by requiring a quick reauthentication step. ![Using email verification during reauthentication](https://developer.android.com/static/identity/digital-credentials/images/reauthentication_ux.png) Email verification during reauthentication ## Accounts supported -Email verification through Credential Manager only supports verification of -consumer Google Accounts. [Workspace accounts](https://knowledge.workspace.google.com/admin/getting-started/set-up-google-workspace-for-your-organization) and [supervised -accounts](https://support.google.com/families/answer/9499054) are not supported. +Email verification through Credential Manager only supports verification of consumer Google Accounts. [Workspace accounts](https://knowledge.workspace.google.com/admin/getting-started/set-up-google-workspace-for-your-organization) and [supervised accounts](https://support.google.com/families/answer/9499054) are not supported. -A consumer Google Account can be created with an email address from any -provider, not necessarily @gmail.com. However, Google verifies these accounts -differently: +A consumer Google Account can be created with an email address from any provider, not necessarily @gmail.com. However, Google verifies these accounts differently: - For @gmail.com accounts: Google is the authoritative source, and the email is known to be verified. - For non-@gmail.com accounts: Google is not the authoritative source for these email addresses in the long term. While Google verifies the email when the account is created, the ownership of that email address might change over time. Therefore, for non-@gmail.com addresses, you should consider an additional verification step, such as sending an OTP, to ensure that the user still has access to the email account. -For more information about what verification implies, see [Digital -Credentials](https://developer.android.com/identity/digital-credentials#verified). +For more information about what verification implies, see [Digital Credentials](https://developer.android.com/identity/digital-credentials#verified). > [!NOTE] > **Note:** Apart from a user's email information, you can request other unverified fields, such as the user's given name, family name, name, and the profile picture of their Google Account. However, only the email is verified by Google. @@ -110,30 +83,19 @@ Credentials](https://developer.android.com/identity/digital-credentials#verified ## Validity and freshness -The system issues [verifiable credentials](https://developer.android.com/identity/digital-credentials#verified) (VCs) based on the user's current -email from the active Google Accounts on the device. These credentials are -issued to the device in advance, typically while the device is idle. While these -credentials might remain valid for multiple days, the system performs a check at -the moment of sharing the credentials to ensure that the account still exists, -is on the device, and that the email address is valid---effectively prioritizing -the account's immediate status over the credential's validity window. +The system issues [verifiable credentials](https://developer.android.com/identity/digital-credentials#verified) (VCs) based on the user's current email from the active Google Accounts on the device. These credentials are issued to the device in advance, typically while the device is idle. While these credentials might remain valid for multiple days, the system performs a check at the moment of sharing the credentials to ensure that the account still exists, is on the device, and that the email address is valid---effectively prioritizing the account's immediate status over the credential's validity window. -To help ensure authenticity, a Key Binding (kb) signature is generated at the -time of sharing, incorporating the nonce. +To help ensure authenticity, a Key Binding (kb) signature is generated at the time of sharing, incorporating the nonce. -If a device is offline or the account is removed, the process fails rather than -providing an expired VC or a VC for an inactive Google Account. +If a device is offline or the account is removed, the process fails rather than providing an expired VC or a VC for an inactive Google Account. ### Email deliverability -While the process confirms the account's legitimacy, it does not guarantee inbox -delivery (for instance, the email might be diverted to spam). An OTP remains the -definitive method for confirming email deliverability. +While the process confirms the account's legitimacy, it does not guarantee inbox delivery (for instance, the email might be diverted to spam). An OTP remains the definitive method for confirming email deliverability. ## Comparison with Sign in with Google -While both Digital Credentials and [Sign in with Google](https://developer.android.com/identity/sign-in/credential-manager-siwg) solutions provide a -verified email, the user flows and use cases are different: +While both Digital Credentials and [Sign in with Google](https://developer.android.com/identity/sign-in/credential-manager-siwg) solutions provide a verified email, the user flows and use cases are different: - **Use cases**: The Credential Manager email verification flow is not exclusively used in sign up or sign in use cases, but rather can be used in any use case involving the retrieval of verified email. This could include account recovery as well. - **Registration**: The Credential Manager flow does not require Google registration, unlike Sign in with Google. diff --git a/identity/verified-email/references/android/identity/digital-credentials/index.md b/identity/verified-email/references/android/identity/digital-credentials/index.md index 5f9ca67..0663d39 100644 --- a/identity/verified-email/references/android/identity/digital-credentials/index.md +++ b/identity/verified-email/references/android/identity/digital-credentials/index.md @@ -1,32 +1,20 @@ -Digital credentials are cryptographically verifiable documents that can be used -to authenticate, authorize, or otherwise provide information about a user. These -are typically things such as mobile driver's licenses, digital passports, -boarding passes, etc. They reside in virtual containers called digital wallets, -and are part of a W3C standard that specifies how to access and retrieve them. -This standard is implemented for web use cases with the [W3C Credential -Management API](https://www.w3.org/TR/credential-management-1/) and on Android, with Credential Manager's -[DigitalCredential API](https://developer.android.com/reference/kotlin/androidx/credentials/DigitalCredential). +Digital credentials are cryptographically verifiable documents that can be used to authenticate, authorize, or otherwise provide information about a user. These are typically things such as mobile driver's licenses, digital passports, boarding passes, etc. They reside in virtual containers called digital wallets, and are part of a W3C standard that specifies how to access and retrieve them. This standard is implemented for web use cases with the [W3C Credential Management API](https://www.w3.org/TR/credential-management-1/) and on Android, with Credential Manager's [DigitalCredential API](https://developer.android.com/reference/kotlin/androidx/credentials/DigitalCredential). ## Understand digital credentials -In the physical world, a person might keep their identity in their wallet, and -present it to a requesting party when asked: +In the physical world, a person might keep their identity in their wallet, and present it to a requesting party when asked: ![Image showing the flow of a normal wallet interaction](https://developer.android.com/static/identity/digital-credentials/images/normal_wallet_flowchart.svg) **Figure 1.** The process of fulfilling a physical-world credential request. The requestor asks the user for a specific credential. Then, the user selects and retrieves it from their physical wallet. Finally, the user provides the credential to the requestor. -In this case, a user generally has a single wallet, and retrieves the requested -credentials from the wallet to present to the requestor. Wallets are mostly -interchangeable, and can generally store the same things. +In this case, a user generally has a single wallet, and retrieves the requested credentials from the wallet to present to the requestor. Wallets are mostly interchangeable, and can generally store the same things. -Digital credentials have the following differences from credentials in the -physical world: +Digital credentials have the following differences from credentials in the physical world: 1. Users are expected to have multiple wallets - also known as **holders** - which can contain various different credentials. Wallets determine which credentials may be stored inside of them. 2. The app or service asking for the credential to grant access or verify an identity is called the **verifier**. 3. The entity that creates the credential and asserts claims about the subject (such as, a university, a government, or a tech company) is referred to as the **issuer**. 4. The credential presentation happens in software, which means an API surface retrieves and presents the credentials - in Android, this is Credential Manager. -As such, Credential Manager takes on several roles that were formerly handled by -the user: +As such, Credential Manager takes on several roles that were formerly handled by the user: 1. On Android, wallets must register their credentials metadata with Credential Manager to be listed in the Credential Manager UI. 2. Credential Manager matches credentials across wallets based on the request and presents a list for the user to select. @@ -37,52 +25,32 @@ This flow is shown here: ## Verifiable credentials -Verifiable credentials are a subset of digital credentials governed by strict -standards (like the W3C Verifiable Credentials Data Model). These credentials -contain claims that are cryptographically secured, making them tamper-evident -and proving exactly who issued them. +Verifiable credentials are a subset of digital credentials governed by strict standards (like the W3C Verifiable Credentials Data Model). These credentials contain claims that are cryptographically secured, making them tamper-evident and proving exactly who issued them. -Not all digital credentials are verifiable credentials, but all verifiable -credentials are digital credentials. +Not all digital credentials are verifiable credentials, but all verifiable credentials are digital credentials. ## What it means for a claim to be verified -When a credential arrives through the Android Credential Manager API and a claim -within it is marked as "verified," it implies that the issuer is asserting that -they performed a check on that specific piece of data. However, it does not mean -the data is an absolute, universal truth. "Verified" is an assertion of process, -not an automatic guarantee of trust. +When a credential arrives through the Android Credential Manager API and a claim within it is marked as "verified," it implies that the issuer is asserting that they performed a check on that specific piece of data. However, it does not mean the data is an absolute, universal truth. "Verified" is an assertion of process, not an automatic guarantee of trust. -The core philosophy of this ecosystem is that trust is always resolved at the -verifier. When the verifier (your app) receives the cryptographically secure -data, and sees that the issuer marked it as "verified," it must determine -whether it trusts the issuer to have verified the claim to its standards. +The core philosophy of this ecosystem is that trust is always resolved at the verifier. When the verifier (your app) receives the cryptographically secure data, and sees that the issuer marked it as "verified," it must determine whether it trusts the issuer to have verified the claim to its standards. ### User experience -As shown in the Android flow, the user only needs to interact once with the -Credential Manager UI to select the appropriate credential. Here is an example -of how the selector looks: +As shown in the Android flow, the user only needs to interact once with the Credential Manager UI to select the appropriate credential. Here is an example of how the selector looks: ![Image showing the digital credentials UI in Credential Manager](https://developer.android.com/static/identity/digital-credentials/images/digital_credentials_ui.png) **Figure 3.** The digital credentials UI. ### Standards -Digital credentials requests are created using the [OpenID4VP -standard](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#name-introduction). You can see example requests at the [Digital -Credentials Demo site](https://digital-credentials.dev/). +Digital credentials requests are created using the [OpenID4VP standard](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#name-introduction). You can see example requests at the [Digital Credentials Demo site](https://digital-credentials.dev/). -Digital credential responses are typically returned in a standardized credential -format. These are maintained by different standards bodies, and include [W3C -Verifiable Credentials](https://www.w3.org/TR/vc-data-model-2.0/), [sd-jwt](https://datatracker.ietf.org/doc/draft-ietf-oauth-selective-disclosure-jwt/), and -[mdoc](https://www.iso.org/standard/69084.html). +Digital credential responses are typically returned in a standardized credential format. These are maintained by different standards bodies, and include [W3C Verifiable Credentials](https://www.w3.org/TR/vc-data-model-2.0/), [sd-jwt](https://datatracker.ietf.org/doc/draft-ietf-oauth-selective-disclosure-jwt/), and [mdoc](https://www.iso.org/standard/69084.html). -Custom protocols are also feasible, though we recommend using one of the -standard protocols in your application. +Custom protocols are also feasible, though we recommend using one of the standard protocols in your application. ### Try it out -You can test out the digital credentials flow across platforms with an Android -wallet and web-based verifier: +You can test out the digital credentials flow across platforms with an Android wallet and web-based verifier: 1. Install the [CMWallet public sample](https://github.com/digitalcredentialsdev/CMWallet) on your Android phone. You can do this by pulling from the repository and installing directly from Android Studio or navigating to and selecting the latest build to access the latest `app-debug.apk` file. 2. Open the CMWallet to register the metadata with Credential Manager. Make sure Bluetooth is enabled to allow your devices to connect to each other. diff --git a/identity/verified-email/references/android/identity/passkeys/create-passkeys.md b/identity/verified-email/references/android/identity/passkeys/create-passkeys.md index bfe19e5..3a190a3 100644 --- a/identity/verified-email/references/android/identity/passkeys/create-passkeys.md +++ b/identity/verified-email/references/android/identity/passkeys/create-passkeys.md @@ -1,11 +1,6 @@ -Before your users can authenticate with passkeys, your app must first register -or create the passkey for their account. +Before your users can authenticate with passkeys, your app must first register or create the passkey for their account. -To create the passkey, obtain details required to create the passkey from your -app server, and then call the Credential Manager API, which returns a public and -private key pair. The returned private key is stored in a credential provider, -such as Google Password Manager, as a passkey. The public key is stored on your -app server. +To create the passkey, obtain details required to create the passkey from your app server, and then call the Credential Manager API, which returns a public and private key pair. The returned private key is stored in a credential provider, such as Google Password Manager, as a passkey. The public key is stored on your app server. > [!TIP] > **Tip:** While designing authentication flows with passkeys, make sure that you follow the [UX guidelines for passkeys](https://developer.android.com/design/ui/mobile/guides/patterns/passkeys). @@ -14,15 +9,11 @@ app server. ## Prerequisites -Make sure that you have set up [Digital Asset Links](https://developer.android.com/identity/credential-manager/prerequisites) and that you target -devices running Android 9 (API level 28) or higher. +Make sure that you have set up [Digital Asset Links](https://developer.android.com/identity/credential-manager/prerequisites) and that you target devices running Android 9 (API level 28) or higher. ## Overview -This guide focuses on the changes required in your [relying party client app](https://developer.android.com/identity/credential-manager#authentication-terminology) -to create a passkey, and gives a brief overview of the [relying party app -server](https://developer.android.com/identity/credential-manager#authentication-terminology) implementation. To learn more about the server-side integration, see -[Server-side passkey registration](https://developers.google.com/identity/passkeys/developer-guides/server-registration). +This guide focuses on the changes required in your [relying party client app](https://developer.android.com/identity/credential-manager#authentication-terminology) to create a passkey, and gives a brief overview of the [relying party app server](https://developer.android.com/identity/credential-manager#authentication-terminology) implementation. To learn more about the server-side integration, see [Server-side passkey registration](https://developers.google.com/identity/passkeys/developer-guides/server-registration). 1. [**Add dependencies to your app**](https://developer.android.com/identity/passkeys/create-passkeys#add-dependencies): Add the required Credential Manager libraries. 2. [**Instantiate Credential Manager**](https://developer.android.com/identity/passkeys/create-passkeys#instantiate): Create a Credential Manager instance. @@ -33,8 +24,7 @@ server](https://developer.android.com/identity/credential-manager#authentication 7. [**Notify the user**](https://developer.android.com/identity/passkeys/create-passkeys#notify): Notify the user that their passkey has been created. > [!TIP] -> **Tip:** To enhance the user experience during sign up, add functionality to [restore credentials](https://developer.android.com/identity/sign-in/restore-credentials) on a new device to let users seamlessly set up their existing accounts on new Android devices, and [suppressing autofill dialogs on -> credential fields](https://developer.android.com/identity/passkeys/create-passkeys#suppress-autofill). +> **Tip:** To enhance the user experience during sign up, add functionality to [restore credentials](https://developer.android.com/identity/sign-in/restore-credentials) on a new device to let users seamlessly set up their existing accounts on new Android devices, and [suppressing autofill dialogs on credential fields](https://developer.android.com/identity/passkeys/create-passkeys#suppress-autofill). ## Add dependencies to your app @@ -44,8 +34,8 @@ Add the following dependencies to your app module's `build.gradle` file: ```kotlin dependencies { - implementation("androidx.credentials:credentials:1.7.0-alpha02") - implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha02") + implementation("androidx.credentials:credentials:1.7.0-alpha03") + implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha03") } ``` @@ -53,8 +43,8 @@ dependencies { ```groovy dependencies { - implementation "androidx.credentials:credentials:1.7.0-alpha02" - implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha02" + implementation "androidx.credentials:credentials:1.7.0-alpha03" + implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha03" } ``` @@ -71,26 +61,16 @@ Use your app or activity context to create a `CredentialManager` object. ## Get credential creation options from your app server -When the user clicks a "Create Passkey" button or when a new user signs up, make -a request from your app to your app server to obtain the information required to -start the passkey registration process. +When the user clicks a "Create Passkey" button or when a new user signs up, make a request from your app to your app server to obtain the information required to start the passkey registration process. -Use a FIDO-compliant library in your app server to send your client app the -information required to create a passkey, such as information about the user, -the app, and additional configuration properties. To learn more, see [Server -side passkey registration](https://developers.google.com/identity/passkeys/developer-guides/server-registration). +Use a FIDO-compliant library in your app server to send your client app the information required to create a passkey, such as information about the user, the app, and additional configuration properties. To learn more, see [Server side passkey registration](https://developers.google.com/identity/passkeys/developer-guides/server-registration). -In the client app, decode the public key creation options sent by the app -server. These are usually represented in JSON format. To learn more about how -this decoding is done for web clients, see [Encoding and -Decoding](https://developers.google.com/identity/passkeys/developer-guides/server-registration#encoding_and_decoding). For Android client apps, you must handle the decoding -separately. +In the client app, decode the public key creation options sent by the app server. These are usually represented in JSON format. To learn more about how this decoding is done for web clients, see [Encoding and Decoding](https://developers.google.com/identity/passkeys/developer-guides/server-registration#encoding_and_decoding). For Android client apps, you must handle the decoding separately. > [!NOTE] > **Note:** On your app server, securely store the `challenge` so that you can later verify the origin of the credential. -The following snippet shows the structure the public key creation options sent -by the app server: +The following snippet shows the structure the public key creation options sent by the app server: { "challenge": "", @@ -149,9 +129,7 @@ Key fields in the public key creation options include: ## Create a passkey -After you have parsed the server-side public key creation options, create a -passkey by wrapping these options in a `CreatePublicKeyCredentialRequest` object -and calling `createCredential()`. +After you have parsed the server-side public key creation options, create a passkey by wrapping these options in a `CreatePublicKeyCredentialRequest` object and calling `createCredential()`. The `createPublicKeyCredentialRequest` includes the following: @@ -160,25 +138,14 @@ The `createPublicKeyCredentialRequest` includes the following: - `false` (default): Use this value if the call to Credential Manager was triggered by an explicit user action. - `true`: Use this value if Credential Manager is opportunistically called, such as when first opening the app. If you set the value to `true` and there are no immediately available credentials, Credential Manager won't show any UI and the request will fail immediately, returning NoCredentialException for get requests and [`CreateCredentialNoCreateOptionException`](https://developer.android.com/reference/kotlin/androidx/credentials/exceptions/CreateCredentialNoCreateOptionException) for create requests. -- `origin`: This field is automatically set for Android apps. For browsers and similarly privileged apps that need to set `origin`, see [Make Credential - Manager calls on behalf of other parties for privileged apps](https://developer.android.com/training/sign-in/privileged-apps). +- `origin`: This field is automatically set for Android apps. For browsers and similarly privileged apps that need to set `origin`, see [Make Credential Manager calls on behalf of other parties for privileged apps](https://developer.android.com/training/sign-in/privileged-apps). - `isConditional`: This is an optional field that defaults to `false`. For more information, see [Automatically create a passkey](https://developer.android.com/identity/passkeys/create-passkeys#automatic-upgrade). -Calling the `createCredential()` function launches Credential Manager's built-in -bottom sheet UI that prompts the user to use a passkey and to select a -credential provider and account for storage. However, if `isConditional` is set -to `true`, the bottom sheet UI does not display, and the passkey is -automatically created. +Calling the `createCredential()` function launches Credential Manager's built-in bottom sheet UI that prompts the user to use a passkey and to select a credential provider and account for storage. However, if `isConditional` is set to `true`, the bottom sheet UI does not display, and the passkey is automatically created. ### Automatically create a passkey -You can automatically create a passkey for a user after a successful password -login by setting the `isConditional` parameter to `true` in your -`CreatePublicKeyCredentialRequest` while creating a passkey. If the user doesn't -already have a passkey, your app will automatically attempt to create one in the -background and store it in the user's credential provider, such as Google -Password Manager. For an example of how this is implemented, see the [public -sample](https://github.com/android/identity-samples/blob/main/Shrine/app/src/main/java/com/authentication/shrine/ui/AuthenticationScreen.kt#L98). +You can automatically create a passkey for a user after a successful password login by setting the `isConditional` parameter to `true` in your `CreatePublicKeyCredentialRequest` while creating a passkey. If the user doesn't already have a passkey, your app will automatically attempt to create one in the background and store it in the user's credential provider, such as Google Password Manager. For an example of how this is implemented, see the [public sample](https://github.com/android/identity-samples/blob/main/Shrine/app/src/main/java/com/authentication/shrine/ui/AuthenticationScreen.kt#L98). ![An example of the notification Google Password Manager shows after passkey creation](https://developer.android.com/static/identity/passkeys/images/conditional-create-gpm.svg) **Figure 2:**Google Password Manager notification > [!NOTE] @@ -186,11 +153,9 @@ sample](https://github.com/android/identity-samples/blob/main/Shrine/app/src/mai ## Handle the response -After the user is verified using the device's screen lock, a passkey is created -and stored in the user's selected credential provider. +After the user is verified using the device's screen lock, a passkey is created and stored in the user's selected credential provider. -The response after you successfully call `createCredential()` is a -[PublicKeyCredential](https://developer.android.com/jetpack/androidx/releases/credentials) object. +The response after you successfully call `createCredential()` is a [PublicKeyCredential](https://developer.android.com/jetpack/androidx/releases/credentials) object. The `PublicKeyCredential` looks as follows: @@ -241,79 +206,55 @@ Add code to handle failures as shown in the following snippet: ## Verify and save the public key on the app server -On the app server, you must verify the public key credential and then [save the -public key](https://web.dev/articles/passkey-registration#save-credential). +On the app server, you must verify the public key credential and then [save the public key](https://web.dev/articles/passkey-registration#save-credential). -To verify the public key credential's origin, compare it against an allow list -of approved apps. If a key has an unrecognized origin, reject it. +To verify the public key credential's origin, compare it against an allow list of approved apps. If a key has an unrecognized origin, reject it. > [!NOTE] > **Note:** An app's origin is based on its unique identity, which is the SHA-256 fingerprint of its signing certificate. To obtain the app's SHA 256 fingerprint: -1. Print your release app's signing certificate by running the following - command in a terminal: +1. Print your release app's signing certificate by running the following command in a terminal: keytool -list -keystore - In the response, identify the signing certificate's SHA 256 fingerprint, - mentioned as `Certificate fingerprints block` : `SHA256`. -2. Encode the SHA256 fingerprint with base64url encoding. This Python example - demonstrates how to properly encode the fingerprint: + In the response, identify the signing certificate's SHA 256 fingerprint, mentioned as `Certificate fingerprints block` : `SHA256`. +2. Encode the SHA256 fingerprint with base64url encoding. This Python example demonstrates how to properly encode the fingerprint: import binascii import base64 fingerprint = '' # your app's SHA256 fingerprint print(base64.urlsafe_b64encode(binascii.a2b_hex(fingerprint.replace(':', ''))).decode('utf8').replace('=', '')) -3. Append `android:apk-key-hash`: to the start of the output from the previous - step so that you get something that is similar to the following: +3. Append `android:apk-key-hash`: to the start of the output from the previous step so that you get something that is similar to the following: android:apk-key-hash: - The result should match with an allowed origin on your app server. If you - have multiple signing certificates, such as certificates for debugging and - release, or multiple apps, then repeat the process and accept all the - origins as valid on the app server. + The result should match with an allowed origin on your app server. If you have multiple signing certificates, such as certificates for debugging and release, or multiple apps, then repeat the process and accept all the origins as valid on the app server. > [!NOTE] > **Note:** When you save the passkey on the app server, make sure that you save the Authenticator Attestation Globally Unique Identifier ([AAGUID](https://web.dev/articles/webauthn-aaguid)) from the client data. The AAGUID is a unique number that identifies the model of the authenticator. For more information, see [Manage passkeys](https://developer.android.com/identity/passkeys/manage-passkeys). ## Notify the user -After the passkey is successfully created, notify your users about the passkey -and inform them that they can manage their passkeys from their credential -provider app or from [within the app settings](https://developer.android.com/identity/passkeys/manage-passkeys). Notify users by using a -custom dialog, notification, or snackbar. Since an unexpected passkey creation -by a malicious entity requires an immediate security alert, consider -supplementing these in-app methods with external communication, such as an -email. +After the passkey is successfully created, notify your users about the passkey and inform them that they can manage their passkeys from their credential provider app or from [within the app settings](https://developer.android.com/identity/passkeys/manage-passkeys). Notify users by using a custom dialog, notification, or snackbar. Since an unexpected passkey creation by a malicious entity requires an immediate security alert, consider supplementing these in-app methods with external communication, such as an email. ## Enhance the user experience -To enhance the user experience while implementing sign up with Credential -Manager, consider adding functionality for restore credentials and suppress -autofill dialogs. +To enhance the user experience while implementing sign up with Credential Manager, consider adding functionality for restore credentials and suppress autofill dialogs. ### Add functionality to restore credentials on a new device -To allow users to seamlessly log into their accounts on a new device, implement -the [Restore Credentials](https://developer.android.com/identity/sign-in/restore-credentials) functionality. Adding restore credentials with -`BackupAgent` logs users in when they open your restored app on a new device, -letting them use your app right away. +To allow users to seamlessly log into their accounts on a new device, implement the [Restore Credentials](https://developer.android.com/identity/sign-in/restore-credentials) functionality. Adding restore credentials with `BackupAgent` logs users in when they open your restored app on a new device, letting them use your app right away. ### Suppress autofill on credential fields (optional) -For app screens where users are expected to use Credential Manager's bottom -sheet UI for authentication, add the `isCredential` attribute to the username -and password fields. This suppresses autofill dialogs (`FillDialog` and -`SaveDialog`) from overlapping with Credential Manager's bottom sheet UI. +For app screens where users are expected to use Credential Manager's bottom sheet UI for authentication, add the `isCredential` attribute to the username and password fields. This suppresses autofill dialogs (`FillDialog` and `SaveDialog`) from overlapping with Credential Manager's bottom sheet UI. The `isCredential` attribute is supported on Android 14 and higher. -The following example demonstrates how you can add the `isCredential` attribute -to the relevant username and password fields in the relevant views for your app: +The following example demonstrates how you can add the `isCredential` attribute to the relevant username and password fields in the relevant views for your app: ```kotlin @Preview(name = "Phone", device = Devices.PHONE, showBackground = true) @@ -64,25 +61,21 @@ fun FeedScreenPreview() { } } } + ```
## Step 2. Make the navigation bar adaptive -Bottom navigation bars are optimized for touch input when the user is holding a -phone in portrait mode. On larger screen hand-held devices, like tablets and -unfolded foldables, the navigation area must be accessible from the edge of the -screen (navigation rail). +Bottom navigation bars are optimized for touch input when the user is holding a phone in portrait mode. On larger screen hand-held devices, like tablets and unfolded foldables, the navigation area must be accessible from the edge of the screen (navigation rail). -If you need to provide more screen space for the content, hide the -navigation area. Examples of this include: +If you need to provide more screen space for the content, hide the navigation area. Examples of this include: - Hiding the navigation bar when the user scrolls down and showing it again when the user scrolls up. The assumption is that when the user is scrolling down, they are consuming content but when scrolling up they are trying to navigate away from that content. - Hiding the navigation area when its content is distracting. For example, in camera previews or when displaying a full-screen photo. -When the detail screen is displayed full-screen on mobile, full-screen mode must -be deactivated on larger screens. +When the detail screen is displayed full-screen on mobile, full-screen mode must be deactivated on larger screens. Steps to migrate: @@ -94,10 +87,7 @@ Steps to migrate: ### Step 2.1. Control navigation area visibility -If the navigation bar's visibility changes - it is hidden under certain -scenarios or on certain screens - this behavior must be maintained with the -adaptive navigation area. This is done using `NavigationSuiteScaffold`'s `state` -parameter. +If the navigation bar's visibility changes - it is hidden under certain scenarios or on certain screens - this behavior must be maintained with the adaptive navigation area. This is done using `NavigationSuiteScaffold`'s `state` parameter. Steps to migrate: @@ -107,6 +97,7 @@ Steps to migrate: For example: +
```kotlin // Pass this variable to any composable that needs to control the navigation area visibility @@ -127,33 +118,26 @@ LaunchedEffect(isNavBarVisible){ scaffoldVisibilityState.hide() } } + ```
## Step 3. Add multi-pane layouts using Navigation 3 Scenes -Analyze the codebase looking for related screens - tapping on something in one -screen opens another screen that shows information related to the first. There -are two canonical screen relationships: list-detail and supporting pane. +Analyze the codebase looking for related screens - tapping on something in one screen opens another screen that shows information related to the first. There are two canonical screen relationships: list-detail and supporting pane. -IMPORTANT: You must use the Navigation 3 `SceneStrategy` approach to implement -multi-pane layouts. Do not use `ListDetailPaneScaffold` or -`SupportingPaneScaffold`. +IMPORTANT: You must use the Navigation 3 `SceneStrategy` approach to implement multi-pane layouts. Do not use `ListDetailPaneScaffold` or `SupportingPaneScaffold`. ### Step 3.1. List-detail #### Identify the list and detail screens -List-detail layouts display a list of items (this is the list screen) and -clicking on an item opens a new screen that shows more details about that item -(the detail screen). +List-detail layouts display a list of items (this is the list screen) and clicking on an item opens a new screen that shows more details about that item (the detail screen). Typical usage includes productivity apps like email, notes, and messaging. -Unless requested explicitly, avoid this pattern when the detail content requires -substantial screen space (e.g., images or media that benefits from a full-screen -presentation). +Unless requested explicitly, avoid this pattern when the detail content requires substantial screen space (e.g., images or media that benefits from a full-screen presentation). #### Add a Material list-detail SceneStrategy @@ -163,8 +147,7 @@ presentation). #### Use metadata to identify the list and detail screens -- Add metadata using `entry(metadata = ...)` or `NavEntry(metadata = ...)` to the list entry using `ListDetailSceneStrategy.listPane(detailPlaceholder = { - })`. +- Add metadata using `entry(metadata = ...)` or `NavEntry(metadata = ...)` to the list entry using `ListDetailSceneStrategy.listPane(detailPlaceholder = { })`. - Use the `detailPlaceholder` parameter to add a placeholder on the detail screen when no list items are selected. - Add metadata to the detail entry using `ListDetailSceneStrategy.detailPane()`. @@ -173,14 +156,11 @@ presentation). - When a detail screen displays its content full-screen on mobile (content fills the entire screen, bars or rails are hidden), full-screen mode must be deactivated if it's part of a list-detail layout. - Detail screens must not show a back arrow when on a list-detail layout. -For a reference implementation, check the [Nav3 **Material** List Detail -recipe](references/android/guide/navigation/navigation-3/recipes/material-listdetail.md). +For a reference implementation, check the [Nav3 **Material** List Detail recipe](references/android/guide/navigation/navigation-3/recipes/material-listdetail.md). ### Step 3.2. Supporting pane -Identify supporting pane screens where a main screen displays a single item, and -selecting it opens a "supporting screen" with more details. The supporting -screen complements the main screen and is shown in a supporting pane. +Identify supporting pane screens where a main screen displays a single item, and selecting it opens a "supporting screen" with more details. The supporting screen complements the main screen and is shown in a supporting pane. #### Add a Material supporting pane `SceneStrategy` @@ -195,15 +175,13 @@ screen complements the main screen and is shown in a supporting pane. ### Step 3.3. Run screenshot tests -If you have made changes, record new reference files. Ask the user to visually -verify that the new layouts are correct. +If you have made changes, record new reference files. Ask the user to visually verify that the new layouts are correct. ## Step 4. Make vertical lists adaptive by changing the number of columns ### Step 4.1. Make lazy lists adaptive -Look for the following vertical list composables: `LazyColumn`, -`LazyVerticalGrid`, `LazyVerticalStaggeredGrid`. +Look for the following vertical list composables: `LazyColumn`, `LazyVerticalGrid`, `LazyVerticalStaggeredGrid`. Steps to migrate: @@ -214,24 +192,16 @@ Steps to migrate: ### Step 4.2. Migrate non-lazy lists to Grid -WARNING: Grid is an experimental API available from Compose 1.11.0-beta01. -Confirm with the user that they are happy to use an experimental API in their -codebase. +WARNING: Grid is an experimental API available from Compose 1.11.0-beta01. Confirm with the user that they are happy to use an experimental API in their codebase. -Look for any `Column` that contains multiple items of the same type and replace -it with `Grid`. Do not replace it with `LazyVerticalGrid` or any other lazy -layout. Do not place `Grid` inside the existing `Column`. Completely replace it. +Look for any `Column` that contains multiple items of the same type and replace it with `Grid`. Do not replace it with `LazyVerticalGrid` or any other lazy layout. Do not place `Grid` inside the existing `Column`. Completely replace it. -`Grid` is configured by supplying a lambda (an extension function on -`GridConfigurationScope`) to its `config` parameter. Inside the lambda, -`constraints` provides the minimum and maximum dimensions of the grid container -and can be used to change the number of rows and columns based on the available -size. For example, the following code configures `Grid` such that when the -available width is: +`Grid` is configured by supplying a lambda (an extension function on `GridConfigurationScope`) to its `config` parameter. Inside the lambda, `constraints` provides the minimum and maximum dimensions of the grid container and can be used to change the number of rows and columns based on the available size. For example, the following code configures `Grid` such that when the available width is: - less than 800dp, a 2x4 grid is used - 800dp or more, a 4x2 grid is used +
```kotlin Grid( @@ -250,26 +220,23 @@ Grid( gap(gapSizeDp) } ) { /** items **/ } + ```
-`Grid` is an experimental API so add the `@OptIn(ExperimentalGridApi::class)` -annotation to any function that uses it. +`Grid` is an experimental API so add the `@OptIn(ExperimentalGridApi::class)` annotation to any function that uses it. ## Step 5: Hide App Bars when scrolling -In an app with multiple top-level destinations, each screen must manage its own -app bar state independently. There are two main scroll behaviors: +In an app with multiple top-level destinations, each screen must manage its own app bar state independently. There are two main scroll behaviors: - `exitUntilCollapsedScrollBehavior`: Hides on scroll down, stays hidden while you scroll up until you reach the very top (0 offset). - `enterAlwaysScrollBehavior`: Hides on scroll down, shows immediately on scroll up. ## Final step: Build and test -Build the app and run the local tests. If the project has screenshot tests, run -them but DO NOT update the reference images. Prompt the user to do this after -they have viewed the screenshot diffs. +Build the app and run the local tests. If the project has screenshot tests, run them but DO NOT update the reference images. Prompt the user to do this after they have viewed the screenshot diffs. ## Additional documentation for experimental adaptive APIs @@ -286,14 +253,11 @@ Check the FlexBox documentation: ## MediaQuery -Check the [MediaQuery documentation](references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md) when you need to query the device's -screen size, pointer precision, keyboard type, whether it has cameras or -microphones, and other device capabilities. +Check the [MediaQuery documentation](references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md) when you need to query the device's screen size, pointer precision, keyboard type, whether it has cameras or microphones, and other device capabilities. ## Grid -Check the Grid documentation when you need to display a fixed number of items in -a grid layout: +Check the Grid documentation when you need to display a fixed number of items in a grid layout: - [Overview](references/android/develop/ui/compose/layouts/adaptive/grid/index.md) - [Get started - setup](references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md) diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/container-behavior.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/container-behavior.md index 41112fc..27c2e3d 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/container-behavior.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/container-behavior.md @@ -1,6 +1,6 @@ -To configure the behavior of the `FlexBox` container, create a `FlexBoxConfig` -block and supply it using the `config` parameter. +To configure the behavior of the `FlexBox` container, create a `FlexBoxConfig` block and supply it using the `config` parameter. +
```kotlin FlexBox( @@ -14,17 +14,16 @@ FlexBox( } ) { // child items } + ```
-Use `FlexBoxConfig` to define the layout direction, wrapping behavior, -alignment, and gaps between items. +Use `FlexBoxConfig` to define the layout direction, wrapping behavior, alignment, and gaps between items. ## Layout direction -The `direction` function sets the main axis, which dictates the direction -items are laid out in. It accepts the following values: +The `direction` function sets the main axis, which dictates the direction items are laid out in. It accepts the following values: - `Row` (default): Sets the main axis to be horizontal. In left-to-right locales this will be left-to-right, with the opposite in right-to-left. - `RowReverse`: Reverses the direction of `Row`. @@ -33,13 +32,11 @@ items are laid out in. It accepts the following values: ## Align items and distribute extra space -The following sections describe how to align items and distribute extra space -along the main and cross axes. +The following sections describe how to align items and distribute extra space along the main and cross axes. ### Along the main axis -Use `justifyContent` to distribute items along the main axis. The following -table shows the behavior when the direction is `Row`. +Use `justifyContent` to distribute items along the main axis. The following table shows the behavior when the direction is `Row`. |---|---| | | ![Illustration of a horizontal main axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/main-axis.png) | @@ -52,9 +49,7 @@ table shows the behavior when the direction is `Row`. ### Along the cross axis -Use `alignItems` to align items along the cross axis within a single line. This -behavior can be overridden by individual items using the -[`alignSelf` modifier](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-alignment). +Use `alignItems` to align items along the cross axis within a single line. This behavior can be overridden by individual items using the [`alignSelf` modifier](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-alignment). The following images show the behavior when the direction is `Row`: @@ -62,10 +57,7 @@ The following images show the behavior when the direction is `Row`: | ![Illustration of a vertical cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/crossaxis.png) | ![Items aligned to the start of the cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/crossaxis-start.png) | ![Items aligned to the end of the cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/crossaxis-end.png) | ![Items aligned to the center of the cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/crossaxis-center.png) | ![Items stretched to fill the cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/crossaxis-stretch.png) | ![Items aligned to their baseline along the cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/crossaxis-baseline.png) | | | `Start` | `End` | `Center` | `Stretch` | `Baseline` | -Use `alignContent` to align lines to the cross axis and to distribute extra -space between lines. This property only applies when there are multiple lines -(wrapping is enabled). The following images show the behavior when the direction -is `Row`: +Use `alignContent` to align lines to the cross axis and to distribute extra space between lines. This property only applies when there are multiple lines (wrapping is enabled). The following images show the behavior when the direction is `Row`: |---|---|---|---|---|---|---| | ![Illustration of a vertical cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/crossaxis.png) | ![Multiple lines of items aligned to the start of the cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/aligncontent-start.png) | ![Multiple lines of items aligned to the end of the cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/aligncontent-end.png) | ![Multiple lines of items aligned to the center of the cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/aligncontent-center.png) | ![Multiple lines of items stretched to fill the cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/aligncontent-stretch.png) | ![Multiple lines of items distributed along the cross axis with space between them.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/aligncontent-spacebetween.png) | ![Multiple lines of items distributed along the cross axis with space around them.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/aligncontent-spacearound.png) | @@ -73,9 +65,7 @@ is `Row`: ## Wrap items -Wrapping lets a `FlexBox` container become multi-line, moving items that don't -fit onto a new row or column along the cross-axis. Configure wrapping behavior -using `wrap`. +Wrapping lets a `FlexBox` container become multi-line, moving items that don't fit onto a new row or column along the cross-axis. Configure wrapping behavior using `wrap`. |---|---| | **`FlexWrap` value** | **Example using direction `Row`** | @@ -83,29 +73,20 @@ using `wrap`. | `Wrap`: When there is insufficient space for an item (plus any [gap](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#add-gaps)), a new line is created in the direction of the cross axis. For example, if the direction is `Row`, a new line is added **below**. | ![Items wrapping onto a new line below because wrapping is enabled.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/wrapitems-2.png) | | `WrapReverse`: The same as `Wrap`, except the new line is added in the opposite direction to the cross axis. For example, if the direction is `Row`, a new line is added **above**. | ![Items wrapping onto a new line above because reverse wrapping is enabled.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/wrapitems-3.png) | -The following example shows how the `FlexBox` wrapping algorithm works. The -`FlexBox` container has a main size of `100dp`, with `wrap` set to -`FlexWrap.Wrap` and a gap of `8dp`. It contains three items with `basis` `20dp`, -`40dp`, and `50dp`, respectively. +The following example shows how the `FlexBox` wrapping algorithm works. The `FlexBox` container has a main size of `100dp`, with `wrap` set to `FlexWrap.Wrap` and a gap of `8dp`. It contains three items with `basis` `20dp`, `40dp`, and `50dp`, respectively. -There is `100dp` available space in the line. Child 1 is `20dp`. -There is space, so Child 1 is placed into the line. +There is `100dp` available space in the line. Child 1 is `20dp`. There is space, so Child 1 is placed into the line. ![First item placed in the FlexBox container.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/algorithm-1.png) **Figure 1.** First item placed in the `FlexBox` container. -There is `80dp` available space in the line. The gap is `8dp`. Child 2 is -`40dp`. The required space is `48dp`. There is space, so the gap and Child 2 -are placed into the line. +There is `80dp` available space in the line. The gap is `8dp`. Child 2 is `40dp`. The required space is `48dp`. There is space, so the gap and Child 2 are placed into the line. ![Second item placed in the FlexBox container after the first item.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/algorithm-2.png) **Figure 2.** Second item placed in the `FlexBox` container after the first item. -There is `32dp` available space in the line. The gap is `8dp`. Child 3 is -`50dp`. The required space is `58dp`. There is not enough space in the current -line, so Child 3 is placed in a new line. +There is `32dp` available space in the line. The gap is `8dp`. Child 3 is `50dp`. The required space is `58dp`. There is not enough space in the current line, so Child 3 is placed in a new line. ![Third item placed on a new line because it doesn't fit on the first line.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/algorithm-3.png) **Figure 3.** Third item placed on a new line because it doesn't fit on the first line. ## Add gaps between items -Add gaps between rows and columns using `rowGap` and `columnGap`. This is useful -to avoid adding spacing modifiers to children. +Add gaps between rows and columns using `rowGap` and `columnGap`. This is useful to avoid adding spacing modifiers to children. |---|---|---| | ![Row gap adds vertical space between items.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/gap-1.png) | ![Column gap adds horizontal space between items.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/gap-2.png) | ![Gap adds both horizontal and vertical space between items.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/gap-3.png) | diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/get-started.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/get-started.md index 8b00b01..2bf41f0 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/get-started.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/get-started.md @@ -2,11 +2,10 @@ This page describes how to implement basic `FlexBox` layouts. ## Set up project -1. Add the [`androidx.compose.foundation.layout`](https://developer.android.com/jetpack/androidx/versions) library to your project's - `lib.versions.toml`. +1. Add the [`androidx.compose.foundation.layout`](https://developer.android.com/jetpack/androidx/versions) library to your project's `lib.versions.toml`. [versions] - compose = "1.12.0-beta02" + compose = "1.12.0-rc01" [libraries] androidx-compose-foundation-layout = { group = "androidx.compose.foundation", name = "foundation-layout", version.ref = "compose" } @@ -19,9 +18,9 @@ This page describes how to implement basic `FlexBox` layouts. ## Create basic FlexBox layouts -**Example 1** : `FlexBox` lays out two `Text` elements that are centrally -aligned. +**Example 1** : `FlexBox` lays out two `Text` elements that are centrally aligned. +
```kotlin FlexBox( @@ -33,16 +32,16 @@ FlexBox( Text(text = "Hello", fontSize = 48.sp) Text(text = "World!", fontSize = 48.sp) } + ```
![Hello World text composables stacked on top of each other in a basic FlexBox implementation.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/basic-flexbox.png) -**Example 2** : `FlexBox` wraps five items onto two rows and grows them unequally -to fill the available space on each row. There is an `8.dp` -gap, both vertically and horizontally, between the items. +**Example 2** : `FlexBox` wraps five items onto two rows and grows them unequally to fill the available space on each row. There is an `8.dp` gap, both vertically and horizontally, between the items. +
```kotlin FlexBox( @@ -59,11 +58,11 @@ FlexBox( OrangeRoundedBox(modifier = Modifier.flex { grow(1.0f) }) PinkRoundedBox(modifier = Modifier.flex { grow(1.0f) }) } + ```
![Two rows of colored items, with three unequally sized items distributed across the top row and two unequally sized items across the bottom row.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/basic-flexbox-2.png) -To learn more about `FlexBox` behavior, see [Set container behavior](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior) and [Set -item behavior](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior). \ No newline at end of file +To learn more about `FlexBox` behavior, see [Set container behavior](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior) and [Set item behavior](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior). \ No newline at end of file diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/index.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/index.md index ddda0de..50828f0 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/index.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/index.md @@ -1,10 +1,7 @@ > [!NOTE] > **Note:** FlexBox is an experimental API and is likely to change in the future. To use it, annotate your code with `@ExperimentalFlexBoxApi`. Please file any issues or feedback on the [issue tracker](https://issuetracker.google.com/issues/new?component=1876021&title=%5BFlexBox%5D). -[`FlexBox`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/FlexBox.composable#FlexBox(androidx.compose.ui.Modifier,androidx.compose.foundation.layout.FlexBoxConfig,kotlin.Function1)) is a container that lays out items in a single direction. It can -resize, wrap, align, and distribute space among items to optimally fill the -available space. It's a useful layout for different sized items and for resizing -items when the available space changes. +[`FlexBox`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/FlexBox.composable#FlexBox(androidx.compose.ui.Modifier,androidx.compose.foundation.layout.FlexBoxConfig,kotlin.Function1)) is a container that lays out items in a single direction. It can resize, wrap, align, and distribute space among items to optimally fill the available space. It's a useful layout for different sized items and for resizing items when the available space changes. With `FlexBox`, you can: @@ -14,23 +11,16 @@ With `FlexBox`, you can: ## When to use FlexBox -`FlexBox` is usually used to display a small number of items *within* an -overall screen layout. For an overall screen layout, -`Grid` is usually a better choice. `FlexBox` does not support lazy-loading of -items. To display large numbers of items, use [lazy lists and grids](https://developer.android.com/develop/ui/compose/lists). If you -need to wrap items, use `FlexBox` instead of `FlowRow` and `FlowColumn`. +`FlexBox` is usually used to display a small number of items *within* an overall screen layout. For an overall screen layout, `Grid` is usually a better choice. `FlexBox` does not support lazy-loading of items. To display large numbers of items, use [lazy lists and grids](https://developer.android.com/develop/ui/compose/lists). If you need to wrap items, use `FlexBox` instead of `FlowRow` and `FlowColumn`. ## Terminology and concepts > [!IMPORTANT] > **Key Point:** `FlexBox` is heavily influenced by the [CSS Flexible Box Layout specification](https://www.w3.org/TR/css-flexbox-1/) and has almost identical concepts, terminology, and behavior. If you're familiar with `display: flex`, you'll find `FlexBox`'s properties and behavior almost identical. -`FlexBox` lays out its items in either horizontal or vertical *lines* . This -direction of these lines establishes the *main axis* . 90 degrees to the main -axis is the *cross axis* . The length of the `FlexBox` along the main axis is -known as the *main size* . The corresponding cross axis length is known as the -*cross size* . These sizes and axes form the basis of `FlexBox`'s behavior. +`FlexBox` lays out its items in either horizontal or vertical *lines* . This direction of these lines establishes the *main axis* . 90 degrees to the main axis is the *cross axis* . The length of the `FlexBox` along the main axis is known as the *main size* . The corresponding cross axis length is known as the *cross size* . These sizes and axes form the basis of `FlexBox`'s behavior. +
![FlexBox with horizontal main axis and vertical cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/intro-row-2.png) **Figure 1.** Axes and sizes when the `FlexBox` direction is `Row`. ![FlexBox with vertical main axis and horizontal cross axis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/intro-column.png) **Figure 2.** Axes and sizes when the `FlexBox` direction is `Column`. @@ -49,33 +39,18 @@ You can apply `FlexBox` properties in two ways: ### Understand the `FlexBox` layout algorithm -One of `FlexBox`'s most powerful features is its ability to resize its children -to best fit the space available to it. Understanding how `FlexBox` does this can -help you set `FlexBox` properties to optimize your UI for all possible sizes. +One of `FlexBox`'s most powerful features is its ability to resize its children to best fit the space available to it. Understanding how `FlexBox` does this can help you set `FlexBox` properties to optimize your UI for all possible sizes. `FlexBox`'s layout algorithm works in the following way: -1. **Calculate child base size** : Use the child's [`basis` value](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#set-initial-size) - to calculate its initial size along the main axis before any extra space is - distributed. +1. **Calculate child base size** : Use the child's [`basis` value](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#set-initial-size) to calculate its initial size along the main axis before any extra space is distributed. -2. **Sort the children** : Sort the children by their [`order`](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-order) values, if - present. +2. **Sort the children** : Sort the children by their [`order`](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-order) values, if present. -3. **Build lines** : For each child, check if its initial size plus - [`gap`](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#add-gaps) will fit into the remaining space on the current line. - If so, place this child into the line. If not, place it onto a new line if - [wrapping is enabled](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#wrap-items), or place the item into the current line - where it will overflow (it will be partially obscured by the edge of the - container). +3. **Build lines** : For each child, check if its initial size plus [`gap`](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#add-gaps) will fit into the remaining space on the current line. If so, place this child into the line. If not, place it onto a new line if [wrapping is enabled](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#wrap-items), or place the item into the current line where it will overflow (it will be partially obscured by the edge of the container). -4. **Align or resize items in the main axis** : For each line, distribute extra - space *to* or between items by [resizing](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-size) or - [aligning](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#main-axis) them. +4. **Align or resize items in the main axis** : For each line, distribute extra space *to* or between items by [resizing](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-size) or [aligning](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#main-axis) them. -5. **Align or resize items in the cross axis** : For each line, distribute extra - space to or between items and lines by [stretching or aligning - them](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#cross-axis). +5. **Align or resize items in the cross axis** : For each line, distribute extra space to or between items and lines by [stretching or aligning them](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#cross-axis). -Now that you're familiar with `FlexBox` concepts, see [Get started](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/get-started) to -create a basic `FlexBox`. \ No newline at end of file +Now that you're familiar with `FlexBox` concepts, see [Get started](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/get-started) to create a basic `FlexBox`. \ No newline at end of file diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/item-behavior.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/item-behavior.md index e4a5c0f..ddb0f02 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/item-behavior.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/item-behavior.md @@ -1,10 +1,10 @@ -Use `Modifier.flex` to control how an item changes size, order, and is aligned -inside a `FlexBox`. +Use `Modifier.flex` to control how an item changes size, order, and is aligned inside a `FlexBox`. ## Item size Use the `basis`, `grow`, and `shrink` functions to control an item's size. +
```kotlin FlexBox { @@ -16,14 +16,14 @@ FlexBox { } ) } + ```
### Set initial size -Use `basis` to specify the item's initial size before any extra space is -distributed. You can think of this as the item's *preferred* size. +Use `basis` to specify the item's initial size before any extra space is distributed. You can think of this as the item's *preferred* size. |---|---|---|---| | **Value type** | **Behavior** | **Code snippet** Note: The boxes have a maximum intrinsic size of `100dp` | **Example using container width `600dp`** | @@ -31,48 +31,31 @@ distributed. You can think of this as the item's *preferred* size. | Fixed `dp` | A fixed size in Dp. | ```kotlin FlexBox { RedRoundedBox( Modifier.flex { basis(200.dp) } ) BlueRoundedBox( Modifier.flex { basis(100.dp) } ) } ``` | ![Items sized to a fixed dp value using basis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/initialsize-2.png) | | Percentage | A percentage of the container size. | ```kotlin FlexBox { RedRoundedBox( Modifier.flex { basis(0.7f) } ) BlueRoundedBox( Modifier.flex { basis(0.3f) } ) } ``` | ![Items sized as a percentage of container size using basis.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/initialsize-3.png) | -If the basis value is less than the item's intrinsic minimum size, the intrinsic -minimum size is used instead. For example, if a `Text` item that contains a word -requires `50dp` to display, but also has `basis = 10.dp`, a -value of `50dp` is used. +If the basis value is less than the item's intrinsic minimum size, the intrinsic minimum size is used instead. For example, if a `Text` item that contains a word requires `50dp` to display, but also has `basis = 10.dp`, a value of `50dp` is used. ### Grow items when there's space -Use `grow` to specify how much an item grows when there is extra space. This is -space remaining in the `FlexBox` container after all the items' `basis` values -have been added up. The `grow` value indicates *how much* of the extra space a -given child will receive, relative to its siblings. By default, items won't -grow. +Use `grow` to specify how much an item grows when there is extra space. This is space remaining in the `FlexBox` container after all the items' `basis` values have been added up. The `grow` value indicates *how much* of the extra space a given child will receive, relative to its siblings. By default, items won't grow. -The following example shows a `FlexBox` with three child items. Each has a basis -value of `100dp`. The first child has a positive `grow` value. Since there is -only one child with a `grow` value, the actual value is irrelevant - as long as -it's positive, the child receives all the extra space. +The following example shows a `FlexBox` with three child items. Each has a basis value of `100dp`. The first child has a positive `grow` value. Since there is only one child with a `grow` value, the actual value is irrelevant - as long as it's positive, the child receives all the extra space. The images show the `FlexBox` behavior when its container size is `600dp`. |---|---| | ```kotlin FlexBox { RedRoundedBox( title = "400dp", modifier = Modifier.flex { grow(1f) } ) BlueRoundedBox(title = "100dp") GreenRoundedBox(title = "100dp") } ``` | Each child has a basis value of `100dp`. There is `300dp` of extra space. ![Three items with 100dp basis each, in a 600dp container, before growth.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/growitems-1.png) Child 1 grows by `300dp` to fill the extra space. ![First item grows to fill 300dp of extra space.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/growitems-2.png) | -In the following example, the container size and `basis` size are the same. The -difference is that each child has a different `grow` value. +In the following example, the container size and `basis` size are the same. The difference is that each child has a different `grow` value. |---|---| | ```kotlin FlexBox { RedRoundedBox( title = "150dp", modifier = Modifier.flex { grow(1f) } ) BlueRoundedBox( title = "200dp", modifier = Modifier.flex { grow(2f) } ) GreenRoundedBox( title = "250dp", modifier = Modifier.flex { grow(3f) } ) } ``` | Each child has a basis value of `100dp`. There is `300dp` of extra space. ![Three items with 100dp basis each, in a 600dp container, before growth, with different grow values.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/growitems-3.png) The total grow value is 6. Child 1 grows by (1 / 6) \* 300 = `50dp` Child 2 grows by (2 / 6) \* 300 = `100dp` Child 3 grows by (3 / 6) \* 300 = `150dp` ![Items grow to fill 300dp of extra space based on relative grow values.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/flexbox/growitems-4.png) | ### Shrink items when there's insufficient space -Use `shrink` to specify how much an item shrinks when the `FlexBox` container -has insufficient space for all the items. `shrink` works the same way as `grow` -except that, instead of distributing *extra space* to items, the *space deficit* -is distributed to items. The `shrink` value specifies how much of the space -deficit the item receives, or rather, how much the item will shrink by. By -default, items have a `shrink` value of `1f`, meaning they shrink equally. +Use `shrink` to specify how much an item shrinks when the `FlexBox` container has insufficient space for all the items. `shrink` works the same way as `grow` except that, instead of distributing *extra space* to items, the *space deficit* is distributed to items. The `shrink` value specifies how much of the space deficit the item receives, or rather, how much the item will shrink by. By default, items have a `shrink` value of `1f`, meaning they shrink equally. -The following example shows two `Text` composables with the same text. The first -child has a shrink value of `1f`, meaning it shrinks to absorb all the space -deficit. +The following example shows two `Text` composables with the same text. The first child has a shrink value of `1f`, meaning it shrinks to absorb all the space deficit. +
```kotlin FlexBox { @@ -91,6 +74,7 @@ FlexBox { .flex { shrink(0f) } ) } + ```
@@ -105,14 +89,11 @@ As the container size shrinks, Child 1 shrinks. ## Item alignment -Use `alignSelf` to control how an item is aligned to the cross axis. This -overrides the [`alignItems` property](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#align-distribute) of the container for this item. It -has all the same possible values, with the addition of `Auto` which inherits the -behavior of the `FlexBox` container. +Use `alignSelf` to control how an item is aligned to the cross axis. This overrides the [`alignItems` property](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#align-distribute) of the container for this item. It has all the same possible values, with the addition of `Auto` which inherits the behavior of the `FlexBox` container. -For example, this `FlexBox` has `alignItems` set to `Start` and five children -which override the cross axis alignment. +For example, this `FlexBox` has `alignItems` set to `Start` and five children which override the cross axis alignment. +
```kotlin FlexBox( @@ -126,6 +107,7 @@ FlexBox( PinkRoundedBox(modifier = Modifier.flex { alignSelf(FlexAlignSelf.Stretch) }) OrangeRoundedBox(modifier = Modifier.flex { alignSelf(FlexAlignSelf.Baseline) }) } + ```
@@ -134,19 +116,13 @@ FlexBox( ## Item order -By default, `FlexBox` lays out items in the order that they are declared in -code. Override this behavior using `order`. +By default, `FlexBox` lays out items in the order that they are declared in code. Override this behavior using `order`. -The default value for `order` is zero, and `FlexBox` sorts items based on this -value in ascending order. Any items that have the same `order` value are -laid out in the same order they are declared in. Use negative and positive -`order` values to move items to the start or end of a layout without changing -where they are declared. +The default value for `order` is zero, and `FlexBox` sorts items based on this value in ascending order. Any items that have the same `order` value are laid out in the same order they are declared in. Use negative and positive `order` values to move items to the start or end of a layout without changing where they are declared. -The following example shows two child items. The first has the default `order` -of zero, and the second has an order of `-1`. After sorting, Child 1 appears -after Child 2. +The following example shows two child items. The first has the default `order` of zero, and the second has an order of `-1`. After sorting, Child 1 appears after Child 2. +
```kotlin FlexBox { @@ -163,6 +139,7 @@ FlexBox { } ) } + ```
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md index 33b37a2..28c8d13 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md @@ -1,6 +1,4 @@ -You can define a Grid container configuration to create flexible layouts -that respond to different screen sizes and content types. -This page describes how to do the following: +You can define a Grid container configuration to create flexible layouts that respond to different screen sizes and content types. This page describes how to do the following: - [Define a grid](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties#grid-definition): Set up the basic structure of rows and columns. - [Place items in a grid](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties#item-placement): Understand how items are placed into grid cells and how to change flow direction. @@ -9,13 +7,9 @@ This page describes how to do the following: ## Define a grid -A grid consists of columns and rows. -The [`Grid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Grid.composable#Grid(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) composable has a `config` parameter -that accepts a lambda to define the columns and rows -within [`GridConfigurationScope`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope). -The following example defines a grid that has three rows and two columns, -each with a fixed size specified in [`Dp`](https://developer.android.com/reference/kotlin/androidx/compose/ui/unit/Dp): +A grid consists of columns and rows. The [`Grid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Grid.composable#Grid(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) composable has a `config` parameter that accepts a lambda to define the columns and rows within [`GridConfigurationScope`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope). The following example defines a grid that has three rows and two columns, each with a fixed size specified in [`Dp`](https://developer.android.com/reference/kotlin/androidx/compose/ui/unit/Dp): +
```kotlin Grid( @@ -29,26 +23,18 @@ Grid( } ) { } + ```
## Place items in a grid -`Grid` takes the UI elements -in the `content` lambda and places them into grid cells. -The grid lays out items regardless of -whether you have explicitly defined the rows and columns. -By default, -`Grid` tries to place a UI element in the available grid cell in the row; -if it can't, it places it in an available grid cell in the next row. -If there are no empty cells, `Grid` creates a new row. +`Grid` takes the UI elements in the `content` lambda and places them into grid cells. The grid lays out items regardless of whether you have explicitly defined the rows and columns. By default, `Grid` tries to place a UI element in the available grid cell in the row; if it can't, it places it in an available grid cell in the next row. If there are no empty cells, `Grid` creates a new row. -In the following example, the grid has six grid cells -and places a card into each one (Figure 1). -Each grid cell is `160dp` x `90dp`, -making the total grid size `320dp` x `270dp`. +In the following example, the grid has six grid cells and places a card into each one (Figure 1). Each grid cell is `160dp` x `90dp`, making the total grid size `320dp` x `270dp`. +
```kotlin Grid( @@ -68,15 +54,16 @@ Grid( Card5() Card6() } + ```
![Six cards are placed in a grid that has three rows and two columns.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/grid/placement.png) **Figure 1**. Six cards are placed in a grid that has three rows and two columns. -To change this default behavior to filling by column, -set the [`flow`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#flow()) property to [`GridFlow.Column`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridFlow#Column()). +To change this default behavior to filling by column, set the [`flow`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#flow()) property to [`GridFlow.Column`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridFlow#Column()). +
```kotlin Grid( @@ -98,6 +85,7 @@ Grid( Card5() Card6() } + ```
@@ -106,17 +94,16 @@ Grid( ## Manage track sizing -Rows and columns are collectively referred to as a [grid track](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-track). -You can specify the size of a grid track using one of the following methods: +Rows and columns are collectively referred to as a [grid track](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-track). You can specify the size of a grid track using one of the following methods: - **Fixed** (`Dp`): Allocates a specific size (e.g., `column(180.dp)`). - **Percentage** (`Float`): Allocates a percentage of the total available space from `0.0f` to `1.0f` (e.g., `row(0.5f)` for 50%). - **Flexible** ([`Fr`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Fr)): Distributes remaining space proportionally after fixed and percentage tracks are calculated. For example, if two rows are set to `1.fr` and `3.fr`, the latter receives 75% of the remaining height. - **Intrinsic** : Sizes the track based on the content inside it. For more information, see [Determine grid track size intrinsically](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties#intrinsic-grid-track-size). -The following example uses the different track sizing options -to define the row heights: +The following example uses the different track sizing options to define the row heights: +
```kotlin Grid( @@ -136,6 +123,7 @@ Grid( PastelYellowCard("Auto") } + ```
@@ -144,14 +132,11 @@ Grid( ### Set the minimum size for flexible grid tracks -When a grid container has no remaining space, -a standard flexible track can shrink to `0.dp`. -To prevent this and ensure content isn't crushed, -use [`GridTrackSize.MinMax`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#MinMax(androidx.compose.ui.unit.Dp,androidx.compose.foundation.layout.Fr)) -to enforce an explicit minimum size while keeping the track flexible. +When a grid container has no remaining space, a standard flexible track can shrink to `0.dp`. To prevent this and ensure content isn't crushed, use [`GridTrackSize.MinMax`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#MinMax(androidx.compose.ui.unit.Dp,androidx.compose.foundation.layout.Fr)) to enforce an explicit minimum size while keeping the track flexible. The following example allocates at least `100.dp` to the first row: +
```kotlin Grid( @@ -171,6 +156,7 @@ Grid( PastelGreenCard("Flex(1.fr)") PastelBlueCard("Fixed(200.dp)") } + ```
@@ -179,18 +165,11 @@ Grid( ### Set the minimum grid track size to place lazy lists -Standard flexible tracks automatically query the intrinsic sizes of -their children to establish a base size. -However, Jetpack Compose prohibits querying the intrinsic sizes of -[`SubcomposeLayout`](https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/SubcomposeLayout.composable#SubcomposeLayout(androidx.compose.ui.Modifier,kotlin.Function2)), which backs components, -such as [`LazyColumn`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyColumn.composable) and [`LazyRow`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyRow.composable). +Standard flexible tracks automatically query the intrinsic sizes of their children to establish a base size. However, Jetpack Compose prohibits querying the intrinsic sizes of [`SubcomposeLayout`](https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/SubcomposeLayout.composable#SubcomposeLayout(androidx.compose.ui.Modifier,kotlin.Function2)), which backs components, such as [`LazyColumn`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyColumn.composable) and [`LazyRow`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyRow.composable). -Placing a lazy list inside a standard flexible track causes -an [`IllegalStateException`](https://developer.android.com/reference/java/lang/IllegalStateException) crash. -To safely place lazy lists inside a flexible grid track, -use `MinMax` with an explicit minimum size (such as `0.dp`) -to bypass the intrinsic measurement pass. +Placing a lazy list inside a standard flexible track causes an [`IllegalStateException`](https://developer.android.com/reference/java/lang/IllegalStateException) crash. To safely place lazy lists inside a flexible grid track, use `MinMax` with an explicit minimum size (such as `0.dp`) to bypass the intrinsic measurement pass. +
```kotlin Grid( @@ -205,7 +184,7 @@ Grid( }, modifier = Modifier.size(width = 170.dp, height = 240.dp) ) { - Text("Lazy column in a Grid") + Text("LazyColumn in a Grid") // The LazyColumn is placed in the second row, filling the remaining space. LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) { items(100) { number -> @@ -213,6 +192,7 @@ Grid( } } } + ```
@@ -221,20 +201,15 @@ Grid( ### Determine grid track size intrinsically -You can use [intrinsic sizing](https://developer.android.com/develop/ui/compose/layouts/intrinsic-measurements) for a `Grid` -when you want the layout to adapt to the content, -rather than forcing it into a fixed container. -The grid track size is determined with the following values: +You can use [intrinsic sizing](https://developer.android.com/develop/ui/compose/layouts/intrinsic-measurements) for a `Grid` when you want the layout to adapt to the content, rather than forcing it into a fixed container. The grid track size is determined with the following values: - [`GridTrackSize.MaxContent`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#MaxContent()): Use the content's maximum intrinsic size (e.g., the width is determined by the full length of the text in a text block with no wrapping). - [`GridTrackSize.MinContent`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#MinContent()): Use the content's minimum intrinsic size (e.g., the width is determined by the longest single word in a text block). - [`GridTrackSize.Auto`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#Auto()): Use a flexible size for a track that adapts based on available space. It behaves like `MaxContent` by default, but shrinks and wraps its content to fit within the parent container. -The following example places two texts side by side. -The column size for the first text is determined -by the required minimum width to display the text, -and the second column width depends on the required maximum width of the text. +The following example places two texts side by side. The column size for the first text is determined by the required minimum width to display the text, and the second column width depends on the required maximum width of the text. +
```kotlin Grid( @@ -248,6 +223,7 @@ Grid( Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras imperdiet.") Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras imperdiet.") } + ```
@@ -256,13 +232,9 @@ Grid( ## Set gaps between rows and columns -Once your grid tracks are sized, -you can modify the [grid gap](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-gap) to refine the spacing between the tracks. -You can specify the column gap with the [`columnGap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#columnGap(androidx.compose.ui.unit.Dp)) function, -and the row gap with [`rowGap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#rowGap(androidx.compose.ui.unit.Dp)). In the following example, -there is a `16dp` gap between each row, -and an `8dp` gap between each column (Figure 5). +Once your grid tracks are sized, you can modify the [grid gap](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-gap) to refine the spacing between the tracks. You can specify the column gap with the [`columnGap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#columnGap(androidx.compose.ui.unit.Dp)) function, and the row gap with [`rowGap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#rowGap(androidx.compose.ui.unit.Dp)). In the following example, there is a `16dp` gap between each row, and an `8dp` gap between each column (Figure 5). +
```kotlin Grid( @@ -284,17 +256,16 @@ Grid( Card5() Card6() } + ```
![Gaps between rows and columns.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/grid/gaps.png) **Figure 6**. Gaps between rows and columns. -You can also use the convenience function [`gap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#gap(androidx.compose.ui.unit.Dp)) -to define gaps of the same column and row size, -and to define column and gap sizes separately using a single function. -The following code adds `8dp` gaps to the grid: +You can also use the convenience function [`gap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#gap(androidx.compose.ui.unit.Dp)) to define gaps of the same column and row size, and to define column and gap sizes separately using a single function. The following code adds `8dp` gaps to the grid: +
```kotlin Grid( @@ -315,6 +286,7 @@ Grid( Card5() Card6() } + ```
\ No newline at end of file diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md index bb78a97..0a525c7 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md @@ -2,11 +2,10 @@ This page describes how to implement basic [`Grid`](https://developer.android.co ## Set up project -1. Add the [`androidx.compose.foundation.layout`](https://developer.android.com/jetpack/androidx/versions) library to your project's - `lib.versions.toml`. +1. Add the [`androidx.compose.foundation.layout`](https://developer.android.com/jetpack/androidx/versions) library to your project's `lib.versions.toml`. [versions] - compose = "1.12.0-beta02" + compose = "1.12.0-rc01" [libraries] androidx-compose-foundation-layout = { group = "androidx.compose.foundation", name = "foundation-layout", version.ref = "compose" } @@ -19,9 +18,9 @@ This page describes how to implement basic [`Grid`](https://developer.android.co ## Create a basic grid -The following example creates a basic 2x3 grid, -with the columns and rows having a fixed size of `100.dp`. +The following example creates a basic 2x3 grid, with the columns and rows having a fixed size of `100.dp`. +
```kotlin Grid( @@ -41,11 +40,11 @@ Grid( Card5(containerColor = PastelOrange) Card6(containerColor = PastelYellow) } + ```
![A basic grid consists of rows and columns with fixed size.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/grid/six-cards-in-grid.png) **Figure 1**. A basic grid consists of rows and columns with fixed size. -To learn how to implement more advanced grids, -see [Set container properties](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties) and [Set item properties](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/item-properties). \ No newline at end of file +To learn how to implement more advanced grids, see [Set container properties](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties) and [Set item properties](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/item-properties). \ No newline at end of file diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/index.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/index.md index 316b046..e48d9c9 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/index.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/index.md @@ -1,27 +1,16 @@ > [!NOTE] > **Note:** `Grid` is an experimental API and is subject to change. File any issues on the [issue tracker](https://issuetracker.google.com/issues/new?component=1876021&template=1424126). -[`Grid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Grid.composable#Grid(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) is a Jetpack Compose API -that lets you flexibly implement a two-dimensional layout. -With this API, you can display items in multi-column -or multi-row layouts that adapt to the available container size. +[`Grid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Grid.composable#Grid(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) is a Jetpack Compose API that lets you flexibly implement a two-dimensional layout. With this API, you can display items in multi-column or multi-row layouts that adapt to the available container size. ![A flexible and adaptive two-dimensional layout with Grid](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/grid/example.png) **Figure 1.** A flexible and adaptive two-dimensional layout with `Grid`. ## How is Grid different from similar composables? -Compose already offers similar components, such as [`LazyVerticalGrid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/grid/LazyVerticalGrid.composable#LazyVerticalGrid(androidx.compose.foundation.lazy.grid.GridCells,androidx.compose.ui.Modifier,androidx.compose.foundation.lazy.grid.LazyGridState,androidx.compose.foundation.layout.PaddingValues,kotlin.Boolean,androidx.compose.foundation.layout.Arrangement.Vertical,androidx.compose.foundation.layout.Arrangement.Horizontal,androidx.compose.foundation.gestures.FlingBehavior,kotlin.Boolean,androidx.compose.foundation.OverscrollEffect,kotlin.Function1)). -These components are mainly for visualization of large, homogeneous data sets--- -for example, displaying a content catalog in a video streaming app. -These components are NOT designed -for the structural layout of a screen or complex component. +Compose already offers similar components, such as [`LazyVerticalGrid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/grid/LazyVerticalGrid.composable#LazyVerticalGrid(androidx.compose.foundation.lazy.grid.GridCells,androidx.compose.ui.Modifier,androidx.compose.foundation.lazy.grid.LazyGridState,androidx.compose.foundation.layout.PaddingValues,kotlin.Boolean,androidx.compose.foundation.layout.Arrangement.Vertical,androidx.compose.foundation.layout.Arrangement.Horizontal,androidx.compose.foundation.gestures.FlingBehavior,kotlin.Boolean,androidx.compose.foundation.OverscrollEffect,kotlin.Function1)). These components are mainly for visualization of large, homogeneous data sets--- for example, displaying a content catalog in a video streaming app. These components are NOT designed for the structural layout of a screen or complex component. -You can also implement a two-dimensional layout -by combining multiple `Row` and `Column` composables. -However, this approach has some downsides, -such as deep hierarchies and difficulties in adaptability. +You can also implement a two-dimensional layout by combining multiple `Row` and `Column` composables. However, this approach has some downsides, such as deep hierarchies and difficulties in adaptability. -The following table provides an overview -of which layouts are suitable for each API: +The following table provides an overview of which layouts are suitable for each API: | Component | Purpose | |---|---| @@ -34,24 +23,16 @@ of which layouts are suitable for each API: ## Terminology -Familiarize yourself with the following terminology -to understand how `Grid` works. +Familiarize yourself with the following terminology to understand how `Grid` works. ### Grid line -A grid is made up of lines, which run horizontally and vertically. -If your grid has three rows, it has four horizontal lines, -including the one after the last row. -In the following image, each dotted line represents a grid line: +A grid is made up of lines, which run horizontally and vertically. If your grid has three rows, it has four horizontal lines, including the one after the last row. In the following image, each dotted line represents a grid line: ![The grid consists of four horizontal lines and three vertical lines.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/grid/grid-line.png) **Figure 2**. The grid consists of four horizontal lines and three vertical lines. ### Grid track -A grid track is the space between two grid lines. -A row track is between two horizontal lines, -and a column track is between two vertical lines. -To define the size of these tracks, -assign a size to them when you create the grid. +A grid track is the space between two grid lines. A row track is between two horizontal lines, and a column track is between two vertical lines. To define the size of these tracks, assign a size to them when you create the grid. ![A grid track for the first row.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/grid/grid-track.png) **Figure 3**. A grid track for the first row. ### Grid cell @@ -61,13 +42,10 @@ A grid cell is the intersection of a row and column track. ### Grid area -A grid area consists of several grid cells. -You can define a grid area by making an item span multiple tracks. +A grid area consists of several grid cells. You can define a grid area by making an item span multiple tracks. ![A grid area that consists of four grid cells.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/grid/grid-area.png) **Figure 5**. A grid area that consists of four grid cells. ### Grid gap -A grid gap is the gutter between grid tracks. -You can't place a UI element into a gap, -but you can span a UI element across it. +A grid gap is the gutter between grid tracks. You can't place a UI element into a gap, but you can span a UI element across it. ![A grid gap between the first column and the second column.](https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/grid/grid-gap.png) **Figure 6**. A grid gap between the first column and the second column. \ No newline at end of file diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/item-properties.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/item-properties.md index 9f0500e..5c8787c 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/item-properties.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/item-properties.md @@ -1,33 +1,18 @@ -While the `Grid` config defines the overall structure, -you use the [`gridItem`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridScope#(androidx.compose.ui.Modifier).gridItem(kotlin.Int,kotlin.Int,kotlin.Int,kotlin.Int,androidx.compose.ui.Alignment)) modifier to control the position, spanning, -and alignment of items within that structure. +While the `Grid` config defines the overall structure, you use the [`gridItem`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridScope#(androidx.compose.ui.Modifier).gridItem(kotlin.Int,kotlin.Int,kotlin.Int,kotlin.Int,androidx.compose.ui.Alignment)) modifier to control the position, spanning, and alignment of items within that structure. ## Set the item position -Place an item into a specific track or cell -with the `row` and `column` parameters. +Place an item into a specific track or cell with the `row` and `column` parameters. -The `row` and `column` parameters specify the row and column track indexes -that the item is placed in. -Track indexes are 1-based---they start at one. -Specifying only `row` or `column` (not both) places the item -in the next available space in that track. -Specifying both places the item into that cell. +The `row` and `column` parameters specify the row and column track indexes that the item is placed in. Track indexes are 1-based---they start at one. Specifying only `row` or `column` (not both) places the item in the next available space in that track. Specifying both places the item into that cell. -Use a positive integer to specify the track index from the start. -For example, to place an item in the first row and column, -use `gridItem(row = 1, column = 1)`. +Use a positive integer to specify the track index from the start. For example, to place an item in the first row and column, use `gridItem(row = 1, column = 1)`. -Use a negative integer to specify the track relative to the end. -For example, to place an item in the second-to-last row and column, use -`gridItem(row = -2, column = -2)`. +Use a negative integer to specify the track relative to the end. For example, to place an item in the second-to-last row and column, use `gridItem(row = -2, column = -2)`. -In the following example, Card **#2** is placed -in the second row and the second column. -Card **#3** is assigned to the last row (indexed by -1), -where it automatically occupies -the first available column in that track (Figure 1). +In the following example, Card **#2** is placed in the second row and the second column. Card **#3** is assigned to the last row (indexed by -1), where it automatically occupies the first available column in that track (Figure 1). +
```kotlin Grid( @@ -45,6 +30,7 @@ Grid( Card2(modifier = Modifier.gridItem(row = 2, column = 2)) Card3(modifier = Modifier.gridItem(row = -1, column = -2)) } + ```
@@ -55,16 +41,9 @@ and Card #3 is placed in the first column in the third row.](https://developer.a ## Span rows and columns -Use the `rowSpan` and `columnSpan` parameters -to span an item over multiple cells. -You can place a UI element into a [grid area](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-area), -which is the area consisting of several [grid cells](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-cell). -The `gridItem` modifier lets you specify the grid area -with the `rowSpan` and `columnSpan` parameters. -In the following example, -Card **#1** is placed in the area consisting of two rows and two columns -(Figure 2). +Use the `rowSpan` and `columnSpan` parameters to span an item over multiple cells. You can place a UI element into a [grid area](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-area), which is the area consisting of several [grid cells](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-cell). The `gridItem` modifier lets you specify the grid area with the `rowSpan` and `columnSpan` parameters. In the following example, Card **#1** is placed in the area consisting of two rows and two columns (Figure 2). +
```kotlin Grid( @@ -84,6 +63,7 @@ Grid( Card3() Card4(modifier = Modifier.gridItem(columnSpan = 3)) } + ```
@@ -92,11 +72,9 @@ Grid( ## Set the alignment in a grid area -You can set the alignment of the UI element in a grid area -by specifying it in the `alignment` parameter of the [`gridItem`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridScope#(androidx.compose.ui.Modifier).gridItem(kotlin.Int,kotlin.Int,kotlin.Int,kotlin.Int,androidx.compose.ui.Alignment)) modifier. -In the following example, **#1** is placed in the center of the grid area -consisting of two columns and two rows. +You can set the alignment of the UI element in a grid area by specifying it in the `alignment` parameter of the [`gridItem`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridScope#(androidx.compose.ui.Modifier).gridItem(kotlin.Int,kotlin.Int,kotlin.Int,kotlin.Int,androidx.compose.ui.Alignment)) modifier. In the following example, **#1** is placed in the center of the grid area consisting of two columns and two rows. +
```kotlin Grid( @@ -124,6 +102,7 @@ Grid( Card3() Card4(modifier = Modifier.gridItem(columnSpan = 3)) } + ```
@@ -133,13 +112,9 @@ consisting of two rows and two columns.](https://developer.android.com/static/de ## Auto-placement mixed with placed items -A UI element in `Grid` -that has no position specification undergoes auto-placement. -This example shows how you can mix auto-placed elements -and the UI elements with specified grid cells. -Card **#2** and Card **#4** are placed in specified grid cells, -and the other items are auto-placed. +A UI element in `Grid` that has no position specification undergoes auto-placement. This example shows how you can mix auto-placed elements and the UI elements with specified grid cells. Card **#2** and Card **#4** are placed in specified grid cells, and the other items are auto-placed. +
```kotlin Grid( @@ -161,6 +136,7 @@ Grid( Card5() Card6() } + ```
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md index 4cd2564..f9fb3ed 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md @@ -1,10 +1,7 @@ > [!NOTE] > **Note:** The `mediaQuery` function and the related data types are experimental and subject to change. File any issues on the [issue tracker](https://issuetracker.google.com/issues?q=componentid:1876021). -You need various types of information, such as device capability -and app status, to update your app layout. -Window width and height are the most commonly used information. -In addition to that, you can refer to the following information: +You need various types of information, such as device capability and app status, to update your app layout. Window width and height are the most commonly used information. In addition to that, you can refer to the following information: - Window posture - Pointing devices precision @@ -12,13 +9,9 @@ In addition to that, you can refer to the following information: - Whether the camera and microphone are supported by the device - The distance between a user and the device display -Because the information is updated dynamically, -you need to monitor it and trigger recomposition when any update happens. -The [`mediaQuery`](https://developer.android.com/reference/kotlin/androidx/compose/ui/mediaQuery.composable#mediaQuery(kotlin.Function1)) function abstracts the details of the information retrieval -and lets you focus on defining the condition to trigger the layout updates. -The following example switches the layout to `TabletopLayout` -when the foldable posture is tabletop: +Because the information is updated dynamically, you need to monitor it and trigger recomposition when any update happens. The [`mediaQuery`](https://developer.android.com/reference/kotlin/androidx/compose/ui/mediaQuery.composable#mediaQuery(kotlin.Function1)) function abstracts the details of the information retrieval and lets you focus on defining the condition to trigger the layout updates. The following example switches the layout to `TabletopLayout` when the foldable posture is tabletop: +
```kotlin @Composable @@ -33,16 +26,16 @@ fun VideoPlayer( } // ... } + ```
## Enable the `mediaQuery` function -To enable the `mediaQuery` function, -set the `isMediaQueryIntegrationEnabled` attribute of -the [`ComposeUiFlags`](https://developer.android.com/reference/kotlin/androidx/compose/ui/ComposeUiFlags) object to `true`: +To enable the `mediaQuery` function, set the `isMediaQueryIntegrationEnabled` attribute of the [`ComposeUiFlags`](https://developer.android.com/reference/kotlin/androidx/compose/ui/ComposeUiFlags) object to `true`: +
```kotlin class MyApplication : Application() { @@ -51,20 +44,14 @@ class MyApplication : Application() { super.onCreate() } } + ```
## Define a condition with parameters -You can define a condition as a lambda -that is evaluated within [`UiMediaScope`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope). -The `mediaQuery` function evaluates the condition according to -the current status and the device capabilities. -The function returns a boolean value, -so you can determine the layout with conditional branches -like an `if` expression. -Table 1 describes the parameters available in `UiMediaScope`. +You can define a condition as a lambda that is evaluated within [`UiMediaScope`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope). The `mediaQuery` function evaluates the condition according to the current status and the device capabilities. The function returns a boolean value, so you can determine the layout with conditional branches like an `if` expression. Table 1 describes the parameters available in `UiMediaScope`. | Parameter | Value type | Description | |---|---|---| @@ -77,17 +64,9 @@ Table 1 describes the parameters available in `UiMediaScope`. | `hasMicrophone` | `Boolean` | Whether the microphone is supported on the device. | | `viewingDistance` | [`UiMediaScope.ViewingDistance`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance) | The typical distance between the user and the device screen. | -A `UiMediaScope` object resolves the values of the parameters. -The `mediaQuery` function uses [`LocalUiMediaScope.current`](https://developer.android.com/reference/kotlin/androidx/compose/ui/package-summary#LocalUiMediaScope()) -to access the `UiMediaScope` object, -which represents the current device capabilities and context. -This object is dynamically updated when any changes are made, -such as when the user changes the device posture. -The `mediaQuery` function then evaluates the `query` lambda -with the updated `UiMediaScope` object and returns a boolean value. -For example, the following snippet chooses between `TabletopLayout` -and `FlatLayout` based on the `windowPosture` parameter value. +A `UiMediaScope` object resolves the values of the parameters. The `mediaQuery` function uses [`LocalUiMediaScope.current`](https://developer.android.com/reference/kotlin/androidx/compose/ui/package-summary#LocalUiMediaScope()) to access the `UiMediaScope` object, which represents the current device capabilities and context. This object is dynamically updated when any changes are made, such as when the user changes the device posture. The `mediaQuery` function then evaluates the `query` lambda with the updated `UiMediaScope` object and returns a boolean value. For example, the following snippet chooses between `TabletopLayout` and `FlatLayout` based on the `windowPosture` parameter value. +
```kotlin @Composable @@ -102,26 +81,18 @@ fun VideoPlayer( } // ... } + ```
### Make a decision based on the window size -[Window size classes](https://developer.android.com/develop/ui/compose/layouts/adaptive/use-window-size-classes) are a set of opinionated viewport breakpoints -that help you design, develop, and test adaptive layouts. -You can compare the two parameters representing the current window size -with the threshold defined in the window size classes. -The following example changes the number of panes according to the window width. -[`WindowSizeClass`](https://developer.android.com/reference/androidx/window/core/layout/WindowSizeClass) class has constants for the thresholds -of window size classes (Figure 1). +[Window size classes](https://developer.android.com/develop/ui/compose/layouts/adaptive/use-window-size-classes) are a set of opinionated viewport breakpoints that help you design, develop, and test adaptive layouts. You can compare the two parameters representing the current window size with the threshold defined in the window size classes. The following example changes the number of panes according to the window width. [`WindowSizeClass`](https://developer.android.com/reference/androidx/window/core/layout/WindowSizeClass) class has constants for the thresholds of window size classes (Figure 1). -The [`derivedMediaQuery`](https://developer.android.com/reference/kotlin/androidx/compose/ui/derivedMediaQuery.composable#derivedMediaQuery(kotlin.Function1)) function evaluates the `query` lambda -and wraps the result in a [`derivedStateOf`](https://developer.android.com/develop/ui/compose/side-effects#derivedstateof). -Because `windowWidth` and `windowHeight` can update frequently, -call the `derivedMediaQuery` function instead of the `mediaQuery` function -when you refer to those parameters in the `query` lambda. +The [`derivedMediaQuery`](https://developer.android.com/reference/kotlin/androidx/compose/ui/derivedMediaQuery.composable#derivedMediaQuery(kotlin.Function1)) function evaluates the `query` lambda and wraps the result in a [`derivedStateOf`](https://developer.android.com/develop/ui/compose/side-effects#derivedstateof). Because `windowWidth` and `windowHeight` can update frequently, call the `derivedMediaQuery` function instead of the `mediaQuery` function when you refer to those parameters in the `query` lambda. +
```kotlin val narrowerThanMedium by derivedMediaQuery { @@ -135,6 +106,7 @@ when { narrowerThanExpanded -> TwoPaneLayout() else -> ThreePaneLayout() } + ```
@@ -143,12 +115,9 @@ when { ### Update layout according to the window posture -The `windowPosture` parameter describes the current window posture -as a `UiMediaScope.Posture` object. -You can check the current [posture](https://developer.android.com/develop/ui/compose/layouts/adaptive/foldables/learn-about-foldables) by comparing the parameter -with the values defined in the `UiMediaScope.Posture` class. -The following example switches layout according to the window posture: +The `windowPosture` parameter describes the current window posture as a `UiMediaScope.Posture` object. You can check the current [posture](https://developer.android.com/develop/ui/compose/layouts/adaptive/foldables/learn-about-foldables) by comparing the parameter with the values defined in the `UiMediaScope.Posture` class. The following example switches layout according to the window posture: +
```kotlin when { @@ -156,32 +125,22 @@ when { mediaQuery { windowPosture == UiMediaScope.Posture.Book } -> BookLayout() mediaQuery { windowPosture == UiMediaScope.Posture.Flat } -> FlatLayout() } + ```
### Check the precision of the available pointing device -A high precision pointing device helps users to point a UI element precisely. -The precision of a pointing device depends on the device type. +A high precision pointing device helps users to point a UI element precisely. The precision of a pointing device depends on the device type. -The `pointerPrecision` parameter describes the precision -of the available pointing devices, such as a mouse and touchscreen. -There are four values defined in the `UiMediaScope.PointerPrecision` class: -[`Fine`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Fine()), [`Coarse`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Coarse()), [`Blunt`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Blunt()), and [`None`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#None()). -`None` means that no pointing device is available. -The precision ranges from highest to lowest in this order: -`Fine`, `Coarse`, and `Blunt`. +The `pointerPrecision` parameter describes the precision of the available pointing devices, such as a mouse and touchscreen. There are four values defined in the `UiMediaScope.PointerPrecision` class: [`Fine`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Fine()), [`Coarse`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Coarse()), [`Blunt`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Blunt()), and [`None`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#None()). `None` means that no pointing device is available. The precision ranges from highest to lowest in this order: `Fine`, `Coarse`, and `Blunt`. -If multiple pointing devices are available and their precisions are different, -the parameter is resolved with the highest one. -For example, if there are two pointing devices --- a `Fine` precision device and -a `Blunt` precision device --- -`Fine` is the value of the `pointerPrecision` parameter. +If multiple pointing devices are available and their precisions are different, the parameter is resolved with the highest one. For example, if there are two pointing devices --- a `Fine` precision device and a `Blunt` precision device --- `Fine` is the value of the `pointerPrecision` parameter. -The following example shows a larger button -when the user is using a pointing device with low precision: +The following example shows a larger button when the user is using a pointing device with low precision: +
```kotlin if (mediaQuery { pointerPrecision == UiMediaScope.PointerPrecision.Blunt }) { @@ -189,38 +148,31 @@ if (mediaQuery { pointerPrecision == UiMediaScope.PointerPrecision.Blunt }) { } else { NormalSizeButton() } + ```
### Check the available keyboard type -The `keyboardKind` parameter represents the type of the available keyboards: -[`Physical`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#Physical()), [`Virtual`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#Virtual()), and [`None`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#None()). -If an on-screen keyboard is displayed and -a hardware keyboard is available at the same time, -the parameter is resolved as `Physical`. -If neither is detected, `None` is the value of the parameter. -The following example shows a message suggesting that users connect a keyboard -when no keyboard is detected: +The `keyboardKind` parameter represents the type of the available keyboards: [`Physical`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#Physical()), [`Virtual`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#Virtual()), and [`None`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#None()). If an on-screen keyboard is displayed and a hardware keyboard is available at the same time, the parameter is resolved as `Physical`. If neither is detected, `None` is the value of the parameter. The following example shows a message suggesting that users connect a keyboard when no keyboard is detected: +
```kotlin if (mediaQuery { keyboardKind == UiMediaScope.KeyboardKind.None }) { SuggestKeyboardConnect() } + ```
### Check if the device supports camera and microphone -Some devices don't support cameras or microphones. -You can check if the device supports a camera and a microphone -with the `hasCamera` parameter and the `hasMicrophone` parameter. -The following example shows buttons to use with camera and microphone -when the device supports them: +Some devices don't support cameras or microphones. You can check if the device supports a camera and a microphone with the `hasCamera` parameter and the `hasMicrophone` parameter. The following example shows buttons to use with camera and microphone when the device supports them: +
```kotlin Row { @@ -234,25 +186,18 @@ Row { CameraButton() } } + ```
### Adjust UI with the estimated viewing distance -Viewing distance is a factor that helps determine layout. -If the user is using the app from a distance, -they would expect the text and UI elements to be bigger. -The `viewingDistance` parameter provides an estimate of the viewing distance -based on the device type and its typical usage context. +Viewing distance is a factor that helps determine layout. If the user is using the app from a distance, they would expect the text and UI elements to be bigger. The `viewingDistance` parameter provides an estimate of the viewing distance based on the device type and its typical usage context. -There are three values defined in the `UiMediaScope.ViewingDistance` class: -[`Near`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Near()), [`Medium`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Medium()), and [`Far`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Far()). -`Near` means that the screen is in close range, -and `Far` means that the device is viewed from a distance. -The following example increases the font size when the viewing distance is -`Far` or `Medium`: +There are three values defined in the `UiMediaScope.ViewingDistance` class: [`Near`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Near()), [`Medium`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Medium()), and [`Far`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Far()). `Near` means that the screen is in close range, and `Far` means that the device is viewed from a distance. The following example increases the font size when the viewing distance is `Far` or `Medium`: +
```kotlin val fontSize = when { @@ -260,19 +205,16 @@ val fontSize = when { mediaQuery { viewingDistance == UiMediaScope.ViewingDistance.Medium } -> 18.sp else -> 16.sp } + ```
## Preview a UI component -You can call the `mediaQuery` and `derivedMediaQuery` functions in the -composable functions to preview UI components. -The following snippet chooses between `TabletopLayout` -and `FlatLayout` based on the `windowPosture` parameter value. -To preview the `TabletopLayout`, the `windowPosture` parameter should be -[`UiMediaScope.Posture.Tabletop`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.Posture#Tabletop()). +You can call the `mediaQuery` and `derivedMediaQuery` functions in the composable functions to preview UI components. The following snippet chooses between `TabletopLayout` and `FlatLayout` based on the `windowPosture` parameter value. To preview the `TabletopLayout`, the `windowPosture` parameter should be [`UiMediaScope.Posture.Tabletop`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.Posture#Tabletop()). +
```kotlin when { @@ -280,14 +222,12 @@ when { mediaQuery { windowPosture == UiMediaScope.Posture.Book } -> BookLayout() mediaQuery { windowPosture == UiMediaScope.Posture.Flat } -> FlatLayout() } + ```
-The `mediaQuery` and `derivedMediaQuery` functions evaluate -the given `query` lambda within a `UiMediaScope` object, -which is provided as `LocalUiMediaScope.current`. -You can override it with the following steps: +The `mediaQuery` and `derivedMediaQuery` functions evaluate the given `query` lambda within a `UiMediaScope` object, which is provided as `LocalUiMediaScope.current`. You can override it with the following steps: 1. Enable the `mediaQuery` function. 2. Define a custom object that implements the `UiMediaScope` interface. @@ -296,6 +236,7 @@ You can override it with the following steps: You can preview the `TabletopLayout` with the following example: +
```kotlin @Preview @@ -324,6 +265,7 @@ fun PreviewLayoutForTabletop() { } } } + ```
\ No newline at end of file diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/tooling/debug.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/tooling/debug.md index 023836f..027181b 100644 --- a/jetpack-compose/adaptive/references/android/develop/ui/compose/tooling/debug.md +++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/tooling/debug.md @@ -2,60 +2,29 @@ Tools for debugging your Compose UI are available in Android Studio. ## Layout Inspector -Layout Inspector lets you inspect a Compose layout inside a running app in an -emulator or physical device. You can use the Layout Inspector to check how often -a composable is recomposed or skipped, which can help identify issues with your -app. For example, some coding errors might force your UI to recompose -excessively, which can cause [poor performance](https://developer.android.com/develop/ui/compose/performance). -Some coding errors can prevent your UI from recomposing and, therefore, -prevent your UI changes from showing up on the screen. If you're new to -Layout inspector, check the [guidance](https://developer.android.com/studio/debug/layout-inspector) on how to -run it. +Layout Inspector lets you inspect a Compose layout inside a running app in an emulator or physical device. You can use the Layout Inspector to check how often a composable is recomposed or skipped, which can help identify issues with your app. For example, some coding errors might force your UI to recompose excessively, which can cause [poor performance](https://developer.android.com/develop/ui/compose/performance). Some coding errors can prevent your UI from recomposing and, therefore, prevent your UI changes from showing up on the screen. If you're new to Layout inspector, check the [guidance](https://developer.android.com/studio/debug/layout-inspector) on how to run it. > [!NOTE] > **Note:** If you're not seeing Compose components in layout inspector, make sure you are not removing `META-INF/androidx.compose.*.version` files from the APK. These are required for layout inspector to work. ### Get recomposition counts -When debugging your Compose layouts, knowing when composables -[recompose](https://developer.android.com/develop/ui/compose/mental-model#recomposition) is important in -understanding whether your UI is implemented properly. For example, if it's -recomposing too many times, your app might be doing more work than is necessary. -On the other hand, components that don't recompose when you anticipate them to -can lead to unexpected behaviors. +When debugging your Compose layouts, knowing when composables [recompose](https://developer.android.com/develop/ui/compose/mental-model#recomposition) is important in understanding whether your UI is implemented properly. For example, if it's recomposing too many times, your app might be doing more work than is necessary. On the other hand, components that don't recompose when you anticipate them to can lead to unexpected behaviors. -The Layout Inspector shows you when discrete composables in your layout -hierarchy have either recomposed or skipped, as you interact with your app. In -Android Studio, your recompositions are highlighted to help you determine -where in the UI your composables are recomposing. +The Layout Inspector shows you when discrete composables in your layout hierarchy have either recomposed or skipped, as you interact with your app. In Android Studio, your recompositions are highlighted to help you determine where in the UI your composables are recomposing. **Figure 1.** Recompositions are highlighted in Layout Inspector. -The highlighted portion shows a gradient overlay of the composable in the image -section of the Layout Inspector, and gradually disappears so that you can get an -idea of where in the UI the composable with the highest recompositions can be -found. If one composable is recomposing at a higher rate than another -composable, then the first composable receives a stronger gradient overlay -color. If you double-click a composable in the layout inspector, you're taken to -the corresponding code for analysis. +The highlighted portion shows a gradient overlay of the composable in the image section of the Layout Inspector, and gradually disappears so that you can get an idea of where in the UI the composable with the highest recompositions can be found. If one composable is recomposing at a higher rate than another composable, then the first composable receives a stronger gradient overlay color. If you double-click a composable in the layout inspector, you're taken to the corresponding code for analysis. > [!NOTE] > **Note:** To view recomposition counts, make sure your app is using an API level of 29 or higher, and `Compose 1.2.0` or higher. Then, deploy your app as you normally would. ![](https://developer.android.com/static/develop/ui/compose/images/li-recomposition-counts.png) **Figure 2.**The composition and skip counter in Layout Inspector. -Open the **Layout Inspector** window and connect to your app process. In the -**Component Tree** , there are two columns that appear next to the layout -hierarchy. The first column shows the number of compositions for each node and -the second column displays the number of skips for each node. Selecting a -composable node shows the dimensions and parameters of the composable, unless -it's an inline function, in which case the parameters can't be shown. You can -also see similar information in the **Attributes** pane when you select a -composable from the **Component Tree** or the **Layout Display**. +Open the **Layout Inspector** window and connect to your app process. In the **Component Tree** , there are two columns that appear next to the layout hierarchy. The first column shows the number of compositions for each node and the second column displays the number of skips for each node. Selecting a composable node shows the dimensions and parameters of the composable, unless it's an inline function, in which case the parameters can't be shown. You can also see similar information in the **Attributes** pane when you select a composable from the **Component Tree** or the **Layout Display**. -Resetting the count can help you understand recompositions or skips during a -specific interaction with your app. If you want to reset the count, click -**Reset** near the top of the **Component Tree** pane. +Resetting the count can help you understand recompositions or skips during a specific interaction with your app. If you want to reset the count, click **Reset** near the top of the **Component Tree** pane. > [!NOTE] > **Note:** If you don't see the new columns in the **Component Tree** pane, you can view them by selecting **Show Recomposition Counts** from the **View Options** menu ![Layout Inspector View Options @@ -68,47 +37,24 @@ Inspector](https://developer.android.com/static/develop/ui/compose/images/li-sho ### Compose semantics -In Compose, [Semantics](https://developer.android.com/develop/ui/compose/accessibility/semantics) describe your UI in an -alternative manner that is understandable for -[Accessibility](https://developer.android.com/develop/ui/compose/accessibility) services and for the -[Testing](https://developer.android.com/develop/ui/compose/testing) framework. You can use the Layout Inspector -to inspect semantic information in your Compose layouts. +In Compose, [Semantics](https://developer.android.com/develop/ui/compose/accessibility/semantics) describe your UI in an alternative manner that is understandable for [Accessibility](https://developer.android.com/develop/ui/compose/accessibility) services and for the [Testing](https://developer.android.com/develop/ui/compose/testing) framework. You can use the Layout Inspector to inspect semantic information in your Compose layouts. ![Semantic information displayed using the Layout Inspector.](https://developer.android.com/static/develop/ui/compose/images/layout_inspector_semantics_new.png) **Figure 4.** Semantic information displayed using the Layout Inspector. -When selecting a Compose node, use the **Attributes** pane to check whether it -declares semantic information directly, merges semantics from its children, or -both. To quickly identify which nodes include semantics, either declared or -merged, use select the **View options** drop-down in the **Component Tree** pane -and select **Highlight Semantics Layers**. This highlights only the nodes in the -tree that include semantics, and you can use your keyboard to quickly navigate -between them. +When selecting a Compose node, use the **Attributes** pane to check whether it declares semantic information directly, merges semantics from its children, or both. To quickly identify which nodes include semantics, either declared or merged, use select the **View options** drop-down in the **Component Tree** pane and select **Highlight Semantics Layers**. This highlights only the nodes in the tree that include semantics, and you can use your keyboard to quickly navigate between them. ## Compose UI Check -To help you build more adaptive and accessible UIs in Jetpack Compose, Android -Studio provides a UI Check mode in Compose Preview. This feature is similar -to [Accessibility Scanner](https://developer.android.com/guide/topics/ui/accessibility/testing#accessibility-scanner) -for views. +To help you build more adaptive and accessible UIs in Jetpack Compose, Android Studio provides a UI Check mode in Compose Preview. This feature is similar to [Accessibility Scanner](https://developer.android.com/guide/topics/ui/accessibility/testing#accessibility-scanner) for views. -When you activate Compose UI check mode on a Compose Preview, Android Studio -automatically audits your Compose UI and suggests improvements to make your UI -more accessible and adaptive. Android Studio checks that your UI works across -different screen sizes. In the **Problems** panel, the tool shows the issues -that it detects, such as text stretched on large screens or low color contrast. +When you activate Compose UI check mode on a Compose Preview, Android Studio automatically audits your Compose UI and suggests improvements to make your UI more accessible and adaptive. Android Studio checks that your UI works across different screen sizes. In the **Problems** panel, the tool shows the issues that it detects, such as text stretched on large screens or low color contrast. To access this feature, click the UI Check icon on Compose Preview: ![](https://developer.android.com/static/studio/images/design/compose-ui-check-entry.png) **Figure 5.** Entry point to UI check mode. -UI check automatically previews your UI in different configurations and -highlights issues found in different configurations. In the **Problems** panel, -when you click an issue, you can see the details of the issue, suggested fixes, -and the renderings that highlight the area of the issue. +UI check automatically previews your UI in different configurations and highlights issues found in different configurations. In the **Problems** panel, when you click an issue, you can see the details of the issue, suggested fixes, and the renderings that highlight the area of the issue. ![](https://developer.android.com/static/studio/images/design/compose-ui-check.png) **Figure 6.** UI check mode in action. ### Fix with AI -For issues detected in UI Check mode, you can use the AI agent to propose and -apply code fixes. Click the **Fix with AI** button on an issue in the -**Problems** panel. The agent analyzes the problem and your code to suggest -changes that resolve the accessibility or adaptive issue. +For issues detected in UI Check mode, you can use the AI agent to propose and apply code fixes. Click the **Fix with AI** button on an issue in the **Problems** panel. The agent analyzes the problem and your code to suggest changes that resolve the accessibility or adaptive issue. ![](https://developer.android.com/static/studio/preview/features/images/ui-check-mode-single-fix.png) **Figure 7.** The agent fixes UI issues in UI Check mode. \ No newline at end of file diff --git a/jetpack-compose/adaptive/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md b/jetpack-compose/adaptive/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md index fbaae79..032a997 100644 --- a/jetpack-compose/adaptive/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md +++ b/jetpack-compose/adaptive/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md @@ -138,4 +138,6 @@ class MaterialListDetailActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/SKILL.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/SKILL.md index ea25f8e..c51cc9d 100644 --- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/SKILL.md +++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/SKILL.md @@ -9,7 +9,7 @@ description: Provides a structured workflow for migrating an Android XML View to license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-02' + last-updated: '2026-08-06' keywords: - Jetpack Compose - migration @@ -20,16 +20,11 @@ metadata: - UI development --- -This skill guides through the process of migrating an existing Android XML View -to Jetpack Compose. It performs a stable, safe and visually consistent -transition by following a structured, 10-step methodology. This skill migrates -UI (XML to Jetpack Compose) only. +This skill guides through the process of migrating an existing Android XML View to Jetpack Compose. It performs a stable, safe and visually consistent transition by following a structured, 10-step methodology. This skill migrates UI (XML to Jetpack Compose) only. ## Objective -To systematically convert a single legacy XML layout into modern, declarative -Jetpack Compose UI while maintaining pixel-perfect visual parity and functional -integrity. +To systematically convert a single legacy XML layout into modern, declarative Jetpack Compose UI while maintaining pixel-perfect visual parity and functional integrity. ## Summary of the 10-step migration process @@ -48,61 +43,31 @@ integrity. ### Step 1: Identify the optimal XML candidate for migration -If the user has explicitly specified a target XML layout, proceed to Step 2. -Otherwise, analyze the codebase to identify the best candidate for migration by -following the logic in [references/identify-optimal-xml-candidate.md](references/identify-optimal-xml-candidate.md). +If the user has explicitly specified a target XML layout, proceed to Step 2. Otherwise, analyze the codebase to identify the best candidate for migration by following the logic in [references/identify-optimal-xml-candidate.md](references/identify-optimal-xml-candidate.md). ### Step 2: Analyze the project and layout -Analyze the identified XML View's structure, hierarchy, and implementation -details. -Use [references/analysis-of-the-project-and-layout.md](references/analysis-of-the-project-and-layout.md) to -guide your technical audit of the layout and surrounding project context. +Analyze the identified XML View's structure, hierarchy, and implementation details. Use [references/analysis-of-the-project-and-layout.md](references/analysis-of-the-project-and-layout.md) to guide your technical audit of the layout and surrounding project context. ### Step 3: Create a plan -Using the outputs and analysis done in the Step 1 and 2, generate a -step-by-step plan for the migration. If you support user interaction, present -to the user and ask for approval before proceeding. If user interaction is not -supported, proceed to Step 4 following the generated plan. +Using the outputs and analysis done in the Step 1 and 2, generate a step-by-step plan for the migration. If you support user interaction, present to the user and ask for approval before proceeding. If user interaction is not supported, proceed to Step 4 following the generated plan. ### Step 4: Capture the XML View UI -**IF** you support user interaction, ask the user to upload a screenshot of the -XML View UI or provide an absolute path to a file. Use this image as a visual -reference for the layout migration in Step 7. -**ELSE IF** you are able to run an Android emulator, locate an existing -screenshot test for the XML candidate. If none exists, create one using the -existing project testing framework. If no framework exists, -use **UI Automator** or **Espresso** to create a screenshot test with minimum -required setup. Run the test and take a baseline screenshot of the XML UI. -**ELSE** proceed to Step 5. +**IF** you support user interaction, ask the user to upload a screenshot of the XML View UI or provide an absolute path to a file. Use this image as a visual reference for the layout migration in Step 7. **ELSE IF** you are able to run an Android emulator, locate an existing screenshot test for the XML candidate. If none exists, create one using the existing project testing framework. If no framework exists, use **UI Automator** or **Espresso** to create a screenshot test with minimum required setup. Run the test and take a baseline screenshot of the XML UI. **ELSE** proceed to Step 5. ### Step 5: Set up Compose dependencies and compiler -Check `build.gradle` or `libs.versions.toml` for Compose dependencies and -compiler setup. If missing, use -[Setup Compose Dependencies and Compiler](references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md). -Run a sync to ensure dependencies resolve without errors. +Check `build.gradle` or `libs.versions.toml` for Compose dependencies and compiler setup. If missing, use [Setup Compose Dependencies and Compiler](references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md). Run a sync to ensure dependencies resolve without errors. ### Step 6: Set up Compose theming -If the project already has Compose theming set up, proceed to Step 7. If Compose -theming is missing, initialize it. For Material-based projects, follow -[Material 3 migration guidelines](references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md). -For custom design systems, apply expert judgment to migrate XML theming and -match existing styles. -**Constraints:** Do not migrate the entire theme. Implement only the minimum -theming required for the specific XML candidate. Maintain original XML themes -for interoperability. Maintain existing project code conventions, patterns, -names and values. +If the project already has Compose theming set up, proceed to Step 7. If Compose theming is missing, initialize it. For Material-based projects, follow [Material 3 migration guidelines](references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md). For custom design systems, apply expert judgment to migrate XML theming and match existing styles. **Constraints:** Do not migrate the entire theme. Implement only the minimum theming required for the specific XML candidate. Maintain original XML themes for interoperability. Maintain existing project code conventions, patterns, names and values. ### Step 7: Migrate the XML View to Compose -Convert the XML candidate to Jetpack Compose code, referencing -[references/xml-layout-migration.md](references/xml-layout-migration.md) and the image from Step 4. -You must include a **Compose Preview** for the newly created composable to -facilitate visual verification. +Convert the XML candidate to Jetpack Compose code, referencing [references/xml-layout-migration.md](references/xml-layout-migration.md) and the image from Step 4. You must include a **Compose Preview** for the newly created composable to facilitate visual verification. ### Step 8: Replace usages @@ -113,12 +78,8 @@ Replace the usages of the migrated XML layout to use the new Compose component. ### Step 9: Validate the migration -Compare the baseline screenshot image from Step 4 with the rendered Compose -Preview of the new composable. Ignore string content; focus on layout and -styling. Iterate on the Compose code until visual parity is achieved. Once -verified, write a Compose UI test for the new composable. +Compare the baseline screenshot image from Step 4 with the rendered Compose Preview of the new composable. Ignore string content; focus on layout and styling. Iterate on the Compose code until visual parity is achieved. Once verified, write a Compose UI test for the new composable. ### Step 10: XML code removal -Delete the migrated XML file and its associated legacy tests. **Caution:** Only -remove code and resources that are not referenced by other parts of the project. +Delete the migrated XML file and its associated legacy tests. **Caution:** Only remove code and resources that are not referenced by other parts of the project. diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/analysis-of-the-project-and-layout.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/analysis-of-the-project-and-layout.md index 3e2f0c3..8b34a75 100644 --- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/analysis-of-the-project-and-layout.md +++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/analysis-of-the-project-and-layout.md @@ -1,41 +1,22 @@ ## 1. Project health \& build validation -Before performing any analysis, you must confirm the project is in a functional state. -\* **Integrity check:** Verify the project syncs (Gradle) and builds successfully. -\* **Error resolution:** If there are pre-existing build errors or sync failures, you must report these immediately and attempt to fix. **Do not proceed** with migration until a stable baseline is established. +Before performing any analysis, you must confirm the project is in a functional state. \* **Integrity check:** Verify the project syncs (Gradle) and builds successfully. \* **Error resolution:** If there are pre-existing build errors or sync failures, you must report these immediately and attempt to fix. **Do not proceed** with migration until a stable baseline is established. ## 2. Compose pattern \& consistency analysis -If Jetpack Compose is already present, you must align with the established implementation style. -\* **Pattern identification:** Scan the codebase for `@Composable` functions. Identify the project's "Best Practices" regarding state hoisting, composable construction and naming conventions, and file organization. -\* **Theming review:** Determine how `MaterialTheme` or custom theme systems are implemented. -\* Identify if the project uses a custom design system theme. -\* Map how attributes, styles, and other theme components are accessed in Compose. +If Jetpack Compose is already present, you must align with the established implementation style. \* **Pattern identification:** Scan the codebase for `@Composable` functions. Identify the project's "Best Practices" regarding state hoisting, composable construction and naming conventions, and file organization. \* **Theming review:** Determine how `MaterialTheme` or custom theme systems are implemented. \* Identify if the project uses a custom design system theme. \* Map how attributes, styles, and other theme components are accessed in Compose. ## 3. Design system \& infrastructure audit -Understand the design system classification (e.g. Material 2, Material 3, or custom design system). -\* **Resource mapping:** Locate central XML definitions: -\* `colors.xml` (Light/Dark variants) -\* `dimens.xml` -\* `styles.xml` / `themes.xml` -\* **Hybrid analysis:** Determine if the project is **XML-only** , **Compose-only** , or **Hybrid** . -\* **Reuse constraint:** If a Compose theming layer (e.g., `AppTheme.kt`) already exists, **DO NOT** generate a new one. You must reuse the existing infrastructure and contribute to it by following its existing implementation pattern. +Understand the design system classification (e.g. Material 2, Material 3, or custom design system). \* **Resource mapping:** Locate central XML definitions: \* `colors.xml` (Light/Dark variants) \* `dimens.xml` \* `styles.xml` / `themes.xml` \* **Hybrid analysis:** Determine if the project is **XML-only** , **Compose-only** , or **Hybrid** . \* **Reuse constraint:** If a Compose theming layer (e.g., `AppTheme.kt`) already exists, **DO NOT** generate a new one. You must reuse the existing infrastructure and contribute to it by following its existing implementation pattern. ## 4. Candidate layout decomposition -Analyze the specific XML layout targeted for migration. You must extract and document the following requirements for the new composable: -\* **Inputs:** UI State objects, primitive parameters, and click listeners. -\* **Styling:** Specific color constants, typography styles, and shape definitions referenced in the XML. -\* **Resources:** Identifying string resources, drawables, and dimensions. -\* **Layout logic:** Modifiers required to replicate the XML constraints (padding, alignment, weight). +Analyze the specific XML layout targeted for migration. You must extract and document the following requirements for the new composable: \* **Inputs:** UI State objects, primitive parameters, and click listeners. \* **Styling:** Specific color constants, typography styles, and shape definitions referenced in the XML. \* **Resources:** Identifying string resources, drawables, and dimensions. \* **Layout logic:** Modifiers required to replicate the XML constraints (padding, alignment, weight). ## 5. Architectural \& non-UI analysis -Understand the environment in which the UI resides to ensure proper integration. -\* **State management:** Identify the usage of `ViewModel`, `Flow`, or `LiveData`. -\* **Dependency Injection:** Check for Hilt, Koin, or manual DI to understand how dependencies are provided to the UI layer. -\* **Testing \& architecture:** Note the architectural pattern (MVI, MVVM, or custom architecture setup.) and existing UI testing frameworks to ensure the migrated code remains testable. Unless the user explicitly requests, **DO NOT** make any changes to any non-UI code that aren't strictly required for the migration of the XML View. +Understand the environment in which the UI resides to ensure proper integration. \* **State management:** Identify the usage of `ViewModel`, `Flow`, or `LiveData`. \* **Dependency Injection:** Check for Hilt, Koin, or manual DI to understand how dependencies are provided to the UI layer. \* **Testing \& architecture:** Note the architectural pattern (MVI, MVVM, or custom architecture setup.) and existing UI testing frameworks to ensure the migrated code remains testable. Unless the user explicitly requests, **DO NOT** make any changes to any non-UI code that aren't strictly required for the migration of the XML View. *** ** * ** *** diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md index 60b7968..3eb0b20 100644 --- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md +++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md @@ -1,14 +1,8 @@ -When you introduce Compose in an existing app, you need to migrate your Material -XML themes to use `MaterialTheme` for Compose components. This means your app's -theming will have two sources of truth: the View-based theme and the Compose -theme. Any changes to your styling need to be made in multiple places. Once -your app is fully migrated to Compose, remove your XML theming. +When you introduce Compose in an existing app, you need to migrate your Material XML themes to use `MaterialTheme` for Compose components. This means your app's theming will have two sources of truth: the View-based theme and the Compose theme. Any changes to your styling need to be made in multiple places. Once your app is fully migrated to Compose, remove your XML theming. -You can use the [Material Theme Builder](https://m3.material.io/theme-builder) -tool for migrating colors. +You can use the [Material Theme Builder](https://m3.material.io/theme-builder) tool for migrating colors. -When you start the migration from XML to Compose, migrate the theming to -Material 3 Compose theming. +When you start the migration from XML to Compose, migrate the theming to Material 3 Compose theming. ## Glossary @@ -29,26 +23,19 @@ Before migrating, be aware of the following limitations: ## Step 1: Evaluate the design system -Identify which design system is used in the XML View project. -Analyze the migration path and necessary steps to migrate the existing design -system to Material 3 in Compose. +Identify which design system is used in the XML View project. Analyze the migration path and necessary steps to migrate the existing design system to Material 3 in Compose. ## Step 2: Identify theme source files -In XML you write `?attr/colorPrimary`. In Compose, you access theme values -with `MaterialTheme.*`: +In XML you write `?attr/colorPrimary`. In Compose, you access theme values with `MaterialTheme.*`: -Identify and locate all XML resources and files necessary for theming: -light and dark color schemes and qualifiers, themes, shapes, dimensions, -typography, styles and other relevant files. +Identify and locate all XML resources and files necessary for theming: light and dark color schemes and qualifiers, themes, shapes, dimensions, typography, styles and other relevant files. Resources such as strings can be reused as is and don't need to be migrated. ## Step 3: Migrate colors -**Key principle:** XML uses named hex colors. -Material 3 uses *semantic roles* (e.g., `primary`, `onPrimary`, `surface`). -Stop naming colors by their hex; name them by their role. +**Key principle:** XML uses named hex colors. Material 3 uses *semantic roles* (e.g., `primary`, `onPrimary`, `surface`). Stop naming colors by their hex; name them by their role. Examples: @@ -69,8 +56,7 @@ Examples: *** ** * ** *** -Migrate the dark and light color schemes from XML to their equivalents in -Material 3 Compose. +Migrate the dark and light color schemes from XML to their equivalents in Material 3 Compose. > [!NOTE] > **Note:** Material 3 naming differs from Material 2 color naming. @@ -117,20 +103,14 @@ XML styles (styles.xml) system defines styles and appearance of: 3. Themes and overlays 4. Shapes -XML Views and components combine multiple attributes to create a style. -They set their styles from styles.xml in two different ways: +XML Views and components combine multiple attributes to create a style. They set their styles from styles.xml in two different ways: 1. Setting "style="@style/..." directly and explicitly in the XML View 2. Setting the style indirectly and implicitly for a component as part of a larger Theme (theme.xml) -Styles have no **direct** equivalent in Compose - instead styles are passed as: -parameters or modifiers to composables, using the -[new, experimental Styles API](https://developer.android.com/develop/ui/compose/styles) defined in the AppTheme, or by creating -layered, reusable composable variations with the defined style. +Styles have no **direct** equivalent in Compose - instead styles are passed as: parameters or modifiers to composables, using the [new, experimental Styles API](https://developer.android.com/develop/ui/compose/styles) defined in the AppTheme, or by creating layered, reusable composable variations with the defined style. -Provide separate @Composable functions named according to the style and the -base component, to signify the difference in styling and use cases for those -components. +Provide separate @Composable functions named according to the style and the base component, to signify the difference in styling and use cases for those components. - **Pattern:** If an XML element uses a custom style (e.g., `style="@style/MyPrimaryButton"`), don't try to replicate the style inline. Instead, suggest creating a specific composable. - **Example:** @@ -162,10 +142,6 @@ components. ## Step 6: Validate the theme migration -Always use the existing theme values from the original XML theme as the source -of truth for the new Material Theme in Compose. -Never invent new theme values during migration, to maintain brand consistency -and avoid visual regressions. +Always use the existing theme values from the original XML theme as the source of truth for the new Material Theme in Compose. Never invent new theme values during migration, to maintain brand consistency and avoid visual regressions. -Verify all new Compose theme values match the existing XML values. -Don't hardcode any migrated values. \ No newline at end of file +Verify all new Compose theme values match the existing XML values. Don't hardcode any migrated values. \ No newline at end of file diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/compose-in-views.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/compose-in-views.md index 83c7188..a0bc6ad 100644 --- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/compose-in-views.md +++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/compose-in-views.md @@ -3,10 +3,9 @@ You can add Compose-based UI into an existing app that uses a View-based design. -To create a new, entirely Compose-based screen, have your -activity call the `setContent()` method, and pass whatever composable functions -you like. +To create a new, entirely Compose-based screen, have your activity call the `setContent()` method, and pass whatever composable functions you like. +
```kotlin class ExampleActivity : ComponentActivity() { @@ -25,6 +24,7 @@ class ExampleActivity : ComponentActivity() { fun Greeting(name: String) { Text(text = "Hello $name!") } + ```
@@ -32,30 +32,17 @@ fun Greeting(name: String) { This code looks just like what you'd find in a Compose-only app. > [!CAUTION] -> **Caution:** To use the `ComponentActivity.setContent` -> method, add the `androidx.activity:activity-compose:$latestVersion` -> dependency to your `build.gradle` file. +> **Caution:** To use the `ComponentActivity.setContent` method, add the `androidx.activity:activity-compose:$latestVersion` dependency to your `build.gradle` file. > -> See the [Activity releases page](https://developer.android.com/jetpack/androidx/releases/activity) -> to find out the latest version. +> See the [Activity releases page](https://developer.android.com/jetpack/androidx/releases/activity) to find out the latest version. ## `ViewCompositionStrategy` for `ComposeView` -[`ViewCompositionStrategy`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ViewCompositionStrategy) -defines when the Composition should be disposed. The default, -[`ViewCompositionStrategy.Default`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ViewCompositionStrategy#Default()), -disposes the Composition when the underlying -[`ComposeView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView) -detaches from the window, unless it is part of a pooling container such as a -`RecyclerView`. In a single-Activity Compose-only app, this default behavior is -what you would want, however, if you are incrementally adding Compose in your -codebase, this behavior may cause state loss in some scenarios. +[`ViewCompositionStrategy`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ViewCompositionStrategy) defines when the Composition should be disposed. The default, [`ViewCompositionStrategy.Default`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ViewCompositionStrategy#Default()), disposes the Composition when the underlying [`ComposeView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView) detaches from the window, unless it is part of a pooling container such as a `RecyclerView`. In a single-Activity Compose-only app, this default behavior is what you would want, however, if you are incrementally adding Compose in your codebase, this behavior may cause state loss in some scenarios. -To change the `ViewCompositionStrategy`, call the [`setViewCompositionStrategy()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/AbstractComposeView#setViewCompositionStrategy(androidx.compose.ui.platform.ViewCompositionStrategy)) -method and provide a different strategy. +To change the `ViewCompositionStrategy`, call the [`setViewCompositionStrategy()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/AbstractComposeView#setViewCompositionStrategy(androidx.compose.ui.platform.ViewCompositionStrategy)) method and provide a different strategy. -The table below summarizes the different scenarios you can use -`ViewCompositionStrategy` in: +The table below summarizes the different scenarios you can use `ViewCompositionStrategy` in: | `ViewCompositionStrategy` | Description and Interop Scenario | |---|---| @@ -69,11 +56,7 @@ The table below summarizes the different scenarios you can use > [!NOTE] > **Note:** For hybrid apps with Views and Compose, that use Fragments, use `ComposeView` to wrap composables content and add to a Fragment during migration. For Compose-only apps, do not use Fragments and instead use the recommended Compose-only architecture with a single Activity and latest navigation libraries, like Navigation 3. -If you want to incorporate Compose UI content in a fragment or an existing View -layout, use [`ComposeView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView) -and call its -[`setContent()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView#setContent(kotlin.Function0)) -method. `ComposeView` is an Android [`View`](https://developer.android.com/reference/android/view/View). +If you want to incorporate Compose UI content in a fragment or an existing View layout, use [`ComposeView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView) and call its [`setContent()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView#setContent(kotlin.Function0)) method. `ComposeView` is an Android [`View`](https://developer.android.com/reference/android/view/View). You can put the `ComposeView` in your XML layout just like any other `View`: @@ -93,13 +76,12 @@ You can put the `ComposeView` in your XML layout just like any other `View`: android:layout_width="match_parent" android:layout_height="match_parent" /> + ``` -In the Kotlin source code, inflate the layout from the [layout -resource](https://developer.android.com/guide/topics/resources/layout-resource) defined in XML. Then get the -`ComposeView` using the XML ID, set a Composition strategy that works best for -the host `View`, and call `setContent()` to use Compose. +In the Kotlin source code, inflate the layout from the [layout resource](https://developer.android.com/guide/topics/resources/layout-resource) defined in XML. Then get the `ComposeView` using the XML ID, set a Composition strategy that works best for the host `View`, and call `setContent()` to use Compose. +
```kotlin class ExampleFragmentXml : Fragment() { @@ -125,13 +107,14 @@ class ExampleFragmentXml : Fragment() { return view } } + ```
-Alternatively, you can also use view binding to obtain references to the -`ComposeView` by referencing the generated binding class for your XML layout file: +Alternatively, you can also use view binding to obtain references to the `ComposeView` by referencing the generated binding class for your XML layout file: +
```kotlin class ExampleFragment : Fragment() { @@ -167,20 +150,18 @@ class ExampleFragment : Fragment() { _binding = null } } + ```
![Two slightly different text elements, one above the other](https://developer.android.com/static/develop/ui/compose/images/interop-hellos.png) -**Figure 1.** This shows the output of the code that adds Compose elements in a -View UI hierarchy. The "Hello Android!" text is displayed by a -`TextView` widget. The "Hello Compose!" text is displayed by a -Compose text element. +**Figure 1.** This shows the output of the code that adds Compose elements in a View UI hierarchy. The "Hello Android!" text is displayed by a `TextView` widget. The "Hello Compose!" text is displayed by a Compose text element. -You can also include a `ComposeView` directly in a fragment if your full screen -is built with Compose, which lets you avoid using an XML layout file entirely. +You can also include a `ComposeView` directly in a fragment if your full screen is built with Compose, which lets you avoid using an XML layout file entirely. +
```kotlin class ExampleFragmentNoXml : Fragment() { @@ -203,15 +184,16 @@ class ExampleFragmentNoXml : Fragment() { } } } + ```
## Multiple `ComposeView` instances in the same layout -If there are multiple `ComposeView` elements in the same layout, each one must -have a unique ID for `savedInstanceState` to work. +If there are multiple `ComposeView` elements in the same layout, each one must have a unique ID for `savedInstanceState` to work. +
```kotlin class ExampleFragmentMultipleComposeView : Fragment() { @@ -242,6 +224,7 @@ class ExampleFragmentMultipleComposeView : Fragment() { ) } } + ```
@@ -253,18 +236,16 @@ The `ComposeView` IDs are defined in the `res/values/ids.xml` file: + ``` ## Preview composables in Layout Editor -You can also preview composables within the Layout Editor for your XML layout -containing a `ComposeView`. Doing so lets you see how your composables look -within a mixed Views and Compose layout. +You can also preview composables within the Layout Editor for your XML layout containing a `ComposeView`. Doing so lets you see how your composables look within a mixed Views and Compose layout. -Say you want to display the following composable in the Layout Editor. Note -that composables annotated with `@Preview` are good candidates to preview in the -Layout Editor. +Say you want to display the following composable in the Layout Editor. Note that composables annotated with `@Preview` are good candidates to preview in the Layout Editor. +
```kotlin @Preview @@ -272,13 +253,12 @@ Layout Editor. fun GreetingPreview() { Greeting(name = "Android") } + ```
-To display this composable, use the `tools:composableName` tools attribute and -set its value to the fully qualified name of the composable to preview in the -layout. +To display this composable, use the `tools:composableName` tools attribute and set its value to the fully qualified name of the composable to preview in the layout. ```xml + ``` ![Composable displayed within layout editor](https://developer.android.com/static/develop/ui/compose/images/layout-editor-composable-preview.png) \ No newline at end of file diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/views-in-compose.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/views-in-compose.md index 14b9121..248d909 100644 --- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/views-in-compose.md +++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/views-in-compose.md @@ -1,22 +1,13 @@ -You can include an Android View hierarchy in a Compose UI. This approach is -particularly useful if you want to use UI elements that are not yet available in -Compose, like -[`AdView`](https://developers.google.com/android/reference/com/google/android/gms/ads/AdView). -This approach also lets you reuse custom views you may have designed. +You can include an Android View hierarchy in a Compose UI. This approach is particularly useful if you want to use UI elements that are not yet available in Compose, like [`AdView`](https://developers.google.com/android/reference/com/google/android/gms/ads/AdView). This approach also lets you reuse custom views you may have designed. > [!NOTE] > **Note:** Use `AndroidView` as a wrapper only for missing SDK components without Compose support. Rewrite your custom Views in Compose wherever possible, starting the migration with the simplest custom Views and scaling to more complex ones.
-To include a view element or hierarchy, use the [`AndroidView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/AndroidView.composable#AndroidView(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) -composable. `AndroidView` is passed a lambda that returns a -[`View`](https://developer.android.com/reference/android/view/View). `AndroidView` also provides an `update` -callback that is called when the view is inflated. The `AndroidView` recomposes -whenever a `State` read within the callback changes. `AndroidView`, like many -other built-in composables, takes a `Modifier` parameter that can be used, for -example, to set its position in the parent composable. +To include a view element or hierarchy, use the [`AndroidView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/AndroidView.composable#AndroidView(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) composable. `AndroidView` is passed a lambda that returns a [`View`](https://developer.android.com/reference/android/view/View). `AndroidView` also provides an `update` callback that is called when the view is inflated. The `AndroidView` recomposes whenever a `State` read within the callback changes. `AndroidView`, like many other built-in composables, takes a `Modifier` parameter that can be used, for example, to set its position in the parent composable. +
```kotlin @Composable @@ -54,6 +45,8 @@ fun ContentExample() { CustomView() } } + + ```
@@ -63,14 +56,12 @@ fun ContentExample() { ## `AndroidView` with view binding -To embed an XML layout, use the -[`AndroidViewBinding`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidViewBinding(kotlin.Function3,%20androidx.compose.ui.Modifier,%20kotlin.Function1)) -API, which is provided by the `androidx.compose.ui:ui-viewbinding` library. To -do this, your project must enable [view binding](https://developer.android.com/topic/libraries/view-binding#setup). +To embed an XML layout, use the [`AndroidViewBinding`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidViewBinding(kotlin.Function3,%20androidx.compose.ui.Modifier,%20kotlin.Function1)) API, which is provided by the `androidx.compose.ui:ui-viewbinding` library. To do this, your project must enable [view binding](https://developer.android.com/topic/libraries/view-binding#setup). > [!NOTE] > **Note:** For Compose-only apps, don't use `AndroidViewBinding` to inflate full screen-level XML layouts, and instead use it only for smaller, legacy XML layouts during the incremental migration process. +
```kotlin @Composable @@ -79,23 +70,21 @@ fun AndroidViewBindingExample() { exampleView.setBackgroundColor(Color.GRAY) } } + ```
## `AndroidView` in Lazy lists -If you are using an `AndroidView` in a Lazy list (`LazyColumn`, `LazyRow`, -`Pager`, etc.), consider using the [`AndroidView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidView(kotlin.Function1,kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1,kotlin.Function1)) -overload introduced in version 1.4.0-rc01. This overload allows Compose to reuse -the underlying `View` instance when the containing composition is reused as is -the case for Lazy lists. +If you are using an `AndroidView` in a Lazy list (`LazyColumn`, `LazyRow`, `Pager`, etc.), consider using the [`AndroidView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidView(kotlin.Function1,kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1,kotlin.Function1)) overload introduced in version 1.4.0-rc01. This overload allows Compose to reuse the underlying `View` instance when the containing composition is reused as is the case for Lazy lists. This overload of `AndroidView` adds 2 additional parameters: - `onReset` - A callback invoked to signal that the `View` is about to be reused. This must be non-null to enable View reuse. - `onRelease` (optional) - A callback invoked to signal that the `View` has exited the composition and will not be reused again. +
```kotlin @Composable @@ -117,72 +106,50 @@ fun AndroidViewInLazyList() { } } } + ```
## Fragments in Compose (Transitionary Step) -Use the `AndroidFragment` composable to add a `Fragment` in Compose. -`AndroidFragment` has fragment-specific handling such as removing the -fragment when the composable leaves the composition. +Use the `AndroidFragment` composable to add a `Fragment` in Compose. `AndroidFragment` has fragment-specific handling such as removing the fragment when the composable leaves the composition. > [!NOTE] > **Note:** Wrap existing Fragments in Compose only during incremental migration. For Compose-only apps, do not use Fragments and instead use the recommended Compose-only architecture with a single Activity and latest navigation libraries, like Navigation 3. -To include a fragment, use the [`AndroidFragment`](https://developer.android.com/reference/kotlin/androidx/fragment/compose/package-summary#AndroidFragment) -composable. You pass a `Fragment` class to `AndroidFragment`, which then adds -an instance of that class directly into the composition. `AndroidFragment` also -provides a `fragmentState` object to create the `AndroidFragment` with a given -state, `arguments` to pass into the new fragment, and an `onUpdate` callback -that provides the fragment from the composition. Like many -other built-in composables, `AndroidFragment` accepts a `Modifier` parameter -that you can use, for -example, to set its position in the parent composable. +To include a fragment, use the [`AndroidFragment`](https://developer.android.com/reference/kotlin/androidx/fragment/compose/package-summary#AndroidFragment) composable. You pass a `Fragment` class to `AndroidFragment`, which then adds an instance of that class directly into the composition. `AndroidFragment` also provides a `fragmentState` object to create the `AndroidFragment` with a given state, `arguments` to pass into the new fragment, and an `onUpdate` callback that provides the fragment from the composition. Like many other built-in composables, `AndroidFragment` accepts a `Modifier` parameter that you can use, for example, to set its position in the parent composable. Call `AndroidFragment` in Compose as follows: +
```kotlin @Composable fun FragmentInComposeExample() { AndroidFragment() } + + ```
## Calling the Android framework from Compose -Compose operates within the Android framework classes. For example, it's hosted -on Android View classes, like `Activity` or `Fragment`, and might use Android -framework classes like the `Context`, system resources, -`Service`, or `BroadcastReceiver`. +Compose operates within the Android framework classes. For example, it's hosted on Android View classes, like `Activity` or `Fragment`, and might use Android framework classes like the `Context`, system resources, `Service`, or `BroadcastReceiver`. To learn more about system resources, see [Resources in Compose](https://developer.android.com/develop/ui/compose/resources). ### Composition Locals -[`CompositionLocal`](https://developer.android.com/reference/kotlin/androidx/compose/runtime/CompositionLocal) -classes allow passing data implicitly through composable functions. They're -usually provided with a value in a certain node of the UI tree. That value can -be used by its composable descendants without declaring the `CompositionLocal` -as a parameter in the composable function. +[`CompositionLocal`](https://developer.android.com/reference/kotlin/androidx/compose/runtime/CompositionLocal) classes allow passing data implicitly through composable functions. They're usually provided with a value in a certain node of the UI tree. That value can be used by its composable descendants without declaring the `CompositionLocal` as a parameter in the composable function. -`CompositionLocal` is used to propagate values for Android framework types in -Compose such as `Context`, `Configuration` or the `View` in which the Compose -code is hosted with the corresponding -[`LocalContext`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalContext()), -[`LocalConfiguration`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalConfiguration()), -or -[`LocalView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalView()). -Note that `CompositionLocal` classes are prefixed with `Local` for better -discoverability with auto-complete in the IDE. +`CompositionLocal` is used to propagate values for Android framework types in Compose such as `Context`, `Configuration` or the `View` in which the Compose code is hosted with the corresponding [`LocalContext`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalContext()), [`LocalConfiguration`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalConfiguration()), or [`LocalView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalView()). Note that `CompositionLocal` classes are prefixed with `Local` for better discoverability with auto-complete in the IDE. -Access the current value of a `CompositionLocal` by using its `current` -property. For example, the code below shows a toast message by providing -`LocalContext.current` into the `Toast.makeToast` method. +Access the current value of a `CompositionLocal` by using its `current` property. For example, the code below shows a toast message by providing `LocalContext.current` into the `Toast.makeToast` method. +
```kotlin @Composable @@ -194,18 +161,16 @@ fun ToastGreetingButton(greeting: String) { Text("Greet") } } + ```
### Broadcast receivers -To showcase `CompositionLocal` and [side -effects](https://developer.android.com/develop/ui/compose/side-effects), if a -[`BroadcastReceiver`](https://developer.android.com/guide/components/broadcasts) needs to be registered from -a composable function, use of `LocalContext` to use the current context, and -`rememberUpdatedState` and `DisposableEffect` side effects. +To showcase `CompositionLocal` and [side effects](https://developer.android.com/develop/ui/compose/side-effects), if a [`BroadcastReceiver`](https://developer.android.com/guide/components/broadcasts) needs to be registered from a composable function, use of `LocalContext` to use the current context, and `rememberUpdatedState` and `DisposableEffect` side effects. +
```kotlin @Composable @@ -247,18 +212,16 @@ fun HomeScreen() { /* Rest of the HomeScreen */ } + ```
## Other interactions -If there isn't a utility defined for the interaction you need, the best practice -is to follow the general Compose guideline, -*data flows down, events flow up* (discussed at more length in [Thinking -in Compose](https://developer.android.com/develop/ui/compose/mental-model)). For example, this composable -launches a different activity: +If there isn't a utility defined for the interaction you need, the best practice is to follow the general Compose guideline, *data flows down, events flow up* (discussed at more length in [Thinking in Compose](https://developer.android.com/develop/ui/compose/mental-model)). For example, this composable launches a different activity: +
```kotlin class OtherInteractionsActivity : ComponentActivity() { @@ -281,6 +244,7 @@ fun ExampleComposable(data: DataExample, onButtonClick: () -> Unit) { Text(data.title) } } + ```
\ No newline at end of file diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md index bf06fa0..ceda68a 100644 --- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md +++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md @@ -1,9 +1,7 @@ -For Gradle, use the Compose Compiler Gradle plugin to set up and configure -Compose. +For Gradle, use the Compose Compiler Gradle plugin to set up and configure Compose. > [!NOTE] -> **Note:** The Compose Compiler Gradle Plugin is only available from Kotlin 2.0+. For migration instructions, see ["Jetpack Compose compiler moving to the Kotlin -> repository"](https://android-developers.googleblog.com/2024/04/jetpack-compose-compiler-moving-to-kotlin-repository.html). +> **Note:** The Compose Compiler Gradle Plugin is only available from Kotlin 2.0+. For migration instructions, see ["Jetpack Compose compiler moving to the Kotlin repository"](https://android-developers.googleblog.com/2024/04/jetpack-compose-compiler-moving-to-kotlin-repository.html). ### Set up with Gradle version catalogs @@ -21,8 +19,7 @@ Set up the Compose Compiler Gradle plugin: // Add this line compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } -3. In the project's root `build.gradle.kts` file, add the following to the - `plugins` section. +3. In the project's root `build.gradle.kts` file, add the following to the `plugins` section. plugins { // Existing plugins @@ -36,14 +33,11 @@ Set up the Compose Compiler Gradle plugin: alias(libs.plugins.compose.compiler) } -The project should now build and compile if it was using the default set up. If -it had configured custom options on the Compose compiler, follow the next -section. +The project should now build and compile if it was using the default set up. If it had configured custom options on the Compose compiler, follow the next section. ### Set up the Compose Compiler without Gradle version catalogs -Add the plugin to `build.gradle.kts` files associated with modules where Compose -is used: +Add the plugin to `build.gradle.kts` files associated with modules where Compose is used: plugins { id("org.jetbrains.kotlin.plugin.compose") version "2.3.21" // this version matches your Kotlin version @@ -59,9 +53,7 @@ Add the classpath to your top-level project `build.gradle.kts` file: ### Configuration options with the Compose Compiler Gradle Plugin -To configure the Compose compiler using the Gradle plugin, add the -`composeCompiler` block to the module's `build.gradle.kts` file at the top -level: +To configure the Compose compiler using the Gradle plugin, add the `composeCompiler` block to the module's `build.gradle.kts` file at the top level: android { ... } @@ -74,10 +66,9 @@ For the full list of available options, see the [documentation](https://www.jetb ## Set up Compose dependencies -Always use the latest Compose BOM version: `2026.06.00`. +Always use the latest Compose BOM version: `2026.06.01`. -Set the `compose` flag to `true` inside the Android [`BuildFeatures`](https://developer.android.com/reference/tools/gradle-api/7.0/com/android/build/api/dsl/BuildFeatures) to -enable [Compose functionality](https://developer.android.com/develop/ui/compose/tooling) in Android Studio. +Set the `compose` flag to `true` inside the Android [`BuildFeatures`](https://developer.android.com/reference/tools/gradle-api/7.0/com/android/build/api/dsl/BuildFeatures) to enable [Compose functionality](https://developer.android.com/develop/ui/compose/tooling) in Android Studio. Add the following definition to your app's `build.gradle` file: @@ -103,7 +94,7 @@ Add the Compose BOM and the subset of Compose library dependencies: dependencies { - def composeBom = platform('androidx.compose:compose-bom:2026.06.00') + def composeBom = platform('androidx.compose:compose-bom:2026.06.01') implementation composeBom androidTestImplementation composeBom @@ -142,7 +133,7 @@ Add the Compose BOM and the subset of Compose library dependencies: dependencies { - val composeBom = platform("androidx.compose:compose-bom:2026.06.00") + val composeBom = platform("androidx.compose:compose-bom:2026.06.01") implementation(composeBom) androidTestImplementation(composeBom) @@ -178,20 +169,12 @@ Add the Compose BOM and the subset of Compose library dependencies: } > [!NOTE] -> **Note:** Jetpack Compose is shipped using a Bill of Materials (BOM), to keep the versions of all library groups in sync. Read more about it in the [Bill of -> Materials page](https://developer.android.com/develop/ui/compose/bom/bom). +> **Note:** Jetpack Compose is shipped using a Bill of Materials (BOM), to keep the versions of all library groups in sync. Read more about it in the [Bill of Materials page](https://developer.android.com/develop/ui/compose/bom/bom). ## `compileSdk` and Android Gradle Plugin compatibility -Compose library releases continually adopt the latest `compileSdk` versions to -provide access to the latest Android features. Newer `compileSdk` versions -require newer versions of Android Gradle Plugin, so adopting new Compose -releases also requires projects to adopt new versions of the Android Gradle -Plugin. We recommend keeping your project's `compileSdk` up to date with the -latest released versions. `compileSdk` is unrelated from `targetSdk`. +Compose library releases continually adopt the latest `compileSdk` versions to provide access to the latest Android features. Newer `compileSdk` versions require newer versions of Android Gradle Plugin, so adopting new Compose releases also requires projects to adopt new versions of the Android Gradle Plugin. We recommend keeping your project's `compileSdk` up to date with the latest released versions. `compileSdk` is unrelated from `targetSdk`. -For example, starting with Compose 1.12.0, projects are required to use -`compileSdk 37` and Android Gradle Plugin (AGP) 9. +For example, starting with Compose 1.12.0, projects are required to use `compileSdk 37` and Android Gradle Plugin (AGP) 9. -To check which version of AGP is supported for different API levels, see the -[Android Gradle plugin API level support](https://developer.android.com/build/releases/about-agp#api-level-support) documentation. \ No newline at end of file +To check which version of AGP is supported for different API levels, see the [Android Gradle plugin API level support](https://developer.android.com/build/releases/about-agp#api-level-support) documentation. \ No newline at end of file diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/identify-optimal-xml-candidate.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/identify-optimal-xml-candidate.md index 650ac92..e8a42d0 100644 --- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/identify-optimal-xml-candidate.md +++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/identify-optimal-xml-candidate.md @@ -14,18 +14,12 @@ Prioritize layouts that meet the following criteria: ### 3. Risk assessment -Evaluate the migration risk based on: -\* **Reusability:** Find layouts with **minimum reuse** across the project to limit regression impact. -\* **Accessibility:** Ensure the layout has an **easily accessible entry point** (e.g., used in a simple Activity, Fragment, or as a standalone include). +Evaluate the migration risk based on: \* **Reusability:** Find layouts with **minimum reuse** across the project to limit regression impact. \* **Accessibility:** Ensure the layout has an **easily accessible entry point** (e.g., used in a simple Activity, Fragment, or as a standalone include). *** ** * ** *** ## Output requirements -Provide a ranked list of the top 3-5 candidates. For each candidate, include: -1. **File path:** (e.g., `res/layout/item_user_profile.xml`) -2. **Rationale:** Why this is a good candidate based on the provided criteria. -3. **Complexity score:** A rating from 1-5 (1 being simplest). -4. **Dependency count:** List of custom/external views found within. +Provide a ranked list of the top 3-5 candidates. For each candidate, include: 1. **File path:** (e.g., `res/layout/item_user_profile.xml`) 2. **Rationale:** Why this is a good candidate based on the provided criteria. 3. **Complexity score:** A rating from 1-5 (1 being simplest). 4. **Dependency count:** List of custom/external views found within. **Action:** If you support user interaction, ask the user to choose which XML to proceed with. Else proceed with the best option, based on the previous criteria. \ No newline at end of file diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/xml-layout-migration.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/xml-layout-migration.md index 5aeb6b3..ba27ac4 100644 --- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/xml-layout-migration.md +++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/xml-layout-migration.md @@ -1,7 +1,6 @@ ## 1. Structural analysis \& mapping -**Identify the precise mapping** between XML elements and Compose equivalents. -You must determine: +**Identify the precise mapping** between XML elements and Compose equivalents. You must determine: - The exact `@Composable` functions (e.g., `ConstraintLayout`, `Column`, `LazyColumn`) that replace the XML tag hierarchy. - The specific parameters and `Modifier` extensions required to replicate XML attributes (e.g., `layout_width`, `padding`, `elevation`). @@ -9,9 +8,7 @@ You must determine: ## 2. Migration execution -**Convert the XML layout code to Jetpack Compose**, ensuring the visual -hierarchy and layout logic are preserved while leveraging Compose's declarative -nature. +**Convert the XML layout code to Jetpack Compose**, ensuring the visual hierarchy and layout logic are preserved while leveraging Compose's declarative nature. ## 3. Theming \& design system integrity @@ -23,8 +20,7 @@ nature. ## 4. Component layering \& reusability -Evaluate if the XML layout serves as a foundation-level design system component -(reused across the app with a distinct role). If it is: +Evaluate if the XML layout serves as a foundation-level design system component (reused across the app with a distinct role). If it is: - **Create a reusable composable:** Do not just inline the code. Define a new standalone `@Composable`. - **Parameterization:** Expose specific parameters for variable data (text, colors, styles) and use `Modifier` for layout-specific customizations. @@ -44,6 +40,7 @@ Example before migration: Example after migration: +
```kotlin @Composable @@ -73,6 +70,7 @@ fun RoundedBorderlessButton( ) } } + ```
diff --git a/jetpack-compose/theming/styles/SKILL.md b/jetpack-compose/theming/styles/SKILL.md index c223382..eb97976 100644 --- a/jetpack-compose/theming/styles/SKILL.md +++ b/jetpack-compose/theming/styles/SKILL.md @@ -8,7 +8,7 @@ description: Use this skill to integrate the Jetpack Compose Styles API into an license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-07' + last-updated: '2026-08-06' keywords: - Jetpack Compose - Styles @@ -30,13 +30,11 @@ metadata: - The project must use `compileSdk` version 37 or higher. - The project must use `androidx.compose.foundation:foundation` version `1.12.0-alpha01` or higher. - Alternatively, the project must use Compose BOM version `2026.04.01` or higher. -- The API requires this exact package: `import - androidx.compose.foundation.style.Style` +- The API requires this exact package: `import androidx.compose.foundation.style.Style` ### 2. Configure compiler options to enable experimental API -You must opt-in to the experimental API at the project level. Add the following -block to your module's `build.gradle.kts`: +You must opt-in to the experimental API at the project level. Add the following block to your module's `build.gradle.kts`: kotlin { compilerOptions { @@ -49,12 +47,9 @@ block to your module's `build.gradle.kts`: Refer to the official documentation to complete specific development tasks: -- Basic Style Usage: To set backgrounds, sizes, and alignments on a component, follow the [Compose Styles Fundamentals - Guide](references/android/develop/ui/compose/styles/fundamentals.md). -- State and Transitions: To configure property changes for state shifts (like pressed or hovered), follow the [Animations and State-Based Styling - Guide](references/android/develop/ui/compose/styles/state-animations.md). -- Architecture Trade offs: To decide when to use a Style versus a standard Modifier, follow the [Styles versus Modifiers - Comparison](references/android/develop/ui/compose/styles/styles-vs-modifiers.md). +- Basic Style Usage: To set backgrounds, sizes, and alignments on a component, follow the [Compose Styles Fundamentals Guide](references/android/develop/ui/compose/styles/fundamentals.md). +- State and Transitions: To configure property changes for state shifts (like pressed or hovered), follow the [Animations and State-Based Styling Guide](references/android/develop/ui/compose/styles/state-animations.md). +- Architecture Trade offs: To decide when to use a Style versus a standard Modifier, follow the [Styles versus Modifiers Comparison](references/android/develop/ui/compose/styles/styles-vs-modifiers.md). - Theme Level Integration: To connect style definitions with custom themes, follow [Theming with Styles](references/android/develop/ui/compose/styles/theming.md) and [Custom Themes in Compose](references/android/develop/ui/compose/designsystems/custom.md). ## Step-by-Step Migration Workflow @@ -71,6 +66,7 @@ Refer to the official documentation to complete specific development tasks: 1. Create a new file named `ComponentStyles.kt` in your theme directory. 2. Define a top-level data class to hold your component styles, for example, the Jetsnack one is called `JetsnackStyles`: +
```kotlin object ExampleComponentStyles { @@ -81,13 +77,14 @@ Refer to the official documentation to complete specific development tasks: } } + ```
-3. Expose this class through your custom theme with a static reference, don't - use `CompositionLocals` here as it's not required. +3. Expose this class through your custom theme with a static reference, don't use `CompositionLocals` here as it's not required. +
```kotlin @Immutable @@ -104,13 +101,14 @@ Refer to the official documentation to complete specific development tasks: val styles: ComponentStyles = ComponentStyles } } + ```
-4. Provide extensions on `StyleScope` to reference theme tokens directly if - they are exposed using `CompositionLocals`. For example: +4. Provide extensions on `StyleScope` to reference theme tokens directly if they are exposed using `CompositionLocals`. For example: +
```kotlin val StyleScope.colors: JetsnackColors @@ -121,14 +119,15 @@ Refer to the official documentation to complete specific development tasks: val StyleScope.shapes: Shapes get() = LocalJetsnackTheme.currentValue.shapes + + ```
### Step 3: Migrate a component to Styles API -For each custom component (for example, `CustomButton`), complete the following -sequence: +For each custom component (for example, `CustomButton`), complete the following sequence: 1. **Establish a visual baseline (If an emulator is available):** - **If you CANNOT run an Android emulator:** Skip this step entirely and proceed to Step 2. @@ -137,8 +136,7 @@ sequence: - **Option B (If no test exists):** Create a test using the project's existing testing framework, then run it. - **Option C (If no framework exists):** Create a minimal screenshot test using UI Automator or Espresso, then run it. 2. **Remove individual styling parameters** : Remove styling parameters such as `backgroundColor`, `shape`, `textStyle`, and `contentPadding` from the signature - anything that `StyleScope` supports. -3. **Add the style parameter** : Add `style: Style = Style` to the function signature. Always ensure the default value is exactly `Style` (e.g., `style: - Style = Style`) and not a specific style default like `ChipStyleDefault` or any other value. +3. **Add the style parameter** : Add `style: Style = Style` to the function signature. Always ensure the default value is exactly `Style` (e.g., `style: Style = Style`) and not a specific style default like `ChipStyleDefault` or any other value. 4. **Declare state tracking** : If the component is interactable, create a `MutableStyleState` using the interaction source. Update state fields (such as `isEnabled`) inside the Composable to track the state correctly. 5. **Apply styleable modifier** : Replace specific layout modifiers on the root element with `Modifier.styleable()`. 6. **Move defaults to ComponentStyles** : Move hardcoded values from the component definition to a dedicated `Style` instance in `ComponentStyles.kt`. @@ -148,6 +146,7 @@ sequence: Before Migration: +
```kotlin @Composable @@ -172,12 +171,14 @@ fun CustomButton( content = content, ) } + ```
After Migration: +
```kotlin // Exposed via ComponentStyles.kt @@ -215,6 +216,7 @@ fun CustomButton( content = content, ) } + ```
diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/designsystems/custom.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/designsystems/custom.md index 59dbb25..ae05b5a 100644 --- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/designsystems/custom.md +++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/designsystems/custom.md @@ -1,7 +1,4 @@ -While Material is our recommended design system and Jetpack Compose ships an -implementation of Material, you are not forced to use it. Material is built -entirely on public APIs, so it's possible to create your own design system in -the same manner. +While Material is our recommended design system and Jetpack Compose ships an implementation of Material, you are not forced to use it. Material is built entirely on public APIs, so it's possible to create your own design system in the same manner. There are several approaches you might take: @@ -9,21 +6,15 @@ There are several approaches you might take: - [Replace one or more Material systems](https://developer.android.com/develop/ui/compose/designsystems/custom#replacing-systems) --- `Colors`, `Typography`, or `Shapes` --- with custom implementations while keeping the others. - [Implement a fully custom design system](https://developer.android.com/develop/ui/compose/designsystems/custom#implementing-fully-custom) to replace `MaterialTheme`. -You may also want to continue using Material components with a custom design -system. It's possible to do this but there are things to keep in mind to suit -the approach you've taken. +You may also want to continue using Material components with a custom design system. It's possible to do this but there are things to keep in mind to suit the approach you've taken. -To learn more about the lower-level constructs and APIs used by `MaterialTheme` -and custom design systems, check out the [Anatomy of a theme in Compose](https://developer.android.com/develop/ui/compose/designsystems/anatomy) guide. +To learn more about the lower-level constructs and APIs used by `MaterialTheme` and custom design systems, check out the [Anatomy of a theme in Compose](https://developer.android.com/develop/ui/compose/designsystems/anatomy) guide. ## Extend Material Theming -Compose Material closely models -[Material Theming](https://m3.material.io/) -to make it straightforward and type-safe to follow the Material guidelines. -However, it's possible to extend the color, typography, and shape sets with -additional values. The simplest approach is to add extension properties: +Compose Material closely models [Material Theming](https://m3.material.io/) to make it straightforward and type-safe to follow the Material guidelines. However, it's possible to extend the color, typography, and shape sets with additional values. The simplest approach is to add extension properties: +
```kotlin // Use with MaterialTheme.colorScheme.snackbarAction @@ -38,26 +29,21 @@ val Typography.textFieldInput: TextStyle // Use with MaterialTheme.shapes.card val Shapes.card: Shape get() = RoundedCornerShape(size = 20.dp) + ```
-This provides consistency with `MaterialTheme` usage APIs. An example of this -defined by Compose itself is -[`surfaceColorAtElevation`](https://developer.android.com/reference/kotlin/androidx/compose/material3/package-summary#(androidx.compose.material3.ColorScheme).surfaceColorAtElevation(androidx.compose.ui.unit.Dp)), -which determines the surface color that should be used depending on the -elevation. +This provides consistency with `MaterialTheme` usage APIs. An example of this defined by Compose itself is [`surfaceColorAtElevation`](https://developer.android.com/reference/kotlin/androidx/compose/material3/package-summary#(androidx.compose.material3.ColorScheme).surfaceColorAtElevation(androidx.compose.ui.unit.Dp)), which determines the surface color that should be used depending on the elevation. > [!NOTE] > **Note:** This approach is only recommended for straightforward theming value additions, or for values that are the same in different themes. If you have multiple themes, it's better to define a class with new properties instead. -Another approach is to define an extended theme that "wraps" `MaterialTheme` and -its values. +Another approach is to define an extended theme that "wraps" `MaterialTheme` and its values. -Suppose you want to add two additional colors --- `caution` and `onCaution`, a -yellow color used for actions that are semi-dangerous --- whilst keeping the -existing Material colors: +Suppose you want to add two additional colors --- `caution` and `onCaution`, a yellow color used for actions that are semi-dangerous --- whilst keeping the existing Material colors: +
```kotlin @Immutable @@ -96,22 +82,20 @@ object ExtendedTheme { @Composable get() = LocalExtendedColors.current } + ```
-This is similar to `MaterialTheme` usage APIs. It also supports multiple themes -as you can nest `ExtendedTheme`s in the same way as `MaterialTheme`. +This is similar to `MaterialTheme` usage APIs. It also supports multiple themes as you can nest `ExtendedTheme`s in the same way as `MaterialTheme`. ### Use Material components -When extending Material Theming, existing `MaterialTheme` values are maintained -and Material components still have reasonable defaults. +When extending Material Theming, existing `MaterialTheme` values are maintained and Material components still have reasonable defaults. -If you want to use extended values in components, wrap them in your own -composable functions, directly setting the values you want to alter, and -exposing others as parameters to the containing composable: +If you want to use extended values in components, wrap them in your own composable functions, directly setting the values you want to alter, and exposing others as parameters to the containing composable: +
```kotlin @Composable @@ -131,13 +115,14 @@ fun ExtendedButton( content = content ) } + ```
-You would then replace usages of `Button` with `ExtendedButton` where -appropriate. +You would then replace usages of `Button` with `ExtendedButton` where appropriate. +
```kotlin @Composable @@ -149,19 +134,18 @@ fun ExtendedApp() { } } } + ```
## Replace Material subsystems -Instead of extending Material Theming, you may want to replace one or more -systems --- `Colors`, `Typography`, or `Shapes` --- with a custom implementation, -while maintaining the others. +Instead of extending Material Theming, you may want to replace one or more systems --- `Colors`, `Typography`, or `Shapes` --- with a custom implementation, while maintaining the others. -Suppose you want to replace the type and shape systems while keeping the color -system: +Suppose you want to replace the type and shape systems while keeping the color system: +
```kotlin @Immutable @@ -222,22 +206,21 @@ object ReplacementTheme { @Composable get() = LocalReplacementShapes.current } + ```
### Use Material components -When one or more systems of `MaterialTheme` have been replaced, using Material -components as-is may result in unwanted Material color, type, or shape values. +When one or more systems of `MaterialTheme` have been replaced, using Material components as-is may result in unwanted Material color, type, or shape values. -If you want to use replacement values in components, wrap them in your own -composable functions, directly setting the values for the relevant system, and -exposing others as parameters to the containing composable. +If you want to use replacement values in components, wrap them in your own composable functions, directly setting the values for the relevant system, and exposing others as parameters to the containing composable. > [!NOTE] > **Note:** Not all values may be exposed as parameters in Material composables, in particular with `CompositionLocal` composables (such as `LocalTextStyle`). In such cases you may need to wrap `content` lambdas in provider functions (like `ProvideTextStyle`). +
```kotlin @Composable @@ -259,13 +242,14 @@ fun ReplacementButton( } ) } + ```
-You would then replace usages of `Button` with `ReplacementButton` where -appropriate. +You would then replace usages of `Button` with `ReplacementButton` where appropriate. +
```kotlin @Composable @@ -277,33 +261,28 @@ fun ReplacementApp() { } } } + ```
## Implement a fully custom design system -You may want to replace Material Theming with a fully custom design system. -Consider that `MaterialTheme` provides the following systems: +You may want to replace Material Theming with a fully custom design system. Consider that `MaterialTheme` provides the following systems: - `Colors`, `Typography`, and `Shapes`: Material Theming systems - `TextSelectionColors`: Colors used for text selection by `Text` and `TextField` - `Ripple` and `RippleTheme`: Material implementation of `Indication` -If you want to continue using Material components, you must replace some of -these systems in your custom themes or handle the systems in your -components to avoid unwanted behavior. +If you want to continue using Material components, you must replace some of these systems in your custom themes or handle the systems in your components to avoid unwanted behavior. -However, design systems are not limited to the concepts Material relies on. You -can modify existing systems and introduce entirely new ones --- with new classes -and types --- to make other concepts compatible with themes. +However, design systems are not limited to the concepts Material relies on. You can modify existing systems and introduce entirely new ones --- with new classes and types --- to make other concepts compatible with themes. -In the following code, we model a custom color system that includes gradients -(`List`), include a type system, introduce a new elevation system, -and exclude other systems provided by `MaterialTheme`: +In the following code, we model a custom color system that includes gradients (`List`), include a type system, introduce a new elevation system, and exclude other systems provided by `MaterialTheme`: ![Screenshot of a mobile app UI demonstrating a custom design system with elements using gradients for colors, custom typography, and elevation.](https://developer.android.com/static/develop/ui/compose/images/themes/custom-color-gradients.png) +
```kotlin @Immutable @@ -383,23 +362,20 @@ object CustomTheme { @Composable get() = LocalCustomElevation.current } + ```
### Use Material components -When no `MaterialTheme` is present, using Material components as-is will result -in unwanted Material color, type, and shape values and indication behavior. +When no `MaterialTheme` is present, using Material components as-is will result in unwanted Material color, type, and shape values and indication behavior. -If you want to use custom values in components, wrap them in your own composable -functions, directly setting the values for the relevant system, and exposing -others as parameters to the containing composable. +If you want to use custom values in components, wrap them in your own composable functions, directly setting the values for the relevant system, and exposing others as parameters to the containing composable. -We recommend that you access values you set from your custom theme. -Alternatively, if your theme doesn't provide `Color`, `TextStyle`, `Shape`, or -other systems, you can hardcode them. +We recommend that you access values you set from your custom theme. Alternatively, if your theme doesn't provide `Color`, `TextStyle`, `Shape`, or other systems, you can hardcode them. +
```kotlin @Composable @@ -438,6 +414,7 @@ fun CustomButton( } val ButtonShape = RoundedCornerShape(percent = 50) + ```
@@ -445,11 +422,7 @@ val ButtonShape = RoundedCornerShape(percent = 50) > [!NOTE] > **Note:** `Button` uses `rememberRipple()` internally to provide a `Ripple` `Indication`. It's a good idea to check the source code when implementing other custom components that wrap existing components. -If you've introduced new class types --- such as `List` to represent -gradients --- then it may be better to implement components from scratch instead -of wrapping them. For an example, take a look at -[`JetsnackButton`](https://github.com/android/compose-samples/blob/main/Jetsnack/app/src/main/java/com/example/jetsnack/ui/components/Button.kt) -from the Jetsnack sample. +If you've introduced new class types --- such as `List` to represent gradients --- then it may be better to implement components from scratch instead of wrapping them. For an example, take a look at [`JetsnackButton`](https://github.com/android/compose-samples/blob/main/Jetsnack/app/src/main/java/com/example/jetsnack/ui/components/Button.kt) from the Jetsnack sample. ## Recommended for you diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/fundamentals.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/fundamentals.md index ab0d26d..901315d 100644 --- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/fundamentals.md +++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/fundamentals.md @@ -6,10 +6,7 @@ There are three ways you can adopt Styles throughout your app: ## Available properties on Styles -Styles support many of the same properties that modifiers support; however, not -everything that is a modifier can be replicated with a Style. You still need -modifiers for certain behaviors, like interactions, custom drawing, or stacking -of properties. +Styles support many of the same properties that modifiers support; however, not everything that is a modifier can be replicated with a Style. You still need modifiers for certain behaviors, like interactions, custom drawing, or stacking of properties. | Grouping | Properties | Inherited by children | |---|---|---| @@ -36,6 +33,7 @@ of properties. Components that expose a `Style` parameter allow you to set their styling: +
```kotlin BaseButton( @@ -44,13 +42,14 @@ BaseButton( ) { BaseText("Click me") } + ```
-Within the style lambda, you can set various properties, such as `externalPadding` -or `background`: +Within the style lambda, you can set various properties, such as `externalPadding` or `background`: +
```kotlin BaseButton( @@ -59,19 +58,18 @@ BaseButton( ) { BaseText("Click me") } + ```
-For the full list of supported properties, see [Available properties on -Styles](https://developer.android.com/develop/ui/compose/styles/fundamentals#properties-styles). +For the full list of supported properties, see [Available properties on Styles](https://developer.android.com/develop/ui/compose/styles/fundamentals#properties-styles). ## Apply Styles using modifiers for components with no existing parameter -For components that lack a built-in style parameter, you can still apply styles -with the `styleable` modifier. This approach is also useful when developing your -own custom components. +For components that lack a built-in style parameter, you can still apply styles with the `styleable` modifier. This approach is also useful when developing your own custom components. +
```kotlin Row( @@ -79,13 +77,14 @@ Row( ) { BaseText("Content") } + ```
-Similar to the `style` parameter, you can include properties like `background`, -`contentPadding`, or `externalPadding` inside the lambda. +Similar to the `style` parameter, you can include properties like `background`, `contentPadding`, or `externalPadding` inside the lambda. +
```kotlin Row( @@ -95,6 +94,7 @@ Row( ) { BaseText("Content") } + ```
@@ -102,35 +102,28 @@ Row( > [!NOTE] > **Note:** When using `Modifier.styleable`, the child composables won't have those properties applied to them, unless they are inherited properties. Only the container with the `styleable` modifier has those properties applied. -Multiple chained `Modifier.styleable` modifiers are additive with non-inherited -properties on the applied composable, behaving similarly to multiple modifiers -defining the same properties. For inherited properties, these are overridden, -and the last `styleable` modifier in the chain sets the values. +Multiple chained `Modifier.styleable` modifiers are additive with non-inherited properties on the applied composable, behaving similarly to multiple modifiers defining the same properties. For inherited properties, these are overridden, and the last `styleable` modifier in the chain sets the values. -When using `Modifier.styleable`, you may also want to create and supply a -`StyleState` to be used with the modifier to apply state-based styling. For more -details, see [State and animations with -Styles](https://developer.android.com/develop/ui/compose/styles/state-animations). +When using `Modifier.styleable`, you may also want to create and supply a `StyleState` to be used with the modifier to apply state-based styling. For more details, see [State and animations with Styles](https://developer.android.com/develop/ui/compose/styles/state-animations). ## Define a standalone Style You can define a standalone Style for reusability purposes: +
```kotlin val style = Style { background(Color.Blue) } + ```
-You can then pass that defined style into a composable's style parameter or with -`Modifier.styleable`. When using `Modifier.styleable`, you also need to create a -`StyleState` object. `StyleState` is covered in detail in the [State and -animations with Styles](https://developer.android.com/develop/ui/compose/styles/state-animations) documentation. +You can then pass that defined style into a composable's style parameter or with `Modifier.styleable`. When using `Modifier.styleable`, you also need to create a `StyleState` object. `StyleState` is covered in detail in the [State and animations with Styles](https://developer.android.com/develop/ui/compose/styles/state-animations) documentation. -The following example shows how you can apply a Style either directly through a -component's built-in parameters, or through a `Modifier.styleable`: +The following example shows how you can apply a Style either directly through a component's built-in parameters, or through a `Modifier.styleable`: +
```kotlin val style = Style { background(Color.Blue) } @@ -147,12 +140,14 @@ Column( ) { BaseText("Column content") } + ```
You can also pass that Style into multiple components: +
```kotlin val style = Style { background(Color.Blue) } @@ -176,15 +171,16 @@ Row( ) { BaseText("Row") } + ```
## Add multiple Style properties -You can add multiple Style properties by setting different properties on each -line: +You can add multiple Style properties by setting different properties on each line: +
```kotlin BaseButton( @@ -196,6 +192,7 @@ BaseButton( ) { BaseText("Button") } + ```
@@ -203,12 +200,9 @@ BaseButton( > [!IMPORTANT] > **Important:** Unlike modifier-based styling, properties in Styles override one another; the last property defined takes precedence. -Properties in Styles are not additive, unlike modifier-based styling. Styles -take the last set value in the list of properties within one style block. In the -following example, with the background set twice, the `TealColor` is the applied -background. For padding, `contentPaddingTop` overrides the top -padding set by `contentPadding` and does not combine the values. +Properties in Styles are not additive, unlike modifier-based styling. Styles take the last set value in the list of properties within one style block. In the following example, with the background set twice, the `TealColor` is the applied background. For padding, `contentPaddingTop` overrides the top padding set by `contentPadding` and does not combine the values. +
```kotlin BaseButton( @@ -227,6 +221,7 @@ BaseButton( ) { BaseText("Click me!") } + ```
@@ -236,9 +231,9 @@ overrides](https://developer.android.com/static/develop/ui/compose/styles/images ## Merge multiple style objects -You can create multiple Style objects and pass them into the style parameter of -your composable. +You can create multiple Style objects and pass them into the style parameter of your composable. +
```kotlin val style1 = Style { background(TealColor) } @@ -252,6 +247,7 @@ BaseButton( ) { BaseText("Click me!") } + ```
@@ -259,12 +255,9 @@ BaseButton( ![Button with background color and contentPaddingTop set](https://developer.android.com/static/develop/ui/compose/styles/images/button_content_padding_top.png) **Figure 2.** Button with background color and `contentPaddingTop` set. -When multiple Styles specify the same property, the last set -property is chosen. Because properties are not additive in Styles, the last -padding passed in overrides the `contentPaddingHorizontal` set by the initial -`contentPadding`. Additionally, the last background color overrides the -background color set by the initial style passed in. +When multiple Styles specify the same property, the last set property is chosen. Because properties are not additive in Styles, the last padding passed in overrides the `contentPaddingHorizontal` set by the initial `contentPadding`. Additionally, the last background color overrides the background color set by the initial style passed in. +
```kotlin val style1 = Style { @@ -285,12 +278,12 @@ BaseButton( ) { BaseText("Click me!") } + ```
-In this case, the styling applied has a light gray background and `32.dp` padding, -except for the left and right padding, which has a value of `8.dp`. +In this case, the styling applied has a light gray background and `32.dp` padding, except for the left and right padding, which has a value of `8.dp`. ![Button with contentPadding that's overridden by different Styles](https://developer.android.com/static/develop/ui/compose/styles/images/button_content_padding_overrides.png) **Figure 3.** Button with `contentPadding` that's overridden by different Styles. @@ -299,9 +292,7 @@ Styles](https://developer.android.com/static/develop/ui/compose/styles/images/bu > [!NOTE] > **Note:** While the Style APIs are experimental, you need to opt-in to enable Style inheritance by setting the flag `ComposeFoundationFlags.isInheritedTextStyleEnabled = true`. -Certain style properties, such as `contentColor` and text style-related -properties, propagate to the child composables. A style set on a child -composable overrides the inherited parent styling for that specific child. +Certain style properties, such as `contentColor` and text style-related properties, propagate to the child composables. A style set on a child composable overrides the inherited parent styling for that specific child. ![Style propagation with Style, styleable, and direct parameters](https://developer.android.com/static/develop/ui/compose/styles/images/styles_modifiers_precedence_ordering.png) **Figure 4.** Style propagation with `Style`, `styleable`, and direct parameters. @@ -317,9 +308,9 @@ parameters](https://developer.android.com/static/develop/ui/compose/styles/image ### Parent styling -You can set text properties (such as `contentColor`) from the parent composable, -and they propagate to all child `Text` composables. +You can set text properties (such as `contentColor`) from the parent composable, and they propagate to all child `Text` composables. +
```kotlin val styleState = remember { MutableStyleState(null) } @@ -336,6 +327,7 @@ Column( BaseText("certain properties") BaseText("from their parents") } + ```
@@ -345,10 +337,9 @@ inheritance](https://developer.android.com/static/develop/ui/compose/styles/imag ### Child override of properties -You can also set styling on a specific `Text` composable. If the parent composable -has styling set, the styling set on the child composable overrides the -parent composable's styling. +You can also set styling on a specific `Text` composable. If the parent composable has styling set, the styling set on the child composable overrides the parent composable's styling. +
```kotlin val styleState = remember { MutableStyleState(null) } @@ -367,6 +358,7 @@ Column( BaseText("override properties") BaseText("set by their parents") } + ```
@@ -376,39 +368,40 @@ properties](https://developer.android.com/static/develop/ui/compose/styles/image ## Implement custom Style properties -You can create custom properties that map to existing Style definitions by using -extension functions on the `StyleScope`, as shown in the following example: +You can create custom properties that map to existing Style definitions by using extension functions on the `StyleScope`, as shown in the following example: +
```kotlin fun StyleScope.outlinedBackground(color: Color) { border(1.dp, color) background(color) } + ```
Apply this new property within a Style definition: +
```kotlin val customExtensionStyle = Style { outlinedBackground(Color.Blue) } + ```
-Creating new styleable properties is unsupported. If your use case -requires such support, submit a [feature request](https://issuetracker.google.com/issues/new?component=612128). +Creating new styleable properties is unsupported. If your use case requires such support, submit a [feature request](https://issuetracker.google.com/issues/new?component=612128). ## Read `CompositionLocal` values -It's a common pattern to store design system tokens within a `CompositionLocal`, -to access the variables without needing to pass them as parameters. Styles -can access `CompositionLocal`s to retrieve system-wide values within a style: +It's a common pattern to store design system tokens within a `CompositionLocal`, to access the variables without needing to pass them as parameters. Styles can access `CompositionLocal`s to retrieve system-wide values within a style: +
```kotlin val buttonStyle = Style { @@ -416,6 +409,7 @@ val buttonStyle = Style { shape(RoundedCornerShape(50)) background(Brush.verticalGradient(LocalCustomColors.currentValue.background)) } + ```
\ No newline at end of file diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/state-animations.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/state-animations.md index 01683bd..8c387a6 100644 --- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/state-animations.md +++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/state-animations.md @@ -1,15 +1,8 @@
-The Styles API offers a declarative and streamlined approach to managing UI -changes during interaction states like `hovered`, `focused`, and `pressed`. With -this API, you can significantly decrease the boilerplate code typically required -when using modifiers. +The Styles API offers a declarative and streamlined approach to managing UI changes during interaction states like `hovered`, `focused`, and `pressed`. With this API, you can significantly decrease the boilerplate code typically required when using modifiers. -To facilitate reactive styling, `StyleState` acts as a stable, read-only -interface that tracks the active state of an element (such as its enabled, -pressed, or focused status). Within a `StyleScope`, you can access this through -the `state` property to implement conditional logic directly in your Style -definitions. +To facilitate reactive styling, `StyleState` acts as a stable, read-only interface that tracks the active state of an element (such as its enabled, pressed, or focused status). Within a `StyleScope`, you can access this through the `state` property to implement conditional logic directly in your Style definitions. ## State-based interaction: Hovered, focused, pressed, selected, enabled, toggled @@ -21,15 +14,13 @@ Styles come with built-in support for common interactions: - Enabled - Toggled -It's also possible to support custom states. See the [Custom State Styling with -StyleState](https://developer.android.com/develop/ui/compose/styles/state-animations#custom-state) section for more information. +It's also possible to support custom states. See the [Custom State Styling with StyleState](https://developer.android.com/develop/ui/compose/styles/state-animations#custom-state) section for more information. ### Handle interaction states with Style parameters -The following example demonstrates modifying the `background` and `borderColor` -in response to interaction states, specifically switching to purple when hovered -and blue when focused: +The following example demonstrates modifying the `background` and `borderColor` in response to interaction states, specifically switching to purple when hovered and blue when focused: +
```kotlin @Preview @@ -56,16 +47,17 @@ private fun OpenButton() { } ) } + + ```
**Figure 1.** Changing background color based on hovered and focused states. -You can also create nested state definitions. For example, you can define a -specific style for when a button is being both pressed and hovered -simultaneously: +You can also create nested state definitions. For example, you can define a specific style for when a button is being both pressed and hovered simultaneously: +
```kotlin @Composable @@ -99,6 +91,7 @@ private fun OpenButton_CombinedStates() { } ) } + ```
@@ -107,18 +100,15 @@ private fun OpenButton_CombinedStates() { ### Custom composables with Modifier.styleable -When creating your own `styleable` components, you must connect an -`interactionSource` to a `styleState`. Then, pass this state into -`Modifier.styleable` to utilize it. +When creating your own `styleable` components, you must connect an `interactionSource` to a `styleState`. Then, pass this state into `Modifier.styleable` to utilize it. -Consider a scenario where your design system includes a `GradientButton`. You -may want to create a `LoginButton` that inherits from `GradientButton`, but -alters its colors during interactions, like being pressed. +Consider a scenario where your design system includes a `GradientButton`. You may want to create a `LoginButton` that inherits from `GradientButton`, but alters its colors during interactions, like being pressed. - To enable `interactionSource` style updates, include an `interactionSource` as a parameter within your composable. Use the provided parameter or, if one is not supplied, initialize a new `MutableInteractionSource`. - Initialize the `styleState` by providing the `interactionSource`. Make sure the `styleState`'s enabled status reflects the value of the provided enabled parameter. - Assign the `interactionSource` to the `focusable` and `clickable` modifiers. Finally, apply the `styleState` to the modifier's `styleable` parameter. +
```kotlin @Composable @@ -147,13 +137,14 @@ private fun GradientButton( content = content, ) } + ```
-You can now use the `interactionSource` state to drive style modifications with -the pressed, focused, and hovered options inside the style block: +You can now use the `interactionSource` state to drive style modifications with the pressed, focused, and hovered options inside the style block: +
```kotlin @Preview @@ -174,6 +165,7 @@ fun LoginButton() { BaseText("Login") } } + ```
@@ -182,12 +174,9 @@ fun LoginButton() { ## Animate style changes -Styles state changes come with built-in animation support. You can wrap the new -property within any state change block with `animate` to automatically add -animations between different states. This is similar to the `animate*AsState` -APIs. The following example animates the `borderColor` from black to blue when -the state changes to focused: +Styles state changes come with built-in animation support. You can wrap the new property within any state change block with `animate` to automatically add animations between different states. This is similar to the `animate*AsState` APIs. The following example animates the `borderColor` from black to blue when the state changes to focused: +
```kotlin val animatingStyle = Style { @@ -222,16 +211,16 @@ private fun AnimatingStyleChanges() { } } + ```
**Figure 4.** Animating color changes on press. -The `animate` API accepts an `animationSpec` to change the duration or shape of -the animation curve. The following example animates the size of the box with a -`spring` spec: +The `animate` API accepts an `animationSpec` to change the duration or shape of the animation curve. The following example animates the size of the box with a `spring` spec: +
```kotlin val animatingStyleSpec = Style { @@ -267,6 +256,7 @@ fun AnimatingStyleChangesSpec() { ) .styleable(styleState, animatingStyleSpec)) } + ```
@@ -275,11 +265,7 @@ fun AnimatingStyleChangesSpec() { ## Custom state styling with StyleState -Depending on your composable use case, you may have different styles that are -backed by custom states. For example, if you have a media app, you may want to -have different styling for the buttons in your `MediaPlayer` composable -depending on the playback state of the player. Follow these steps to create and -use your own custom state: +Depending on your composable use case, you may have different styles that are backed by custom states. For example, if you have a media app, you may want to have different styling for the buttons in your `MediaPlayer` composable depending on the playback state of the player. Follow these steps to create and use your own custom state: 1. Define custom key 2. Create `StyleState` extension @@ -287,11 +273,9 @@ use your own custom state: ### Define custom key -To create a custom state-based style, first create a -[`StyleStateKey`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/style/StyleStateKey) and pass in the default state value. When the -app launches, the media player is in the `Stopped` state, so it's initialized in -this way: +To create a custom state-based style, first create a [`StyleStateKey`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/style/StyleStateKey) and pass in the default state value. When the app launches, the media player is in the `Stopped` state, so it's initialized in this way: +
```kotlin enum class PlayerState { @@ -301,16 +285,16 @@ enum class PlayerState { } val playerStateKey = StyleStateKey(PlayerState.Stopped) + ```
### Create StyleState extension functions -Define an extension function on `StyleState` to query the current `playState`. -Then, create extension functions on `StyleScope` with your custom states passing -in the `playStateKey`, a lambda with the specific state, and the style. +Define an extension function on `StyleState` to query the current `playState`. Then, create extension functions on `StyleScope` with your custom states passing in the `playStateKey`, a lambda with the specific state, and the style. +
```kotlin // Extension Function on MutableStyleState to query and set the current playState @@ -324,16 +308,16 @@ fun StyleScope.playerPlaying(block: () -> Unit) { fun StyleScope.playerPaused(block: () -> Unit) { state(playerStateKey, block, { key, state -> state[key] == PlayerState.Paused }) } + ```
### Link to custom state -Define the `styleState` in your composable and set the `styleState.playState` -equal to incoming state. Pass `styleState` into the `styleable` function on the -modifier. +Define the `styleState` in your composable and set the `styleState.playState` equal to incoming state. Pass `styleState` into the `styleable` function on the modifier. +
```kotlin @Composable @@ -352,13 +336,14 @@ fun MediaPlayer( ///.. } } + ```
-Within the `style` lambda, you can apply state-based styling for custom states, -using the previously defined extension functions. +Within the `style` lambda, you can apply state-based styling for custom states, using the previously defined extension functions. +
```kotlin @Composable @@ -385,12 +370,14 @@ fun StyleStateKeySample() { style = style, state = PlayerState.Stopped) } + ```
The following code is the full snippet for this example: +
```kotlin enum class PlayerState { @@ -456,6 +443,7 @@ fun StyleStateKeySample() { style = style, state = PlayerState.Stopped) } + ```
\ No newline at end of file diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/styles-vs-modifiers.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/styles-vs-modifiers.md index cd9bc50..e6a756b 100644 --- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/styles-vs-modifiers.md +++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/styles-vs-modifiers.md @@ -1,7 +1,4 @@ -Styles differ from modifiers by design. Styles don't replace modifiers; instead, -the two systems coexist with different goals. Internally, a Style is a modifier. -You can do everything Styles can do with modifiers, but not all functionality in -modifiers is available in Styles. +Styles differ from modifiers by design. Styles don't replace modifiers; instead, the two systems coexist with different goals. Internally, a Style is a modifier. You can do everything Styles can do with modifiers, but not all functionality in modifiers is available in Styles. **Important:** - **Choose Styles if:** You need to override a default of an existing component, perform high-performance animations, or define a theme-wide set of properties for a component. @@ -19,8 +16,7 @@ The following is a comparison between Styles versus modifiers: ## Limitations of modifiers -Modifiers have many benefits in the current Compose landscape. However, Styles -address some limitations of modifiers, which the following list describes: +Modifiers have many benefits in the current Compose landscape. However, Styles address some limitations of modifiers, which the following list describes: - Modifiers are typically created in the Composition phase. Updates can force a full rerun of Composition, Layout, and Draw, even for small visual changes like color, unless you create lambda-based modifiers. - Conditional modifiers require disruptive if-else logic within fluent chains. Animating them requires manual state boilerplate and lacks a high-performance "auto-animate" mechanism. @@ -29,18 +25,15 @@ address some limitations of modifiers, which the following list describes: ## Limitations of Styles -While Styles can fill in some of the gaps that modifiers have, they also have -some limitations, which show how they cannot entirely replace modifiers: +While Styles can fill in some of the gaps that modifiers have, they also have some limitations, which show how they cannot entirely replace modifiers: - Styles are specialized Modifiers. While a modifier can do anything a Style does, the reverse is not true. Consequently, Styles can supplement, but cannot replace, modifiers. - Styles are limited to visual configuration (backgrounds, padding, borders). They cannot handle behaviors like click logic, gesture detection, or accessibility semantics. -- Resolving a Style into its final state is *more expensive than applying a - single modifier*. The system must generate a data structure containing all possible property values, and the lookup of inherited properties further complicates this. +- Resolving a Style into its final state is *more expensive than applying a single modifier*. The system must generate a data structure containing all possible property values, and the lookup of inherited properties further complicates this. ## When to use Styles over modifiers -While the choice to use Styles is largely dependent on your app and use cases, -the following guidance helps determine when to prefer a style over a modifier: +While the choice to use Styles is largely dependent on your app and use cases, the following guidance helps determine when to prefer a style over a modifier: - **To achieve theme-wide consistency:** Styles are designed to be "lifted" into a global theme. Instead of passing repetitive Modifiers to every component, you can define a single Style in your theme to create a unified look across the entire app. - **When performing frequent animations:** Styles evaluate during the Layout and Draw phases, allowing properties like color or scale to animate while bypassing the Composition phase entirely. This significantly reduces performance overhead. Use a Style instead of a modifier when doing visual property animations. diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/theming.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/theming.md index c8a373b..e80dfb9 100644 --- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/theming.md +++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/theming.md @@ -1,8 +1,7 @@ > [!NOTE] > **Note:** Styles are `@Experimental` and likely to change in upcoming releases, with Material support for Styles added in future releases. If you have any feedback, [file Styles issues](https://issuetracker.google.com/issues/new?component=612128). -There are several ways you can build out your apps using Styles. What you choose -depends on where your app sits in relation to its adoption of Material Design: +There are several ways you can build out your apps using Styles. What you choose depends on where your app sits in relation to its adoption of Material Design: 1. Fully custom design system, not using Material Design - **Recommendation**: Define component styles that consume values from the theme, and expose style parameters on design system components. @@ -11,15 +10,9 @@ depends on where your app sits in relation to its adoption of Material Design: ## The Style layer -In the traditional Compose model, customization often relies heavily on -overriding global tokens (colors and typography) provided by `MaterialTheme`, or -wrapping and overriding properties of a design system composable where possible. -Sometimes, there are properties within the Material layer that are not exposed -through the subsystems or parameters, but are hardcoded defaults on the -component itself. +In the traditional Compose model, customization often relies heavily on overriding global tokens (colors and typography) provided by `MaterialTheme`, or wrapping and overriding properties of a design system composable where possible. Sometimes, there are properties within the Material layer that are not exposed through the subsystems or parameters, but are hardcoded defaults on the component itself. -With the Styles API, there's a new layer of abstraction that's a bridge between -subsystems and components: **Styles**. +With the Styles API, there's a new layer of abstraction that's a bridge between subsystems and components: **Styles**. | Layer | Responsibility | Example | |---|---|---| @@ -32,11 +25,9 @@ subsystems and components: **Styles**. ### Atomic versus monolithic Styles -With the Styles API, you can break down a Style into separate atomic styles. -Instead of defining complex, component-specific styles like `baseButtonStyle`, -you can also create small, single-purpose utility styles. These act as your -"atoms". +With the Styles API, you can break down a Style into separate atomic styles. Instead of defining complex, component-specific styles like `baseButtonStyle`, you can also create small, single-purpose utility styles. These act as your "atoms". +
```kotlin // Define single-purpose "atomic" styles @@ -69,19 +60,18 @@ val interactiveShadowAtomic = Style { } } } + + ```
#### Composition using "then" -One of the powerful features of the new Styles API is the `then` operator, which -lets you merge multiple `Style` objects. This lets you build a component using -atomic utility classes. +One of the powerful features of the new Styles API is the `then` operator, which lets you merge multiple `Style` objects. This lets you build a component using atomic utility classes. **Traditional (non-atomic)**: - ```kotlin // One large monolithic style val buttonStyle = Style { @@ -89,49 +79,39 @@ val buttonStyle = Style { shape(RoundedCornerShape(8.dp)) background(Color.Blue) } + ```
**Atomic refactor**: - ```kotlin // Combine atoms to create the final appearance val buttonStyle = paddingAtomic then roundedCornerShapeAtomic then primaryBackgroundAtomic then interactiveShadowAtomic + ```
## Adopt Styles in your design system -Consider the following options when adopting Styles within your design system, -depending on where in the spectrum your design system lies. +Consider the following options when adopting Styles within your design system, depending on where in the spectrum your design system lies. ### Custom design system with Styles -***Consider when**: You've been handed an extensive brand guide that is not -based on Material Design, and you are not planning to use Material Design*. +***Consider when**: You've been handed an extensive brand guide that is not based on Material Design, and you are not planning to use Material Design*. -***Strategy**: Implement a fully custom design system, and expose styles as part -of the theme*. +***Strategy**: Implement a fully custom design system, and expose styles as part of the theme*. -This option is the custom path if you don't use Material as your main design -system language. You bypass `MaterialTheme` entirely for visual definitions and -have created your [own custom theme already](https://developer.android.com/develop/ui/compose/designsystems/custom#implementing-fully-custom). You build a `CompanyTheme` that -acts as a container for your Styles. +This option is the custom path if you don't use Material as your main design system language. You bypass `MaterialTheme` entirely for visual definitions and have created your [own custom theme already](https://developer.android.com/develop/ui/compose/designsystems/custom#implementing-fully-custom). You build a `CompanyTheme` that acts as a container for your Styles. - **How it works** : Create a `CompanyTheme` object that holds `Style` objects for every component in your system. Your components (either wrappers around Material logic or custom `Box` or `Layout` implementations) consume these styles directly, and expose a `Style` parameter for consumers of your design system. - **The Style layer**: Styles are the primary definition of your design system. Tokens are named variables fed into these styles. This allows for deep customization, such as defining unique animations for state changes (for example, animating scale and color on press). -If you are building out your own [custom theme](https://developer.android.com/develop/ui/compose/designsystems/custom) without using Material, and -want to adopt styles, add your list of styles to your Theme. This lets you -access your base styles from anywhere in your project. - -1. Create a `Styles` class that stores the various styles in your application - and create the defaults. For example, in the Jetsnack app - the class is - named `JetsnackStyles`: +If you are building out your own [custom theme](https://developer.android.com/develop/ui/compose/designsystems/custom) without using Material, and want to adopt styles, add your list of styles to your Theme. This lets you access your base styles from anywhere in your project. +1. Create a `Styles` class that stores the various styles in your application and create the defaults. For example, in the Jetsnack app - the class is named `JetsnackStyles`: ```kotlin object JetsnackStyles{ @@ -154,13 +134,12 @@ access your base styles from anywhere in your project. contentColor(colors.textPrimary) } } + ```
-2. Provide `Styles` as part of your overall theme, and expose helper extension - functions on `StyleScope` to access the subsystems: - +2. Provide `Styles` as part of your overall theme, and expose helper extension functions on `StyleScope` to access the subsystems: ```kotlin @Immutable @@ -215,13 +194,13 @@ access your base styles from anywhere in your project. ) } } + ```
3. Access `JetsnackStyles` within your composable: - ```kotlin @Composable fun CustomButton(modifier: Modifier, @@ -245,13 +224,9 @@ access your base styles from anywhere in your project. Text(text) } } + ```
-Beyond global theme adoption, there are alternative strategies for incorporating -`Styles` into your apps. You can leverage `Styles` inline for specific call -sites or use static definitions when full theming capabilities are unnecessary. -`Styles` shouldn't be swapped conditionally unless the whole style is -fundamentally different. You should prefer accessing dynamic tokens inside a -visual definition rather than switching between distinct style objects. \ No newline at end of file +Beyond global theme adoption, there are alternative strategies for incorporating `Styles` into your apps. You can leverage `Styles` inline for specific call sites or use static definitions when full theming capabilities are unnecessary. `Styles` shouldn't be swapped conditionally unless the whole style is fundamentally different. You should prefer accessing dynamic tokens inside a visual definition rather than switching between distinct style objects. \ No newline at end of file diff --git a/media/media3-cast-integration/SKILL.md b/media/media3-cast-integration/SKILL.md new file mode 100644 index 0000000..e6fb809 --- /dev/null +++ b/media/media3-cast-integration/SKILL.md @@ -0,0 +1,224 @@ +--- +name: media3-cast-integration +description: Implements Google Cast support in Android apps using Jetpack Media3. + Handles adding build dependencies, updating manifest, configuring OptionsProvider, + and managing CastPlayer or RemoteCastPlayer for playback in both Compose and View-based + UIs. Use when adding Cast functionality or migrating from legacy Cast SDK to Media3 + Cast. +license: Complete terms in LICENSE.txt +metadata: + author: Google LLC + last-updated: '2026-08-06' + keywords: + - Android + - Media3 + - Cast + - Integration + - Migration + - ExoPlayer + - MediaSession + - Jetpack Media3 +--- + +## Prerequisites + +- Jetpack Media3 version must be `>= 1.9.0`. Cast isn't available in lower versions. + +## Glossary + +- **`CastPlayer`** : Media3 `Player` that controls playback on both local and remote Cast devices. +- **`RemoteCastPlayer`** : Media3 `Player` that communicates with a Cast receiver, only used for remote playback. +- **Google Cast SDK**: Legacy casting SDK in maintenance mode, superseded by Jetpack Media3. +- **`OptionsProvider`** : Interface providing configuration options to initialize GMS `CastContext`. + +## Common guidelines + +- Legacy [Google Cast SDK](https://developers.google.com/cast) is in maintenance mode. +- For new Cast setups: + - You must use [Jetpack Media3 Cast](references/android/media/media3/cast/index.md). + - You mustn't use legacy Cast SDK unless explicitly requested. + +## Step 1: Set up dependencies + +To complete this step, you **MUST** ensure the following: + +- In the app-level build file, declare the `media3-cast` dependency version 1.9.0 or higher. + + implementation("androidx.media3:media3-cast:1.10.1") + +- Ensure required Media3 dependencies are present: + + - `androidx.media3:media3-exoplayer` + - `androidx.media3:media3-session` + - `androidx.media3:media3-ui-compose` +- If the application uses legacy Views, add `media3-ui`. + +- Enforce the same versions across all Media3 dependencies. + +- Use configurations in "Add build dependencies" section of [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md) as the source of truth. + +- **For apps without an existing Cast integration:** + + - Verify legacy Cast SDK (`libs.play.services.cast.framework`) is absent. +- **If Migrating from Legacy Cast SDK:** + + - Add Media3 Cast dependencies first. + - Keep existing legacy dependencies untouched at this stage to prevent compilation errors. + +## Step 2: Update the manifest + +To complete this step, you **MUST** ensure the following: + +- Inside the manifest's `` tag, declare the Cast options provider. +- Use `DefaultCastOptionsProvider` by default. See the "OptionsProvider" section in [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md). +- Declare a custom `OptionsProvider` only if explicitly requested. See [Customize CastOptions](references/android/media/media3/cast/customize-castoptions.md). +- Ensure `INTERNET` permission is present. Don't add any unnecessary permissions. +- **If Migrating from Legacy Cast SDK:** + - Don't delete existing custom options provider files or manifest entries. + +## Step 3: Implement the player and service + +### Architecture baseline + +Before integrating Media3 Cast, an existing app follows one of two setups: + +- **Local-only playback:** Uses Media3 `ExoPlayer` only to support local playback. +- **Legacy Cast setup:** Uses `ExoPlayer` for local playback, alongside a `Player` wrapper over the legacy `RemoteMediaClient` for remote playback. The UI interfaces with a `MediaSession` interacting with a `ForwardingPlayer`, which finally routes controls to either local or remote playback. + +To complete this step, you **MUST** ensure the following: + +- Inside the application's `MediaSessionService` (or `MediaLibraryService`) `onCreate()` method, initialize `ExoPlayer` and `CastPlayer`. +- Use `CastPlayer` by default unless `RemoteCastPlayer` is explicitly requested. See the "Build a CastPlayer" section in [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md). +- For `CastPlayer`, pass the instance directly to `MediaSession.Builder`. +- Replace all legacy forwarding player wrappers. +- Don't delete legacy class files yet to prevent compilation errors during migration. + +### Advanced: `RemoteCastPlayer` + +- Use `RemoteCastPlayer` only if explicitly requested by user. +- Initialize `MediaSession` with `localPlayer` and set a `SessionAvailabilityListener` on `RemoteCastPlayer` to transfer playback state on Cast session availability changes: + + class PlaybackService : MediaSessionService() { + private var mediaSession: MediaSession? = null + private lateinit var localPlayer: ExoPlayer + private lateinit var remotePlayer: RemoteCastPlayer + + override fun onCreate() { + super.onCreate() + + localPlayer = ExoPlayer.Builder(this).build() + remotePlayer = RemoteCastPlayer.Builder(this).build() + mediaSession = MediaSession.Builder(this, localPlayer).build() + + remotePlayer.setSessionAvailabilityListener( + object : SessionAvailabilityListener { + override fun onCastSessionAvailable() { + transferPlaybackState(localPlayer, remotePlayer) + } + + override fun onCastSessionUnavailable() { + transferPlaybackState(remotePlayer, localPlayer) + } + } + ) + } + + private fun transferPlaybackState(previousPlayer: Player, newPlayer: Player) { + if (previousPlayer.mediaItemCount > 0) { + val transferStateBuilder = PlayerTransferState.builderFromPlayer(previousPlayer) + if (previousPlayer.playbackState == Player.STATE_ENDED || + previousPlayer.currentPosition == C.TIME_END_OF_SOURCE) { + transferStateBuilder.setCurrentMediaItemIndex(0) + transferStateBuilder.setCurrentPosition(0) + } + transferStateBuilder.build().setToPlayer(newPlayer) + } + + previousPlayer.stop() + previousPlayer.clearMediaItems() + newPlayer.prepare() + mediaSession?.setPlayer(newPlayer) + } + } + +## Step 4: Set up the UI + +### Compose-based UI + +To complete this step, you **MUST** ensure the following: + +- See the "Add a MediaRouteButton Composable to the Player" section in [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md) for Compose integration guidelines. +- Use the [`MediaRouteButton` composable](https://developer.android.com/reference/kotlin/androidx/media3/cast/MediaRouteButton.composable) from `androidx.media3.cast` package. +- Don't use `AndroidView` in the Compose UI hierarchy. +- Place `MediaRouteButton` in an area next to playback controls. Don't hide it behind system UI. +- Don't use `PlayerSurface` for custom player UI. Use the Material3 [`Player` composable](https://developer.android.com/reference/kotlin/androidx/media3/ui/compose/material3/Player.composable). +- Force recomposition on playback location shifts to ensure UI sync. Use key constraints on `DeviceInfo` changes: + + @OptIn(UnstableApi::class) + @Composable + fun MainScreen() { + val player = rememberMediaController() + val deviceInfo = rememberDeviceInfo(player) + player?.let { activePlayer -> key(deviceInfo) { PlayerScreen(player = activePlayer) } } + } + + @Composable + private fun rememberMediaController(): Player? { + // Logic to connect MediaController to MediaSession and release it + } + + @Composable + private fun rememberDeviceInfo(player: Player?): DeviceInfo? { + var deviceInfo by remember(player) { mutableStateOf(player?.deviceInfo) } + DisposableEffect(player) { + val activePlayer = player ?: return@DisposableEffect onDispose {} + deviceInfo = activePlayer.deviceInfo + val listener = object : Player.Listener { + override fun onDeviceInfoChanged(info: DeviceInfo) { + deviceInfo = info + } + } + activePlayer.addListener(listener) + onDispose { activePlayer.removeListener(listener) } + } + return deviceInfo + } + +### View-based UI + +To complete this step, you **MUST** ensure the following: + +- For View-based UI setups, see the "Add UI elements" section in [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md). +- Casting Activities must extend `AppCompatActivity` or `FragmentActivity` and use a `Theme.AppCompat` descendant. +- Ensure the `AppCompat` theme has a visible `ActionBar` if adding `MediaRouteButton` to the options menu. +- Replace all instances and imports of `CastButtonFactory` with `MediaRouteButtonFactory`. +- Rebind `PlayerView.player` references upon `onDeviceInfoChanged` events to prevent black screens or UI freezes: + + private val playerListener: Player.Listener = + object : Player.Listener { + override fun onDeviceInfoChanged(deviceInfo: DeviceInfo) { + // Resetting to null bypasses PlayerView.setPlayer()'s instance equality check + // (this.player == player), forcing it to re-bind the video surface to the controller. + playerView.player = null + playerView.player = controller + } + } + +- **Migration to Compose:** + + - Don't use `AndroidView` to wrap the legacy `PlayerView`. + - Implement Material3 [`Player` composable](https://developer.android.com/reference/kotlin/androidx/media3/ui/compose/material3/Player.composable) and [`MediaRouteButton` composable](https://developer.android.com/reference/kotlin/androidx/media3/cast/MediaRouteButton.composable) as per [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md). + - Remove legacy XML layout declarations, menu files, and View component references. + +## Step 5: Clean up legacy Cast SDK code + +> [!WARNING] +> **Warning:** Don't perform cleanup directly. Remove legacy files and dependencies only when explicitly requested by the user. + +To complete this step, you **MUST** ensure the following: + +- Remove legacy GMS Cast SDK (`libs.play.services.cast.framework`) and MediaRouter (`libs.androidx.mediarouter`) dependencies. +- Delete custom `OptionsProvider` classes and manifest entries if `DefaultCastOptionsProvider` is adopted. +- Remove legacy `MediaTransferReceiver` manifest declarations if present. +- Remove all references to legacy Cast SDK components such as legacy helper wrappers, forwarding players, and `RemoteMediaClient` interfaces. +- Delete legacy View XML layouts, menu files, and references to `PlayerView` if the migration to Compose is complete. diff --git a/media/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md b/media/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md new file mode 100644 index 0000000..9edd7bb --- /dev/null +++ b/media/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md @@ -0,0 +1,367 @@ +The [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) is a Jetpack Media3 [Player](https://developer.android.com/reference/kotlin/androidx/media3/common/Player) implementation that supports both local playback and casting to a remote Cast-enabled device. [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) simplifies adding cast functionality to your app and provides rich features to seamlessly switch between local and remote playback. This guide shows you how to integrate [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) into your media app. + +To integrate Cast with other platforms, see the [Cast SDK](https://developers.google.com/cast/docs/developers). + +## Get a Cast-enabled device + +To test `CastPlayer`, you need a [Cast-enabled device](https://store.google.com/gb/category/connected_home?hl=en-GB). Choices include Android TV, Chromecast, smart speakers, and smart displays. Verify that your device is set up and connected to the same Wi-Fi network as your development mobile for discovery. + +## Add build dependencies + +To start using `CastPlayer`, add the AndroidX Media3 and `CastPlayer` dependencies to the `build.gradle` file of your app module. + +### Kotlin + + implementation("androidx.media3:media3-exoplayer:1.10.1") + implementation("androidx.media3:media3-ui:1.10.1") + implementation("androidx.media3:media3-session:1.10.1") + implementation("androidx.media3:media3-cast:1.10.1") + +### Groovy + + implementation "androidx.media3:media3-exoplayer:1.10.1" + implementation "androidx.media3:media3-ui:1.10.1" + implementation "androidx.media3:media3-session:1.10.1" + implementation "androidx.media3:media3-cast:1.10.1" + +## Configure your CastPlayer + +To configure the [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer), update your `AndroidManifest.xml` file with an options provider. + +### Options provider + +The [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) requires an options provider to configure its behavior. For a basic setup, you can use the [`DefaultCastOptionsProvider`](https://developer.android.com/reference/androidx/media3/cast/DefaultCastOptionsProvider) by adding it to your `AndroidManifest.xml` file. This uses default settings, including the default receiver application. + + + ... + + ... + + +To customize the configuration, implement your own custom `OptionsProvider`. See the [CastOptions](https://developer.android.com/media/media3/cast/customize-castoptions) guide to learn how. + +### Add a receiver for media transfers + +Adding a `MediaTransferReceiver` to your manifest enables the System UI to discover Cast-enabled devices on the network and reroute media without opening the app activity. For example, a user can change the device playing your app's media from the [media notification](https://developer.android.com/media/implement/surfaces/mobile). + + + ... + + ... + + +## Build a CastPlayer + +For remote playback with Cast, your app should be able to manage playback even when the user isn't interacting with an Activity from your app, such as through the system media notification. For this reason, you should create your `ExoPlayer` (for local playback) and `CastPlayer` (for remote playback) instances in a service, such as [MediaSessionService](https://developer.android.com/media/media3/session/background-playback#service-lifecycle) or [MediaLibraryService](https://developer.android.com/guide/topics/media/session/medialibraryservice). First, create your `ExoPlayer` instance and then when building your [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) instance, set `ExoPlayer` as the local player instance. You can then switch media playback between your mobile and the Cast-enabled device from the media notification or the lock screen notification. Media3 uses the **Output Switcher** feature to handle player transfers when the output route changes from local to remote or from remote to local. +![Screenshot showing the Output Switcher UI in notifications.](https://developer.android.com/static/media/media3/cast/images/output_switcher.jpeg) Figure 1: (a) Device chip on Media notification (b) Cast-enabled devices shown on tapping the device chip (c) Device chip on Lock screen notification + +
+ +### Kotlin + +```kotlin +override fun onCreate() { + super.onCreate() + + val exoPlayer = ExoPlayer.Builder(context).build() + val castPlayer = CastPlayer.Builder(context).setLocalPlayer(exoPlayer).build() + + mediaSession = MediaSession.Builder(context, castPlayer).build() +} + + +``` + +### Java + +```java +@Override +public void onCreate() { + super.onCreate(); + + ExoPlayer exoPlayer = new ExoPlayer.Builder(context).build(); + CastPlayer castPlayer = new CastPlayer.Builder(context).setLocalPlayer(exoPlayer).build(); + + mediaSession = + new MediaSession.Builder(/* context= */ context, /* player= */ castPlayer).build(); +} + + +``` + +
+ +> [!IMPORTANT] +> **Important:** The preceding code snippet shows the `onCreate` method of a `MediaSessionService`. In an `Activity`, players should be created in `onStart` or `onResume`. + +## Add UI elements + +Add a [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) to your app's UI. Tapping the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) opens a dialog displaying a list of available Cast-enabled devices on the network. When the user selects a device, the media playback is transferred from the mobile to the selected receiver device. This section shows you how to add the button and listen for events to update your UI when playback switches between local and remote devices. + +### Set the MediaRouteButton + +There are four ways to add the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) to your activity's UI. The best choice depends on your app's design and requirements. + +- **Compose UI**: Add a button composable. +- **Views UI** : + - Add the button to the app bar menu. + - Add the button inside `PlayerView`. + - Add the button as a standard `View`. + +![Screenshot showing the MediaRouteButton in the UI.](https://developer.android.com/static/media/media3/cast/images/cast.jpeg) Figure 2: (a) MediaRouteButton in menu bar, (b) as a View, (c) in PlayerView, and (d) Dialog of Cast-enabled devices. + +> [!IMPORTANT] +> **Important:** To use the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) in Views UI, the containing activity must be a subclass of `FragmentActivity`. + +> [!TIP] +> **Tip:** These screenshots are from the [demo-session](https://github.com/androidx/media/tree/release/demos/session) apps in Media3. You can checkout the app to see an example of `CastPlayer` implementation. + +#### Add a Composable `MediaRouteButton` to the Player + +You can add the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) Composable to your player's UI. For more information, see the [Compose](https://developer.android.com/media/media3/ui/compose) guide. + +
+ +```kotlin +@Composable +fun PlayerComposeView(player: Player, modifier: Modifier = Modifier) { + var controlsVisible by remember { mutableStateOf(false) } + + Box( + modifier = modifier.clickable { controlsVisible = true }, + contentAlignment = Alignment.Center, + ) { + PlayerSurface(player = player, modifier = modifier) + AnimatedVisibility(visible = controlsVisible, enter = fadeIn(), exit = fadeOut()) { + Box(modifier = Modifier.fillMaxSize()) { + MediaRouteButton(modifier = Modifier.align(Alignment.TopEnd)) + PrimaryControls(player = player, modifier = Modifier.align(Alignment.Center)) + } + } + } +} + +@Composable +fun PrimaryControls(player: Player, modifier: Modifier = Modifier) { + // ... +} + + +``` + +
+ +#### Add the `MediaRouteButton` to the PlayerView + +You can add the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) directly within the [PlayerView](https://developer.android.com/guide/topics/media/ui/playerview)'s UI controls. After setting the [MediaController](https://developer.android.com/guide/topics/media/session/mediacontroller) as the player for your `PlayerView`, provide a `MediaRouteButtonViewProvider` to display the Cast button on the Player. + +
+ +### Kotlin + +```kotlin +override fun onStart() { + super.onStart() + + playerView.player = mediaController + playerView.setMediaRouteButtonViewProvider(MediaRouteButtonViewProvider()) +} + +``` + +### Java + +```java +@Override +public void onStart() { + super.onStart(); + + playerView.setPlayer(mediaController); + playerView.setMediaRouteButtonViewProvider(new MediaRouteButtonViewProvider()); +} + +``` + +
+ +#### Add the `MediaRouteButton` to the app bar menu + +To set up a [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) in the app bar menu, create an XML menu and override `onCreateOptionsMenu` in your `Activity`. + + + + + +
+ +### Kotlin + +```kotlin +override fun onCreateOptionsMenu(menu: Menu): Boolean { + // ... + menuInflater.inflate(R.menu.sample_media_route_button_menu, menu) + val menuItemFuture: ListenableFuture = + MediaRouteButtonFactory.setUpMediaRouteButton(context, menu, R.id.media_route_menu_item) + Futures.addCallback( + menuItemFuture, + object : FutureCallback { + override fun onSuccess(menuItem: MenuItem?) { + // Do something with the menu item. + } + + override fun onFailure(t: Throwable) { + // Handle the failure. + } + }, + executor, + ) + // ... + return true +} + +``` + +### Java + +```java +@Override +public boolean onCreateOptionsMenu(Menu menu) { + // ... + getMenuInflater().inflate(R.menu.sample_media_route_button_menu, menu); + ListenableFuture menuItemFuture = + MediaRouteButtonFactory.setUpMediaRouteButton(context, menu, R.id.media_route_menu_item); + Futures.addCallback( + menuItemFuture, + new FutureCallback() { + @Override + public void onSuccess(MenuItem menuItem) { + // Do something with the menu item. + } + + @Override + public void onFailure(Throwable t) { + // Handle the failure. + } + }, + executor); + // ... + return true; +} + +``` + +
+ +#### Add the `MediaRouteButton` as a View + +You can set up a [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) in your activity layout.xml. + + + +To complete the setup for the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton), use the Media3 Cast `MediaRouteButtonFactory` in your `Activity` code. + +
+ +### Kotlin + +```kotlin +override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + findViewById(R.id.media_route_button)?.also { + val unused = MediaRouteButtonFactory.setUpMediaRouteButton(context, it) + } +} + +``` + +### Java + +```java +@Override +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // ... + MediaRouteButton button = findViewById(R.id.media_route_button); + ListenableFuture setUpFuture = + MediaRouteButtonFactory.setUpMediaRouteButton(context, button); +} + +``` + +
+ +### Activity Listener + +Create a `Player.Listener` in your `Activity` to listen for changes to media playback location. When the `playbackType` changes between `PLAYBACK_TYPE_LOCAL` and `PLAYBACK_TYPE_REMOTE`, you can adjust your UI as needed. To prevent memory leaks and to confine listener activity to only when your app is visible, register the listener in `onStart` and unregister it in `onStop`: + +
+ +### Kotlin + +```kotlin +private val playerListener: Player.Listener = + object : Player.Listener { + override fun onDeviceInfoChanged(deviceInfo: DeviceInfo) { + if (deviceInfo.playbackType == DeviceInfo.PLAYBACK_TYPE_LOCAL) { + // Add UI changes for local playback. + } else if (deviceInfo.playbackType == DeviceInfo.PLAYBACK_TYPE_REMOTE) { + // Add UI changes for remote playback. + } + } + } + +override fun onStart() { + super.onStart() + mediaController.addListener(playerListener) +} + +override fun onStop() { + super.onStop() + mediaController.removeListener(playerListener) +} + +``` + +### Java + +```java +private final Player.Listener playerListener = + new Player.Listener() { + @Override + public void onDeviceInfoChanged(DeviceInfo deviceInfo) { + if (deviceInfo.playbackType == DeviceInfo.PLAYBACK_TYPE_LOCAL) { + // Add UI changes for local playback. + } else if (deviceInfo.playbackType == DeviceInfo.PLAYBACK_TYPE_REMOTE) { + // Add UI changes for remote playback. + } + } + }; + +@Override +protected void onStart() { + super.onStart(); + mediaController.addListener(playerListener); +} + +@Override +protected void onStop() { + super.onStop(); + mediaController.removeListener(playerListener); +} + +``` + +
+ +For more information about listening and responding to playback events, see the [player events](https://developer.android.com/media/media3/exoplayer/listening-to-player-events) guide. \ No newline at end of file diff --git a/media/media3-cast-integration/references/android/media/media3/cast/customize-castoptions.md b/media/media3-cast-integration/references/android/media/media3/cast/customize-castoptions.md new file mode 100644 index 0000000..caf237a --- /dev/null +++ b/media/media3-cast-integration/references/android/media/media3/cast/customize-castoptions.md @@ -0,0 +1,88 @@ +To configure your app's Cast session, provide an [`OptionsProvider`](https://developers.google.com/android/reference/com/google/android/gms/cast/framework/OptionsProvider). Use the [`CastOptions`](https://developers.google.com/android/reference/com/google/android/gms/cast/framework/CastOptions) object built by the provider to set the receiver application ID, manage session lifecycles, and customize media playback behavior. + +## Use the default options provider + +For a basic setup that uses the default Cast receiver application, add the `DefaultCastOptionsProvider` to your app's `AndroidManifest.xml` file: + + + ... + + ... + + +## Create a custom options provider + +For more advanced configurations, such as setting a custom receiver application ID, you need to create your own `OptionsProvider`. + +### 1. Declare the provider in your manifest + +First, declare your custom provider in `AndroidManifest.xml`. Make sure to use the fully qualified class name. + + + ... + + ... + + +### 2. Implement the OptionsProvider interface + +Next, create a class that implements the `OptionsProvider` interface. In this class, you must override `getCastOptions()` to return a `CastOptions` instance. The custom `OptionsProvider` class is where you configure your Cast session, for example, by setting your custom receiver application ID. + +For more information, see [CastOptions.Builder](https://developers.google.com/android/reference/com/google/android/gms/cast/framework/CastOptions.Builder). + +
+ +### Kotlin + +```kotlin +class MyCustomCastOptionsProvider : OptionsProvider { + + override fun getCastOptions(context: Context): CastOptions { + return CastOptions.Builder() + .setReceiverApplicationId(APP_ID) + .setRemoteToLocalEnabled(true) + .build() + } + + override fun getAdditionalSessionProviders(context: Context): List? { + return null + } + + companion object { + // Add your receiver app ID in . + private const val APP_ID = "" + } +} + +``` + +### Java + +```java +public static final class MyCustomCastOptionsProvider implements OptionsProvider { + + // Add your receiver app ID in . + public static final String APP_ID = ""; + + @Override + public CastOptions getCastOptions(Context context) { + return new CastOptions.Builder() + .setReceiverApplicationId(APP_ID) + .setRemoteToLocalEnabled(true) + .build(); + } + + @Override + @Nullable + public List getAdditionalSessionProviders(Context context) { + return null; + } +} + +``` + +
\ No newline at end of file diff --git a/media/media3-cast-integration/references/android/media/media3/cast/index.md b/media/media3-cast-integration/references/android/media/media3/cast/index.md new file mode 100644 index 0000000..1a38415 --- /dev/null +++ b/media/media3-cast-integration/references/android/media/media3/cast/index.md @@ -0,0 +1,13 @@ +The Media3 [`cast`](https://developer.android.com/reference/androidx/media3/cast/package-summary) module extends your media playback experience to Cast devices. It lets your app cast content to [compatible devices](https://developer.android.com/media/media3/cast/create-castplayer#get-device), such as TVs and speakers. The [sender](https://developers.google.com/cast/glossary#sender) app acts as a remote controller for media playback on the [receiver](https://developers.google.com/cast/glossary#receiver) device. This module integrates with the [Jetpack Media3](https://developer.android.com/guide/topics/media/media3) library, so you can use the same `Player` interface and UI components for both local and remote playback. + +## Media3 CastPlayer + +The `CastPlayer` is a media player API included in Media3 that supports both local and remote media playback. It implements the `Player` interface to manage playback, simplifying the integration of casting into your media experience. + +[Go to Media3 CastPlayer](https://developer.android.com/media/media3/cast/create-castplayer) + +## Other Cast integrations + +The Cast SDK overview explains how to integrate Cast with other platforms, such as building a receiver app or integrating with the web sender SDK. + +[Explore Cast SDK](https://developers.google.com/cast/docs/developers) \ No newline at end of file diff --git a/navigation/navigation-3/SKILL.md b/navigation/navigation-3/SKILL.md index 4957098..a7029fe 100644 --- a/navigation/navigation-3/SKILL.md +++ b/navigation/navigation-3/SKILL.md @@ -8,7 +8,7 @@ description: Learn how to install and migrate to Jetpack Navigation 3, and how t license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-18' + last-updated: '2026-08-06' keywords: - recipe - Android @@ -63,8 +63,10 @@ Code examples showcasing common patterns. ### Deep links -- *[Basic](references/android/guide/navigation/navigation-3/recipes/deeplinks-basic.md)*: Shows how to parse a deep link URL from an Android Intent into a navigation key. -- *[Advanced](references/android/guide/navigation/navigation-3/recipes/deeplinks-advanced.md)*: Shows how to handle deep links with a synthetic back stack and correct "Up" navigation behavior. +- *[Static URI](references/android/guide/navigation/navigation-3/recipes/deeplinks-staticuri.md)*: Shows how to handle simple static URI deep links. +- *[URI with Arguments](references/android/guide/navigation/navigation-3/recipes/deeplinks-uriarguments.md)*: Shows how to parse path and query arguments from a deep link. +- *[Synthetic BackStack](references/android/guide/navigation/navigation-3/recipes/deeplinks-syntheticbackstack.md)*: Shows how to handle deep links with a synthetic back stack. +- *[Custom Matcher](references/android/guide/navigation/navigation-3/recipes/deeplinks-custommatcher.md)*: Shows how to implement custom deep link matching logic. ### Scenes @@ -86,6 +88,7 @@ Code examples showcasing common patterns. ### Animations - *[Animations](references/android/guide/navigation/navigation-3/recipes/animations.md)*: Shows how to override the default animations for all destinations and a single destination. +- *[Conditional Transitions](references/android/guide/navigation/navigation-3/recipes/conditional-transitions.md)*: Shows how to implement conditional transition animations. ### Common back stack behavior @@ -95,6 +98,10 @@ Code examples showcasing common patterns. - *[Conditional navigation](references/android/guide/navigation/navigation-3/recipes/conditional.md)*: Switch to a different navigation flow when a condition is met. For example, for authentication or first-time user onboarding. +### Lifecycle + +- *[Lifecycle Owner](references/android/guide/navigation/navigation-3/recipes/lifecycle-owner.md)*: Shows how to use and observe Lifecycle in Navigation 3. + ### Architecture - *[Modularized navigation code (Hilt)](references/android/guide/navigation/navigation-3/recipes/modular-hilt.md)*: Demonstrates how to decouple navigation code into separate modules using Hilt or Dagger for DI. diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/index.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/index.md index b4cefbf..66f2297 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/index.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/index.md @@ -1,7 +1,18 @@ -Navigation 3 is a new navigation library designed to work with Compose. With -Navigation 3, you have full control over your back stack, and navigating to and -from destinations is as simple as adding and removing items from a list. It -creates a flexible app navigation system by providing: +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/navigation/navigation-3) + +### Jetpack Navigation 3 + +Use an Android skill to help you build using Jetpack Navigation 3. To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill navigation-3 + +
+ +Navigation 3 is a new navigation library designed to work with Compose. With Navigation 3, you have full control over your back stack, and navigating to and from destinations is as simple as adding and removing items from a list. It creates a flexible app navigation system by providing: - Conventions for modeling a back stack, where each entry on the back stack represents content that the user has navigated to - A UI that automatically updates with back stack changes (including animations) @@ -11,28 +22,23 @@ creates a flexible app navigation system by providing: At a high level, you implement Navigation 3 in the following ways: -1. Define the content that users can navigate to in your app, each with a unique key, and add a function to resolve that key to the content. See [Resolve keys - to content](https://developer.android.com/guide/navigation/navigation-3/basics#resolve-keys). +1. Define the content that users can navigate to in your app, each with a unique key, and add a function to resolve that key to the content. See [Resolve keys to content](https://developer.android.com/guide/navigation/navigation-3/basics#resolve-keys). 2. Create a back stack that keys are pushed onto and removed as users navigate your app. See [Create a back stack](https://developer.android.com/guide/navigation/navigation-3/basics#create-back). -3. Use a [`NavDisplay`](https://developer.android.com/reference/kotlin/androidx/navigation3/ui/NavDisplay.composable) to display your app's back stack. Whenever the back stack changes, it updates the UI to display relevant content. See [Display - the back stack](https://developer.android.com/guide/navigation/navigation-3/basics#display-back). +3. Use a [`NavDisplay`](https://developer.android.com/reference/kotlin/androidx/navigation3/ui/NavDisplay.composable) to display your app's back stack. Whenever the back stack changes, it updates the UI to display relevant content. See [Display the back stack](https://developer.android.com/guide/navigation/navigation-3/basics#display-back). 4. Modify `NavDisplay`'s [scene strategies](https://developer.android.com/guide/navigation/navigation-3/custom-layouts) as needed to support adaptive layouts and different platforms. You can see the [full source code](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:navigation3/) for Navigation 3 on AOSP. ## Improvements upon Jetpack Navigation -Navigation 3 improves upon the original Jetpack Navigation API in the following -ways: +Navigation 3 improves upon the original Jetpack Navigation API in the following ways: - Provides a simpler integration with Compose - Offers you full control of the back stack - Makes it possible to create layouts that can read more than one destination from the back stack at the same time, allowing them to adapt to changes in window size and other inputs. -Read more about Navigation 3's principles and API design choices in [this blog -post](https://android-developers.googleblog.com/2025/05/announcing-jetpack-navigation-3-for-compose.html). +Read more about Navigation 3's principles and API design choices in [this blog post](https://android-developers.googleblog.com/2025/05/announcing-jetpack-navigation-3-for-compose.html). ## Code samples -The [recipes repository](https://github.com/android/nav3-recipes) contains examples of how to use the -Navigation 3 building blocks to solve common navigation challenges. \ No newline at end of file +The [recipes repository](https://github.com/android/nav3-recipes) contains examples of how to use the Navigation 3 building blocks to solve common navigation challenges. \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/migration-guide.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/migration-guide.md index ba86f3c..970e3da 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/migration-guide.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/migration-guide.md @@ -1,3 +1,17 @@ +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/navigation/navigation-3) + +### Jetpack Navigation 3 + +Use an Android skill to help you build and migrate to Jetpack Navigation 3. To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill navigation-3 + +
+ To migrate your app from [Navigation 2](https://developer.android.com/guide/navigation) to Navigation 3, follow these steps: 1. Add the Navigation 3 dependencies. @@ -8,46 +22,16 @@ To migrate your app from [Navigation 2](https://developer.android.com/guide/navi 6. Replace `NavHost` with `NavDisplay`. 7. Remove Navigation 2 dependencies. -> [!IMPORTANT] -> **Important:** We released an agent skill to help you install and migrate to Jetpack Navigation 3. Try out the skill from the [Android skills repository](https://github.com/android/skills). - -
- - -## AI Prompt - -### Migrate from Navigation 2 to Navigation 3 - -This prompt will use this guide to migrate to navigation 3. - - Migrate from Navigation 2 to Navigation 3 using the official - migration guide. - -### Using AI prompts - -AI prompts are intended to be used within Gemini in Android Studio. - -Learn more about Gemini in Studio here: [https://developer.android.com/studio/gemini/overview](https://developer.android.com/studio/gemini/overview) - - -
- -If you run into problems [file an issue here](https://issuetracker.google.com/issues/new?component=1750212&template=2102223&title=%5BMigration%5D). - ## Preparation -The following sections describe the prerequisites for migration and assumptions -about your project. They also cover the features that are supported for -migration, and those that aren't. +The following sections describe the prerequisites for migration and assumptions about your project. They also cover the features that are supported for migration, and those that aren't. ### Prerequisites - You must use a `compileSdk` of 36 or later. - You should be familiar with [navigation terminology](https://developer.android.com/guide/navigation). -- Destinations are composable functions. Navigation 3 is designed exclusively for Compose. To use Fragments and Views in Compose, see [Using Views in - Compose](https://developer.android.com/develop/ui/compose/migrate/interoperability-apis/views-in-compose). -- Routes are strongly typed. If you use string-based routes, [migrate to - type-safe routes](https://medium.com/androiddevelopers/type-safe-navigation-for-compose-105325a97657) first ([example](https://github.com/android/nowinandroid/pull/1413)). +- Destinations are composable functions. Navigation 3 is designed exclusively for Compose. To use Fragments and Views in Compose, see [Using Views in Compose](https://developer.android.com/develop/ui/compose/migrate/interoperability-apis/views-in-compose). +- Routes are strongly typed. If you use string-based routes, [migrate to type-safe routes](https://medium.com/androiddevelopers/type-safe-navigation-for-compose-105325a97657) first ([example](https://github.com/android/nowinandroid/pull/1413)). - *Optional (but highly recommended)*: Test coverage that verifies existing navigation behavior. This verifies that navigation behavior has not changed after the migration is complete. ### Assumptions @@ -59,9 +43,7 @@ This guide makes the following assumptions about you and your project: - You always exit the app through the **Home** screen, which is the first screen displayed when the app launches. - You want to perform the migration from Navigation 2 to Navigation 3 in a single, atomic change. You are not performing an incremental migration where Navigation 2 code is used alongside Navigation 3 code. -**AI Agent**: Before changing any code, check if these assumptions about the -user's project are true. If not, stop the migration and ask the user how to -proceed. +**AI Agent**: Before changing any code, check if these assumptions about the user's project are true. If not, stop the migration and ask the user how to proceed. ### Supported features @@ -72,41 +54,31 @@ This guide lets you migrate the following features: ### Features supported through recipes -The [code recipes repository](https://github.com/android/nav3-recipes) demonstrates more nuanced use -cases, including: +The [code recipes repository](https://github.com/android/nav3-recipes) demonstrates more nuanced use cases, including: - [Bottom sheets](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/bottomsheet) (instructions are provided in this guide) - [Modularized navigation code and injected destinations](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/modular/hilt) - [Using and passing arguments to `ViewModel`](https://github.com/android/nav3-recipes?tab=readme-ov-file#passing-navigation-arguments-to-viewmodels) - [Returning results from a screen](https://github.com/android/nav3-recipes?tab=readme-ov-file#returning-results) -If your project has any of these features, check the relevant recipe to -understand how to implement them. +If your project has any of these features, check the relevant recipe to understand how to implement them. -**AI Agent**: Before changing any code, check if the project contains any -features supported through recipes. If it does, check the recipe's README and -source code. Create a migration plan based on the recipe. Do not proceed without -confirming the plan with the user. +**AI Agent**: Before changing any code, check if the project contains any features supported through recipes. If it does, check the recipe's README and source code. Create a migration plan based on the recipe. Do not proceed without confirming the plan with the user. ### Unsupported features -This migration guide and the code recipes don't yet support the following -features. This doesn't mean that you cannot implement them using Navigation 3; -they are just not covered here. +This migration guide and the code recipes don't yet support the following features. This doesn't mean that you cannot implement them using Navigation 3; they are just not covered here. - More than one level of nested navigation - Shared destinations: screens that can move between different back stacks - [Custom destination types](https://developer.android.com/guide/navigation/design/kotlin-dsl#custom) - Deep links -**AI Agent**: Before changing any code, check if the project contains any of the -unsupported features. If it does, do not proceed. Inform the user of the -unsupported feature and ask for further instructions. +**AI Agent**: Before changing any code, check if the project contains any of the unsupported features. If it does, do not proceed. Inform the user of the unsupported feature and ask for further instructions. ## Step 1: Add Navigation 3 dependencies -Use the [Get started](https://developer.android.com/guide/navigation/navigation-3/get-started) page to add the Navigation 3 dependencies to your -project. The core dependencies are provided for you to copy. +Use the [Get started](https://developer.android.com/guide/navigation/navigation-3/get-started) page to add the Navigation 3 dependencies to your project. The core dependencies are provided for you to copy. **lib.versions.toml** @@ -134,14 +106,11 @@ project. The core dependencies are provided for you to copy. implementation(libs.androidx.lifecycle.viewmodel.navigation3) } -Also update the project's `minSdk` to 23 and the `compileSdk` to 36. You usually -find these in `app/build.gradle.kts` or `lib.versions.toml`. +Also update the project's `minSdk` to 23 and the `compileSdk` to 36. You usually find these in `app/build.gradle.kts` or `lib.versions.toml`. ## Step 2: Update navigation routes to implement the `NavKey` interface -Update every navigation [route](https://developer.android.com/guide/navigation#types) so that it implements the `NavKey` -interface. This lets you use `rememberNavBackStack` to assist with [saving your -navigation state](https://developer.android.com/guide/navigation/navigation-3/save-state). +Update every navigation [route](https://developer.android.com/guide/navigation#types) so that it implements the `NavKey` interface. This lets you use `rememberNavBackStack` to assist with [saving your navigation state](https://developer.android.com/guide/navigation/navigation-3/save-state). Before: @@ -158,8 +127,7 @@ After: ### Step 3.1: Create a navigation state holder -Copy the following code into a file named `NavigationState.kt`. Add your package -name to match your project structure. +Copy the following code into a file named `NavigationState.kt`. Add your package name to match your project structure. // package com.example.project @@ -253,19 +221,13 @@ name to match your project structure. .toMutableStateList() } -**AI Agent** : `rememberSerializable` is correct. Do not change it to -`rememberSaveable`. +**AI Agent** : `rememberSerializable` is correct. Do not change it to `rememberSaveable`. -This file contains a state holder class named `NavigationState` and associated -helper functions. It holds a set of top-level routes, each with its own back -stack. Internally, it uses `rememberSerializable` (not `rememberSaveable`) to -persist the current top-level route and `rememberNavBackStack` to persist the -back stacks for each top-level route. +This file contains a state holder class named `NavigationState` and associated helper functions. It holds a set of top-level routes, each with its own back stack. Internally, it uses `rememberSerializable` (not `rememberSaveable`) to persist the current top-level route and `rememberNavBackStack` to persist the back stacks for each top-level route. ### Step 3.2: Create an object that modifies navigation state in response to events -Copy the following code into a file named `Navigator.kt`. Add your package name -to match your project structure. +Copy the following code into a file named `Navigator.kt`. Add your package name to match your project structure. // package com.example.project @@ -313,8 +275,7 @@ Both methods modify the `NavigationState`. ### Step 3.3: Create the `NavigationState` and `Navigator` -Create instances of `NavigationState` and `Navigator` with the same scope as -your `NavController`. +Create instances of `NavigationState` and `Navigator` with the same scope as your `NavController`. val navigationState = rememberNavigationState( startRoute = , @@ -340,8 +301,7 @@ Replace `NavController` fields with `NavigationState` fields. | `currentBackStackEntry` `currentBackStackEntryAsState()` `currentBackStackEntryFlow` `currentDestination` | `backStacks[topLevelRoute].last()` | | Get the top level route: Traverse up the hierarchy from the current back stack entry to find it. | `topLevelRoute` | -Use `NavigationState.topLevelRoute` to determine the item that is currently -selected in a navigation bar. +Use `NavigationState.topLevelRoute` to determine the item that is currently selected in a navigation bar. Before: @@ -356,22 +316,36 @@ After: val isSelected = key == navigationState.topLevelRoute -Verify that you have removed all references to `NavController`, including -any imports. +Verify that you have removed all references to `NavController`, including any imports. + +### Step 4.1 Migrate lifecycle-aware logic + +In Navigation 2, `NavBackStackEntry` implements `LifecycleOwner`, letting you listen to lifecycle events or collect flows in a lifecycle-aware manner using `navController.currentBackStackEntry`. + +In Navigation 3, `NavDisplay` provides an entry-scoped `LifecycleOwner` through `LocalLifecycleOwner.current` to each destination's composable content. See [Destination lifecycle](https://developer.android.com/guide/navigation/navigation-3/basics#destination-lifecycle) for more information. + +You should perform lifecycle-aware operations directly inside your destination's composable content by referencing `LocalLifecycleOwner.current`. + +For example, if you collect a flow in a lifecycle-aware manner using the back stack entry: + +Before: + + // In your destination screen or host + val lifecycleOwner = navController.currentBackStackEntry + val state by flow.collectAsStateWithLifecycle(lifecycleOwner = lifecycleOwner) + +After: + + // Inside the destination composable + val state by flow.collectAsStateWithLifecycle() ## Step 5: Move your destinations from `NavHost`'s `NavGraph` into an `entryProvider` -In Navigation 2, you [define your destinations](https://developer.android.com/guide/navigation/design#compose) -using the [NavGraphBuilder DSL](https://developer.android.com/guide/navigation/design/kotlin-dsl#navgraphbuilder), -usually inside `NavHost`'s trailing lambda. It is common to use extension -functions here as described in [Encapsulate your navigation code](https://developer.android.com/guide/navigation/design/encapsulate). +In Navigation 2, you [define your destinations](https://developer.android.com/guide/navigation/design#compose) using the [NavGraphBuilder DSL](https://developer.android.com/guide/navigation/design/kotlin-dsl#navgraphbuilder), usually inside `NavHost`'s trailing lambda. It is common to use extension functions here as described in [Encapsulate your navigation code](https://developer.android.com/guide/navigation/design/encapsulate). -In Navigation 3, you define your destinations using an `entryProvider`. This -`entryProvider` resolves a route to a [`NavEntry`](https://developer.android.com/guide/navigation/navigation-3/basics#resolve-keys). Importantly, the -`entryProvider` does not define parent-child relationships between entries. +In Navigation 3, you define your destinations using an `entryProvider`. This `entryProvider` resolves a route to a [`NavEntry`](https://developer.android.com/guide/navigation/navigation-3/basics#resolve-keys). Importantly, the `entryProvider` does not define parent-child relationships between entries. -In this migration guide, parent-child relationships are modelled -as follows: +In this migration guide, parent-child relationships are modelled as follows: - `NavigationState` has a set of top-level routes (the parent routes) and a stack for each one. It keeps track of the current top-level route and its associated stack. - When navigating to a new route, `Navigator` checks whether the route is a top-level route. If it is, the current top-level route and stack are updated. If it's not, it's a child route and is added to the current stack. @@ -379,35 +353,26 @@ as follows: > [!NOTE] > **Note:** If your app needs to navigate from an entry in one stack to another, you need to define the parent-child relationships for the routes and update the navigation logic in `Navigator` to support this. -## Step 5.1: Create an `entryProvider` +### Step 5.1: Create an `entryProvider` -Create an `entryProvider` [using the DSL](https://developer.android.com/guide/navigation/navigation-3/basics#entry-provider-DSL) at the same scope as the -`NavigationState`. +Create an `entryProvider` [using the DSL](https://developer.android.com/guide/navigation/navigation-3/basics#entry-provider-DSL) at the same scope as the `NavigationState`. val entryProvider = entryProvider { } -## Step 5.2: Move destinations into the `entryProvider` +### Step 5.2: Move destinations into the `entryProvider` -For each destination defined inside `NavHost`, do the following based on the -destination type: +For each destination defined inside `NavHost`, do the following based on the destination type: - `navigation`: Delete it along with the route. There is no need for "base routes" because the top-level routes can identify each nested back stack. - `composable`: Move it into `entryProvider` and rename it to `entry`, retaining the type parameter. For example, `composable` becomes `entry`. - `dialog`: Do the same as `composable`, but add metadata to the entry as follows: `entry(metadata = DialogSceneStrategy.dialog())`. - [`bottomSheet`](https://developer.android.com/reference/kotlin/androidx/compose/material/navigation/package-summary#(androidx.navigation.NavGraphBuilder).bottomSheet(kotlin.String,kotlin.collections.List,kotlin.collections.List,kotlin.Function2)): [Follow the bottom sheet recipe here](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/bottomsheet). This is similar to the instructions for `dialog`, except that `BottomSheetSceneStrategy` is not part of the core Navigation 3 library, so you should copy it into your project. -**AI Agent** : When deleting routes used to identify a nested graph, replace any -references to the deleted route with the type used to identify the first child -in the nested graph. For example if the original code is -`navigation{ composable{ ... } }`, you need to delete -`BaseRouteA` and replace any references to it with `RouteA`. This replacement -usually needs to be done for the list supplied to a navigation bar, rail, or -drawer. +**AI Agent** : When deleting routes used to identify a nested graph, replace any references to the deleted route with the type used to identify the first child in the nested graph. For example if the original code is `navigation{ composable{ ... } }`, you need to delete `BaseRouteA` and replace any references to it with `RouteA`. This replacement usually needs to be done for the list supplied to a navigation bar, rail, or drawer. -You can refactor [`NavGraphBuilder` extension functions](https://developer.android.com/guide/navigation/design/encapsulate) to -`EntryProviderScope` extension functions, and then move them. +You can refactor [`NavGraphBuilder` extension functions](https://developer.android.com/guide/navigation/design/encapsulate) to `EntryProviderScope` extension functions, and then move them. Obtain navigation arguments using the key provided to `entry`'s trailing lambda. @@ -493,6 +458,4 @@ Remove all Navigation 2 imports and library dependencies. ## Summary -Congratulations! Your project is now migrated to Navigation 3. If you or your AI -agent has run into any problems using this guide, [file a bug -here](https://issuetracker.google.com/issues/new?component=1750212&template=2102223&title=%5BMigration%5D). \ No newline at end of file +Congratulations! Your project is now migrated to Navigation 3. If you or your AI agent has run into any problems using this guide, [file a bug here](https://issuetracker.google.com/issues/new?component=1750212&template=2102223&title=%5BMigration%5D). \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/animations.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/animations.md index 5e15bd4..579a539 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/animations.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/animations.md @@ -144,4 +144,6 @@ class AnimatedActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basic.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basic.md index 087d5cf..4ab55aa 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basic.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basic.md @@ -86,4 +86,6 @@ class BasicActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basicdsl.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basicdsl.md index 2067c08..461afd7 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basicdsl.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basicdsl.md @@ -82,4 +82,6 @@ class BasicDslActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basicsaveable.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basicsaveable.md index fd2a72d..4575a71 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basicsaveable.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/basicsaveable.md @@ -87,4 +87,6 @@ class BasicSaveableActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/bottomsheet.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/bottomsheet.md index aa6b456..1ae419a 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/bottomsheet.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/bottomsheet.md @@ -102,6 +102,8 @@ class BottomSheetActivity : ComponentActivity() { } } } + + ``` ``` @@ -192,4 +194,5 @@ class BottomSheetSceneStrategy : SceneStrategy { } } + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/common-ui.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/common-ui.md index d49b399..da4f696 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/common-ui.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/common-ui.md @@ -197,4 +197,6 @@ class TopLevelBackStack(startKey: T) { } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/conditional-transitions.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/conditional-transitions.md new file mode 100644 index 0000000..497f208 --- /dev/null +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/conditional-transitions.md @@ -0,0 +1,184 @@ +# Conditional Transitions Recipe + +This recipe demonstrates how to create route-dependent screen transitions in Navigation 3 using `transitionSpec` and `popTransitionSpec`. The slide directions (right, left, bottom, top) are conditionally selected based on pairs of `initialState` and `targetState` navigation keys. + +## How it works + +- **Route Definitions** : Navigation destinations (`Step1`, `Step2`, `Step3`, `Step4`) are defined using a sealed class hierarchy implementing `NavKey` and marked with `@Serializable`. +- **Conditional Forward Transitions (`transitionSpec`)** : Matches pairs of `(initialKey to targetKey)` to determine the direction of the slide animation: + - `Step1` $\\rightarrow$ `Step2`: Swipes to the left + - `Step2` $\\rightarrow$ `Step3`: Swipes to the up + - `Step3` $\\rightarrow$ `Step4`: Swipes to the right + - `Step4` $\\rightarrow$ `Step1`: Slides to the bottom (restarts flow) +- **Conditional Pop Transitions (`popTransitionSpec`)**: Handles reverse slide directions when navigating back or when clearing the backstack. +- **Backstack Control** : Demonstrates clearing the navigation stack on the final step (`backStack.clear()` \& `backStack.add(Step1)`) while executing a seamless top-slide transition. + +[![](https://developer.android.com/static/images/picto-icons/code.svg) Explore View the full recipe on GitHub.](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/conditionaltransitions) + +``` +package com.example.nav3recipes.conditionaltransitions + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.animation.ContentTransform +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutHorizontally +import androidx.compose.animation.slideOutVertically +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.ElevatedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberNavBackStack +import androidx.navigation3.ui.NavDisplay +import com.example.nav3recipes.content.ContentGreen +import com.example.nav3recipes.content.ContentOrange +import com.example.nav3recipes.content.ContentPurple +import com.example.nav3recipes.content.ContentRed +import com.example.nav3recipes.sharedviewmodel.toContentKey +import com.example.nav3recipes.ui.setEdgeToEdgeConfig +import dagger.hilt.android.AndroidEntryPoint +import kotlinx.serialization.Serializable + +@Serializable +sealed class Step(val firstButtonTitle: String, val secondButtonTitle: String) : NavKey + +@Serializable +data object Step1 : Step("Home", "Swipe left") + +@Serializable +data object Step2 : Step("Swipe right", "Swipe up") + +@Serializable +data object Step3 : Step("Swipe down", "Swipe right") + +@Serializable +data object Step4 : Step("Swipe left", "Swipe down") + +@AndroidEntryPoint +class ConditionalTransitionsActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setEdgeToEdgeConfig() + + setContent { + Scaffold { paddingValues -> + val backStack = rememberNavBackStack(Step1) + + NavDisplay( + backStack = backStack, + modifier = Modifier.padding(paddingValues), + onBack = backStack::removeLastOrNull, + entryProvider = entryProvider { + entry { + ContentGreen(title = "Screen 1") { + StepContent( + step = it, + onNext = { backStack += Step2 }, + onBack = ::finish, // closing the activity + ) + } + + } + entry { + ContentRed(title = "Screen 2") { + StepContent( + step = it, + onNext = { backStack += Step3 }, + onBack = backStack::removeLastOrNull, + ) + } + } + entry { + ContentOrange(title = "Screen 3") { + StepContent( + step = it, + onNext = { backStack += Step4 }, + onBack = backStack::removeLastOrNull, + ) + } + } + entry { + ContentPurple(title = "Screen 4") { + StepContent( + step = it, + onNext = { + backStack.clear() + backStack.add(Step1) + }, + onBack = backStack::removeLastOrNull, + ) + } + } + }, + transitionSpec = { + val initialKey = initialState.entries.lastOrNull()?.contentKey + val targetKey = targetState.entries.lastOrNull()?.contentKey + + when (initialKey to targetKey) { + Step1.toContentKey() to Step2.toContentKey() -> swipeLeft() + Step2.toContentKey() to Step3.toContentKey() -> swipeUp() + Step3.toContentKey() to Step4.toContentKey() -> swipeRight() + Step4.toContentKey() to Step1.toContentKey() -> swipeDown() + else -> swipeRight() + } + }, + popTransitionSpec = { + val initialKey = initialState.entries.lastOrNull()?.contentKey + val targetKey = targetState.entries.lastOrNull()?.contentKey + + when (initialKey to targetKey) { + Step4.toContentKey() to Step1.toContentKey() -> swipeDown() // via backstack clearing + Step2.toContentKey() to Step1.toContentKey() -> swipeRight() + Step3.toContentKey() to Step2.toContentKey() -> swipeDown() + Step4.toContentKey() to Step3.toContentKey() -> swipeLeft() + else -> swipeLeft() + } + }, + ) + } + } + } +} + +@Composable +fun StepContent(step: Step, onNext: () -> Unit, onBack: () -> Unit) { + Column( + verticalArrangement = Arrangement.SpaceEvenly, + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.fillMaxSize() + ) { + Row(horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxWidth()) { + ElevatedButton(onBack) { Text(text = step.firstButtonTitle) } + ElevatedButton(onNext) { Text(text = step.secondButtonTitle) } + } + } +} + +private fun swipeLeft(): ContentTransform = + slideInHorizontally(initialOffsetX = { it }) togetherWith slideOutHorizontally(targetOffsetX = { -it }) + +private fun swipeUp(): ContentTransform = + slideInVertically(initialOffsetY = { it }) togetherWith slideOutVertically(targetOffsetY = { -it }) + +private fun swipeRight(): ContentTransform = + slideInHorizontally(initialOffsetX = { -it }) togetherWith slideOutHorizontally(targetOffsetX = { it }) + +private fun swipeDown(): ContentTransform = + slideInVertically(initialOffsetY = { -it }) togetherWith slideOutVertically(targetOffsetY = { it }) + + +``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/conditional.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/conditional.md index 60848b3..0bd6bca 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/conditional.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/conditional.md @@ -176,6 +176,7 @@ fun rememberNavBackStack(vararg elements: T): NavBackStack { NavBackStack(*elements) } } + ``` ``` @@ -227,4 +228,5 @@ class Navigator( fun goBack() = backStack.removeLastOrNull() } + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-basic.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-basic.md deleted file mode 100644 index 66312de..0000000 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-basic.md +++ /dev/null @@ -1,744 +0,0 @@ -# Deep Link Basic Recipe - -This recipe demonstrates how to parse a deep link URL from an Android Intent into a Navigation key. - -## How it works - -It consists of two activities - `CreateDeepLinkActivity` to construct and trigger the deeplink request, and the `MainActivity` to show how an app can handle that request. - -## Demonstrated forms of deeplink - -The `MainActivity` has several backStack keys to demonstrate different types of supported deeplinks: - -1. `HomeKey` - deeplink with an exact url (no deeplink arguments) -2. `UsersKey` - deeplink with path arguments -3. `SearchKey` - deeplink with query arguments - -See `MainActivity.deepLinkPatterns` for the actual url pattern of each. - -## Recipe structure - -This recipe consists of three main packages: - -1. `basic.deeplink` - Contains the two activities -2. `basic.deeplink.ui` - Contains the activity UI code, i.e. global string variables, deeplink URLs etc -3. `basic.deeplink.util` - Contains the classes and helper methods to parse and match the deeplinks - -[![](https://developer.android.com/static/images/picto-icons/code.svg) Explore View the full recipe on GitHub.](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/deeplink/basic) - -``` -package com.example.nav3recipes.deeplink.basic - -import androidx.navigation3.runtime.NavKey -import com.example.nav3recipes.deeplink.basic.ui.STRING_LITERAL_FILTER -import com.example.nav3recipes.deeplink.basic.ui.STRING_LITERAL_HOME -import com.example.nav3recipes.deeplink.basic.ui.STRING_LITERAL_SEARCH -import com.example.nav3recipes.deeplink.basic.ui.STRING_LITERAL_USERS -import kotlinx.serialization.Serializable - -internal interface NavRecipeKey: NavKey { - val name: String -} - -@Serializable -internal object HomeKey: NavRecipeKey { - override val name: String = STRING_LITERAL_HOME -} - -@Serializable -internal data class UsersKey( - val filter: String, -): NavRecipeKey { - override val name: String = STRING_LITERAL_USERS - companion object { - const val FILTER_KEY = STRING_LITERAL_FILTER - const val FILTER_OPTION_RECENTLY_ADDED = "recentlyAdded" - const val FILTER_OPTION_ALL = "all" - } -} - -@Serializable -internal data class SearchKey( - val firstName: String? = null, - val ageMin: Int? = null, - val ageMax: Int? = null, - val location: String? = null, -): NavRecipeKey { - override val name: String = STRING_LITERAL_SEARCH -} -``` - -``` -package com.example.nav3recipes.deeplink.basic - -import android.net.Uri -import android.os.Bundle -import androidx.activity.ComponentActivity -import androidx.activity.compose.setContent -import androidx.core.net.toUri -import androidx.navigation3.runtime.NavBackStack -import androidx.navigation3.runtime.NavKey -import androidx.navigation3.runtime.entryProvider -import androidx.navigation3.runtime.rememberNavBackStack -import androidx.navigation3.ui.NavDisplay -import com.example.nav3recipes.common.deeplink.EntryScreen -import com.example.nav3recipes.common.deeplink.FriendsList -import com.example.nav3recipes.common.deeplink.LIST_USERS -import com.example.nav3recipes.common.deeplink.TextContent -import com.example.nav3recipes.deeplink.basic.ui.URL_HOME_EXACT -import com.example.nav3recipes.deeplink.basic.ui.URL_SEARCH -import com.example.nav3recipes.deeplink.basic.ui.URL_USERS_WITH_FILTER -import com.example.nav3recipes.deeplink.basic.util.DeepLinkMatchResult -import com.example.nav3recipes.deeplink.basic.util.DeepLinkMatcher -import com.example.nav3recipes.deeplink.basic.util.DeepLinkPattern -import com.example.nav3recipes.deeplink.basic.util.DeepLinkRequest -import com.example.nav3recipes.deeplink.basic.util.KeyDecoder -import com.example.nav3recipes.ui.setEdgeToEdgeConfig - -/** - * Parses a target deeplink into a NavKey. There are several crucial steps involved: - * - * STEP 1.Parse supported deeplinks (URLs that can be deeplinked into) into a readily readable - * format (see [DeepLinkPattern]) - * STEP 2. Parse the requested deeplink into a readily readable, format (see [DeepLinkRequest]) - * **note** the parsed requested deeplink and parsed supported deeplinks should be cohesive with each - * other to facilitate comparison and finding a match - * STEP 3. Compare the requested deeplink target with supported deeplinks in order to find a match - * (see [DeepLinkMatchResult]). The match result's format should enable conversion from result - * to backstack key, regardless of what the conversion method may be. - * STEP 4. Associate the match results with the correct backstack key - * - * This recipes provides an example for each of the above steps by way of kotlinx.serialization. - * - * **This recipe is designed to focus on parsing an intent into a key, and therefore these additional - * deeplink considerations are not included in this scope** - * - Create synthetic backStack - * - Multi-modular setup - * - DI - * - Managing TaskStack - * - Up button ves Back Button - * - */ -class MainActivity : ComponentActivity() { - /** STEP 1. Parse supported deeplinks */ - // internal so that landing activity can link to this in the kdocs - internal val deepLinkPatterns: List> = listOf( - // "https://www.nav3recipes.com/home" - DeepLinkPattern(HomeKey.serializer(), (URL_HOME_EXACT).toUri()), - // "https://www.nav3recipes.com/users/with/{filter}" - DeepLinkPattern(UsersKey.serializer(), (URL_USERS_WITH_FILTER).toUri()), - // "https://www.nav3recipes.com/users/search?{firstName}&{age}&{location}" - DeepLinkPattern(SearchKey.serializer(), (URL_SEARCH.toUri())), - ) - - override fun onCreate(savedInstanceState: Bundle?) { - setEdgeToEdgeConfig() - super.onCreate(savedInstanceState) - - // retrieve the target Uri - val uri: Uri? = intent.data - // associate the target with the correct backstack key - val key: NavKey = uri?.let { - /** STEP 2. Parse requested deeplink */ - val request = DeepLinkRequest(uri) - /** STEP 3. Compared requested with supported deeplink to find match*/ - val match = deepLinkPatterns.firstNotNullOfOrNull { pattern -> - DeepLinkMatcher(request, pattern).match() - } - /** STEP 4. If match is found, associate match to the correct key*/ - match?.let { - //leverage kotlinx.serialization's Decoder to decode - // match result into a backstack key - KeyDecoder(match.args) - .decodeSerializableValue(match.serializer) - } - } ?: HomeKey // fallback if intent.uri is null or match is not found - - /** - * Then pass starting key to backstack - */ - setContent { - val backStack: NavBackStack = rememberNavBackStack(key) - NavDisplay( - backStack = backStack, - onBack = { backStack.removeLastOrNull() }, - entryProvider = entryProvider { - entry { key -> - EntryScreen(key.name) { - TextContent("") - } - } - entry { key -> - EntryScreen("${key.name} : ${key.filter}") { - TextContent("") - val list = when { - key.filter.isEmpty() -> LIST_USERS - key.filter == UsersKey.FILTER_OPTION_ALL -> LIST_USERS - else -> LIST_USERS.take(5) - } - FriendsList(list) - } - } - entry { search -> - EntryScreen(search.name) { - TextContent("") - val matchingUsers = LIST_USERS.filter { user -> - (search.firstName == null || user.firstName == search.firstName) && - (search.location == null || user.location == search.location) && - (search.ageMin == null || user.age >= search.ageMin) && - (search.ageMax == null || user.age <= search.ageMax) - } - FriendsList(matchingUsers) - } - } - } - ) - } - } -} -``` - -``` -package com.example.nav3recipes.deeplink.basic - -import android.content.Intent -import android.os.Bundle -import androidx.activity.ComponentActivity -import androidx.activity.compose.setContent -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateMapOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.core.net.toUri -import androidx.lifecycle.compose.dropUnlessResumed -import com.example.nav3recipes.common.deeplink.EMPTY -import com.example.nav3recipes.common.deeplink.EntryScreen -import com.example.nav3recipes.common.deeplink.FIRST_NAME_JOHN -import com.example.nav3recipes.common.deeplink.FIRST_NAME_JULIE -import com.example.nav3recipes.common.deeplink.FIRST_NAME_MARY -import com.example.nav3recipes.common.deeplink.FIRST_NAME_TOM -import com.example.nav3recipes.common.deeplink.LOCATION_BC -import com.example.nav3recipes.common.deeplink.LOCATION_BR -import com.example.nav3recipes.common.deeplink.LOCATION_CA -import com.example.nav3recipes.common.deeplink.LOCATION_US -import com.example.nav3recipes.common.deeplink.MenuDropDown -import com.example.nav3recipes.common.deeplink.MenuTextInput -import com.example.nav3recipes.common.deeplink.PaddedButton -import com.example.nav3recipes.common.deeplink.TextContent -import com.example.nav3recipes.deeplink.basic.ui.PATH_BASE -import com.example.nav3recipes.deeplink.basic.ui.PATH_INCLUDE -import com.example.nav3recipes.deeplink.basic.ui.PATH_SEARCH -import com.example.nav3recipes.deeplink.basic.ui.STRING_LITERAL_HOME -import com.example.nav3recipes.ui.setEdgeToEdgeConfig - -/** - * This activity allows the user to create a deep link and make a request with it. - * - * **HOW THIS RECIPE WORKS** it consists of two activities - [CreateDeepLinkActivity] to construct - * and trigger the deeplink request, and the [MainActivity] to show how an app can handle - * that request. - * - * **DEMONSTRATED FORMS OF DEEPLINK** The [MainActivity] has a several backStack keys to - * demonstrate different types of supported deeplinks: - * 1. [HomeKey] - deeplink with an exact url (no deeplink arguments) - * 2. [UsersKey] - deeplink with path arguments - * 3. [SearchKey] - deeplink with query arguments - * See [MainActivity.deepLinkPatterns] for the actual url pattern of each. - * - * **RECIPE STRUCTURE** This recipe consists of three main packages: - * 1. basic.deeplink - Contains the two activities - * 2. basic.deeplink.ui - Contains the activity UI code, i.e. global string variables, deeplink URLs etc - * 3. basic.deeplink.util - Contains the classes and helper methods to parse and match - * the deeplinks - * - * See [MainActivity] for how the requested deeplink is handled. - */ -class CreateDeepLinkActivity : ComponentActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - setEdgeToEdgeConfig() - super.onCreate(savedInstanceState) - - setContent { - /** - * UI for deeplink sandbox - */ - EntryScreen("Sandbox - Build Your Deeplink") { - TextContent("Base url:\n${PATH_BASE}/") - var showFilterOptions by remember { mutableStateOf(false) } - val selectedPath = remember { mutableStateOf(MENU_OPTIONS_PATH[KEY_PATH]?.first()) } - - var showQueryOptions by remember { mutableStateOf(false) } - var selectedFilter by remember { mutableStateOf("") } - val selectedSearchQuery = remember { mutableStateMapOf() } - - // manage path options - MenuDropDown( - menuOptions = MENU_OPTIONS_PATH, - ) { _, selection -> - selectedPath.value = selection - when (selection) { - PATH_SEARCH -> { - showQueryOptions = true - showFilterOptions = false - } - - PATH_INCLUDE -> { - showQueryOptions = false - showFilterOptions = true - } - - else -> { - showQueryOptions = false - showFilterOptions = false - } - } - } - - // manage path filter options, reset state if menu is closed - LaunchedEffect(showFilterOptions) { - selectedFilter = if (showFilterOptions) { - MENU_OPTIONS_FILTER.values.first().first() - } else { - "" - } - } - if (showFilterOptions) { - MenuDropDown( - menuOptions = MENU_OPTIONS_FILTER, - ) { _, selected -> - selectedFilter = selected - } - } - - // manage query options, reset state if menu is closed - LaunchedEffect(showQueryOptions) { - if (showQueryOptions) { - val initEntry = MENU_OPTIONS_SEARCH.entries.first() - selectedSearchQuery[initEntry.key] = initEntry.value.first() - } else { - selectedSearchQuery.clear() - } - } - if (showQueryOptions) { - MenuTextInput( - menuLabels = MENU_LABELS_SEARCH, - ) { label, selected -> - selectedSearchQuery[label] = selected - } - MenuDropDown( - menuOptions = MENU_OPTIONS_SEARCH, - ) { label, selected -> - selectedSearchQuery[label] = selected - } - } - - // form final deeplink url - val arguments = when (selectedPath.value) { - PATH_INCLUDE -> "/${selectedFilter}" - PATH_SEARCH -> { - buildString { - selectedSearchQuery.forEach { entry -> - if (entry.value.isNotEmpty()) { - val prefix = if (isEmpty()) "?" else "&" - append("$prefix${entry.key}=${entry.value}") - } - } - } - } - - else -> "" - } - val finalUrl = "${PATH_BASE}/${selectedPath.value}$arguments" - TextContent("Final url:\n$finalUrl") - // deeplink to target - PaddedButton("Deeplink Away!", onClick = dropUnlessResumed { - val intent = Intent( - this@CreateDeepLinkActivity, - MainActivity::class.java - ) - // start activity with the url - intent.data = finalUrl.toUri() - startActivity(intent) - }) - } - } - } -} - -private const val KEY_PATH = "path" -private val MENU_OPTIONS_PATH = mapOf( - KEY_PATH to listOf( - STRING_LITERAL_HOME, - PATH_INCLUDE, - PATH_SEARCH, - ), -) - -private val MENU_OPTIONS_FILTER = mapOf( - UsersKey.FILTER_KEY to listOf(UsersKey.FILTER_OPTION_RECENTLY_ADDED, UsersKey.FILTER_OPTION_ALL), -) - -private val MENU_OPTIONS_SEARCH = mapOf( - SearchKey::firstName.name to listOf( - EMPTY, - FIRST_NAME_JOHN, - FIRST_NAME_TOM, - FIRST_NAME_MARY, - FIRST_NAME_JULIE - ), - SearchKey::location.name to listOf(EMPTY, LOCATION_CA, LOCATION_BC, LOCATION_BR, LOCATION_US) -) - -private val MENU_LABELS_SEARCH = listOf(SearchKey::ageMin.name, SearchKey::ageMax.name) - -``` - -``` -package com.example.nav3recipes.deeplink.basic.util - -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.descriptors.SerialDescriptor -import kotlinx.serialization.encoding.AbstractDecoder -import kotlinx.serialization.encoding.CompositeDecoder -import kotlinx.serialization.modules.EmptySerializersModule -import kotlinx.serialization.modules.SerializersModule - -/** - * Decodes the list of arguments into a a back stack key - * - * **IMPORTANT** This decoder assumes that all argument types are Primitives. - */ -@OptIn(ExperimentalSerializationApi::class) -internal class KeyDecoder( - private val arguments: Map, -) : AbstractDecoder() { - - override val serializersModule: SerializersModule = EmptySerializersModule() - private var elementIndex: Int = -1 - private var elementName: String = "" - - /** - * Decodes the index of the next element to be decoded. Index represents a position of the - * current element in the [descriptor] that can be found with [descriptor].getElementIndex. - * - * The returned index will trigger deserializer to call [decodeValue] on the argument at that - * index. - * - * The decoder continually calls this method to process the next available argument until this - * method returns [CompositeDecoder.DECODE_DONE], which indicates that there are no more - * arguments to decode. - * - * This method should sequentially return the element index for every element that has its value - * available within [arguments]. - */ - override fun decodeElementIndex(descriptor: SerialDescriptor): Int { - var currentIndex = elementIndex - while (true) { - // proceed to next element - currentIndex++ - // if we have reached the end, let decoder know there are not more arguments to decode - if (currentIndex >= descriptor.elementsCount) return CompositeDecoder.DECODE_DONE - val currentName = descriptor.getElementName(currentIndex) - // Check if bundle has argument value. If so, we tell decoder to process - // currentIndex. Otherwise, we skip this index and proceed to next index. - if (arguments.contains(currentName)) { - elementIndex = currentIndex - elementName = currentName - return elementIndex - } - } - } - - /** - * Returns argument value from the [arguments] for the argument at the index returned by - * [decodeElementIndex] - */ - override fun decodeValue(): Any { - val arg = arguments[elementName] - checkNotNull(arg) { "Unexpected null value for non-nullable argument $elementName" } - return arg - } - - override fun decodeNull(): Nothing? = null - - // we want to know if it is not null, so its !isNull - override fun decodeNotNullMark(): Boolean = arguments[elementName] != null -} -``` - -``` -package com.example.nav3recipes.deeplink.basic.util - -import android.net.Uri - -/** - * Parse the requested Uri and store it in a easily readable format - * - * @param uri the target deeplink uri to link to - */ -internal class DeepLinkRequest( - val uri: Uri -) { - /** - * A list of path segments - */ - val pathSegments: List = uri.pathSegments - - /** - * A map of query name to query value - */ - val queries = buildMap { - uri.queryParameterNames.forEach { argName -> - this[argName] = uri.getQueryParameter(argName)!! - } - } - - // TODO add parsing for other Uri components, i.e. fragments, mimeType, action -} -``` - -```` -package com.example.nav3recipes.deeplink.basic.util - -import android.net.Uri -import androidx.navigation3.runtime.NavKey -import kotlinx.serialization.KSerializer -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialKind -import kotlinx.serialization.encoding.CompositeDecoder -import java.io.Serializable - -/** - * Parse a supported deeplink and stores its metadata as a easily readable format - * - * The following notes applies specifically to this particular sample implementation: - * - * The supported deeplink is expected to be built from a serializable backstack key [T] that - * supports deeplink. This means that if this deeplink contains any arguments (path or query), - * the argument name must match any of [T] member field name. - * - * One [DeepLinkPattern] should be created for each supported deeplink. This means if [T] - * supports two deeplink patterns: - * ``` - * val deeplink1 = www.nav3recipes.com/home - * val deeplink2 = www.nav3recipes.com/profile/{userId} - * ``` - * Then two [DeepLinkPattern] should be created - * ``` - * val parsedDeeplink1 = DeepLinkPattern(T.serializer(), deeplink1) - * val parsedDeeplink2 = DeepLinkPattern(T.serializer(), deeplink2) - * ``` - * - * This implementation assumes a few things: - * 1. all path arguments are required/non-nullable - partial path matches will be considered a non-match - * 2. all query arguments are optional by way of nullable/has default value - * - * @param T the backstack key type that supports the deeplinking of [uriPattern] - * @param serializer the serializer of [T] - * @param uriPattern the supported deeplink's uri pattern, i.e. "abc.com/home/{pathArg}" - */ -internal class DeepLinkPattern( - val serializer: KSerializer, - val uriPattern: Uri -) { - /** - * Help differentiate if a path segment is an argument or a static value - */ - private val regexPatternFillIn = Regex("\\{(.+?)\\}") - - // TODO make these lazy - /** - * parse the path into a list of [PathSegment] - * - * order matters here - path segments need to match in value and order when matching - * requested deeplink to supported deeplink - */ - val pathSegments: List = buildList { - uriPattern.pathSegments.forEach { segment -> - // first, check if it is a path arg - var result = regexPatternFillIn.find(segment) - if (result != null) { - // if so, extract the path arg name (the string value within the curly braces) - val argName = result.groups[1]!!.value - // from [T], read the primitive type of this argument to get the correct type parser - val elementIndex = serializer.descriptor.getElementIndex(argName) - if (elementIndex == CompositeDecoder.UNKNOWN_NAME) { - throw IllegalArgumentException( - "Path parameter '{$argName}' defined in the DeepLink $uriPattern does not exist in the Serializable class '${serializer.descriptor.serialName}'." - ) - } - - val elementDescriptor = serializer.descriptor.getElementDescriptor(elementIndex) - // finally, add the arg name and its respective type parser to the map - add(PathSegment(argName, true, getTypeParser(elementDescriptor.kind))) - } else { - // if its not a path arg, then its just a static string path segment - add(PathSegment(segment, false, getTypeParser(PrimitiveKind.STRING))) - } - } - } - - /** - * Parse supported queries into a map of queryParameterNames to [TypeParser] - * - * This will be used later on to parse a provided query value into the correct KType - */ - val queryValueParsers: Map = buildMap { - uriPattern.queryParameterNames.forEach { paramName -> - val elementIndex = serializer.descriptor.getElementIndex(paramName) - // Ignore static query parameters that are not in the Serializable class - if (elementIndex != CompositeDecoder.UNKNOWN_NAME) { - val elementDescriptor = serializer.descriptor.getElementDescriptor(elementIndex) - this[paramName] = getTypeParser(elementDescriptor.kind) - } - } - } - - /** - * Metadata about a supported path segment - */ - class PathSegment( - val stringValue: String, - val isParamArg: Boolean, - val typeParser: TypeParser - ) -} - -/** - * Parses a String into a Serializable Primitive - */ -private typealias TypeParser = (String) -> Serializable - -private fun getTypeParser(kind: SerialKind): TypeParser { - return when (kind) { - PrimitiveKind.STRING -> Any::toString - PrimitiveKind.INT -> String::toInt - PrimitiveKind.BOOLEAN -> String::toBoolean - PrimitiveKind.BYTE -> String::toByte - PrimitiveKind.CHAR -> String::toCharArray - PrimitiveKind.DOUBLE -> String::toDouble - PrimitiveKind.FLOAT -> String::toFloat - PrimitiveKind.LONG -> String::toLong - PrimitiveKind.SHORT -> String::toShort - else -> throw IllegalArgumentException( - "Unsupported argument type of SerialKind:$kind. The argument type must be a Primitive." - ) - } -} -```` - -``` -package com.example.nav3recipes.deeplink.basic.util - -import android.util.Log -import androidx.navigation3.runtime.NavKey -import kotlinx.serialization.KSerializer - -internal class DeepLinkMatcher( - val request: DeepLinkRequest, - val deepLinkPattern: DeepLinkPattern -) { - /** - * Match a [DeepLinkRequest] to a [DeepLinkPattern]. - * - * Returns a [DeepLinkMatchResult] if this matches the pattern, returns null otherwise - */ - fun match(): DeepLinkMatchResult? { - if (request.uri.scheme != deepLinkPattern.uriPattern.scheme) return null - if (!request.uri.authority.equals(deepLinkPattern.uriPattern.authority, ignoreCase = true)) return null - if (request.pathSegments.size != deepLinkPattern.pathSegments.size) return null - // exact match (url does not contain any arguments) - if (request.uri == deepLinkPattern.uriPattern) - return DeepLinkMatchResult(deepLinkPattern.serializer, mapOf()) - - val args = mutableMapOf() - // match the path - request.pathSegments - .asSequence() - // zip to compare the two objects side by side, order matters here so we - // need to make sure the compared segments are at the same position within the url - .zip(deepLinkPattern.pathSegments.asSequence()) - .forEach { it -> - // retrieve the two path segments to compare - val requestedSegment = it.first - val candidateSegment = it.second - // if the potential match expects a path arg for this segment, try to parse the - // requested segment into the expected type - if (candidateSegment.isParamArg) { - val parsedValue = try { - candidateSegment.typeParser.invoke(requestedSegment) - } catch (e: IllegalArgumentException) { - Log.e(TAG_LOG_ERROR, "Failed to parse path value:[$requestedSegment].", e) - return null - } - args[candidateSegment.stringValue] = parsedValue - } else if(requestedSegment != candidateSegment.stringValue){ - // if it's path arg is not the expected type, its not a match - return null - } - } - // match queries (if any) - request.queries.forEach { query -> - val name = query.key - // If the pattern does not define this query parameter, ignore it. - // This prevents a NullPointerException. - val queryStringParser = deepLinkPattern.queryValueParsers[name]?: return@forEach - - val queryParsedValue = try { - queryStringParser.invoke(query.value) - } catch (e: IllegalArgumentException) { - Log.e(TAG_LOG_ERROR, "Failed to parse query name:[$name] value:[${query.value}].", e) - return null - } - args[name] = queryParsedValue - } - // provide the serializer of the matching key and map of arg names to parsed arg values - return DeepLinkMatchResult(deepLinkPattern.serializer, args) - } -} - - -/** - * Created when a requested deeplink matches with a supported deeplink - * - * @param [T] the backstack key associated with the deeplink that matched with the requested deeplink - * @param serializer serializer for [T] - * @param args The map of argument name to argument value. The value is expected to have already - * been parsed from the raw url string back into its proper KType as declared in [T]. - * Includes arguments for all parts of the uri - path, query, etc. - * */ -internal data class DeepLinkMatchResult( - val serializer: KSerializer, - val args: Map -) - -const val TAG_LOG_ERROR = "Nav3RecipesDeepLink" -``` - -``` -package com.example.nav3recipes.deeplink.basic.ui - -import com.example.nav3recipes.deeplink.basic.SearchKey - -/** - * String resources - */ -internal const val STRING_LITERAL_FILTER = "filter" -internal const val STRING_LITERAL_HOME = "home" -internal const val STRING_LITERAL_USERS = "users" -internal const val STRING_LITERAL_SEARCH = "search" -internal const val STRING_LITERAL_INCLUDE = "include" -internal const val PATH_BASE = "https://www.nav3recipes.com" -internal const val PATH_INCLUDE = "$STRING_LITERAL_USERS/$STRING_LITERAL_INCLUDE" -internal const val PATH_SEARCH = "$STRING_LITERAL_USERS/$STRING_LITERAL_SEARCH" -internal const val URL_HOME_EXACT = "$PATH_BASE/$STRING_LITERAL_HOME" - -internal const val URL_USERS_WITH_FILTER = "$PATH_BASE/$PATH_INCLUDE/{$STRING_LITERAL_FILTER}" -internal val URL_SEARCH = "$PATH_BASE/$PATH_SEARCH" + - "?${SearchKey::ageMin.name}={${SearchKey::ageMin.name}}" + - "&${SearchKey::ageMax.name}={${SearchKey::ageMax.name}}" + - "&${SearchKey::firstName.name}={${SearchKey::firstName.name}}" + - "&${SearchKey::location.name}={${SearchKey::location.name}}" -``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-custommatcher.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-custommatcher.md new file mode 100644 index 0000000..cf2d0c1 --- /dev/null +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-custommatcher.md @@ -0,0 +1,178 @@ +# Custom DeepLinkMatcher Recipe + +This recipe demonstrates how to create a custom `DeepLinkMatcher` in Navigation 3 using custom request extras and Kotlinx Serialization. + +## How it works + +This recipe consists of two activities: + +- `CustomDeepLinkMatcherActivity`: Accepts user input, serializes a `HomeKey` instance into JSON, attaches it to an `Intent` extra via a `RequestExtrasKey`, and launches `MainActivity`. +- `MainActivity`: Constructs a `DeepLinkRequest(intent)`, evaluates it with `JsonDeepLinkMatcher`, decodes the `HomeKey`, and sets it as the starting route in `NavDisplay`. + +## Key Concepts + +1. **Custom `RequestExtrasKey`** : `JsonDeepLinkMatcherKey` defines a custom extra key implementing `RequestExtrasKey` to type-safely store and read serialized JSON payloads in `DeepLinkRequest.extras`. + +2. **Custom `DeepLinkMatcher`** : `JsonDeepLinkMatcher` extends `DeepLinkMatcher>` and implements `matchRequest(request)` to extract `request.extras[JsonDeepLinkMatcherKey]` and decode it into a strongly typed `NavKey` using Kotlinx Serialization. + +[![](https://developer.android.com/static/images/picto-icons/code.svg) Explore View the full recipe on GitHub.](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/deeplink/usecases/matcher) + +``` +package com.example.nav3recipes.deeplink.usecases.matcher + +import android.content.Intent +import android.os.Bundle +import android.util.Log +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.ElevatedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.dropUnlessResumed +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.deeplink.DeepLinkMatcher +import androidx.navigation3.runtime.deeplink.DeepLinkRequest +import androidx.navigation3.runtime.deeplink.RequestExtrasKey +import androidx.navigation3.runtime.deeplink.get +import com.example.nav3recipes.common.deeplink.EntryScreen +import com.example.nav3recipes.ui.setEdgeToEdgeConfig +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json + +class CustomDeepLinkMatcherActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + setEdgeToEdgeConfig() + super.onCreate(savedInstanceState) + + setContent { + EntryScreen { + Column( + verticalArrangement = Arrangement.spacedBy(32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + var text by remember { mutableStateOf("") } + OutlinedTextField( + placeholder = { Text("Your name...", color = Color.Black.copy(alpha = 0.5f)) }, + value = text, + singleLine = true, + onValueChange = { text = it }, + ) + + ElevatedButton( + onClick = + dropUnlessResumed { + val intent = Intent( + this@CustomDeepLinkMatcherActivity, + MainActivity::class.java + ) + val json = Json.encodeToString(HomeKey.serializer(), HomeKey(text)) + intent.putExtra(JsonDeepLinkMatcherKey.toString(), json) + startActivity(intent) + } + ) { + Text("Sign up") + } + } + } + } + } +} + +internal data object JsonDeepLinkMatcherKey: RequestExtrasKey + +internal class JsonDeepLinkMatcher(val serializer: KSerializer): DeepLinkMatcher>() { + override fun matchRequest(request: DeepLinkRequest): MatchResult? { + val json = request.extras[JsonDeepLinkMatcherKey] ?: return null + return try { + val result = Json.decodeFromString(serializer, json) + MatchResult(result) + } catch (e: SerializationException) { + Log.v("DeepLinkMatcher", "Failed to decode json", e) + return null + } + } +} + + +``` + +``` +package com.example.nav3recipes.deeplink.usecases.matcher + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.navigation3.runtime.NavBackStack +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.deeplink.DeepLinkRequest +import androidx.navigation3.runtime.deeplink.invoke +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberNavBackStack +import androidx.navigation3.ui.NavDisplay +import com.example.nav3recipes.common.deeplink.EntryScreen +import com.example.nav3recipes.common.deeplink.TextContent +import com.example.nav3recipes.ui.setEdgeToEdgeConfig +import kotlinx.serialization.Serializable +import kotlinx.serialization.serializer + +@Serializable +internal data class HomeKey(val name: String): NavKey + +@Serializable +internal object FallbackKey: NavKey + +class MainActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + setEdgeToEdgeConfig() + super.onCreate(savedInstanceState) + + val request = DeepLinkRequest(intent) + val deepLinkMatcher = createJsonDeepLinkMatcher() + + val matchResult = deepLinkMatcher.match(request) + val key = matchResult?.key ?: FallbackKey + + setContent { + val backStack: NavBackStack = rememberNavBackStack(key) + NavDisplay( + backStack = backStack, + onBack = backStack::removeLastOrNull, + entryProvider = entryProvider { + entry { key -> + EntryScreen("Welcome") { + TextContent(key.name) + } + } + entry { key -> + EntryScreen("Fallback Key") { + TextContent( + "Failed to deep link - DeepLinkRequest " + + "did not match with any DeepLinkMatcher" + ) + } + } + } + ) + } + } +} + +// Optional JsonDeepLinkMatcher factory function that automatically captures KSerializer for T. +private inline fun createJsonDeepLinkMatcher(): JsonDeepLinkMatcher { + val serializer = serializer() + return JsonDeepLinkMatcher(serializer) +} + + +``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-staticuri.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-staticuri.md new file mode 100644 index 0000000..5b9aa71 --- /dev/null +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-staticuri.md @@ -0,0 +1,143 @@ +# Deep Link Static URI Recipe + +This recipe demonstrates how deep link with a static Uri. + +## Recipe components + +The recipe contains two activities: + +1. `StaticUriDeepLinkActivity` to construct and start an Intent with the deep link uri +2. `MainActivity` is the target Activity of the deep link, represents an app that users can deep link to. + +## How the demonstrated deep link works + +1. The deep link source (`StaticUriDeepLinkActivity`) defines the uri and creates an Intent to deep link with. +2. The app (`MainActivity`) declares a navigation key (`HomeKey`). To indicate that `HomeKey` supports deep linking, the app declares a `UriDeepLinkMatcher` with the `HomeKey` serializer along with the uri pattern that `HomeKey` supports. +3. `MainActivity` onCreate instantiates a `DeepLinkRequest` with the intent and matches it with the `UriDeepLinkMatcher` to get a `MatchResult`. If the `MatchResult` is non-null, the app navigates to the key returned by the result. Otherwise, the deep link is not supported and the app navigates to a `Fallback` screen. + +[![](https://developer.android.com/static/images/picto-icons/code.svg) Explore View the full recipe on GitHub.](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/deeplink/handlerequests/staticuri) + +``` +package com.example.nav3recipes.deeplink.handlerequests.staticuri + +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.core.net.toUri +import androidx.lifecycle.compose.dropUnlessResumed +import com.example.nav3recipes.common.deeplink.EntryScreen +import com.example.nav3recipes.common.deeplink.PaddedButton +import com.example.nav3recipes.common.deeplink.TextContent +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.PATH_BASE +import com.example.nav3recipes.ui.setEdgeToEdgeConfig + +const val HOME_URI = "$PATH_BASE/home" + +class StaticUriDeepLinkActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + setEdgeToEdgeConfig() + super.onCreate(savedInstanceState) + + setContent { + EntryScreen("Deep link url:") { + TextContent(HOME_URI) + PaddedButton("Deeplink Away!", onClick = dropUnlessResumed { + val intent = Intent( + this@StaticUriDeepLinkActivity, + MainActivity::class.java + ) + // the uri to deep link with + intent.data = HOME_URI.toUri() + startActivity(intent) + }) + } + } + } +} + + +``` + +``` +package com.example.nav3recipes.deeplink.handlerequests.staticuri + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.navigation3.runtime.NavBackStack +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberNavBackStack +import androidx.navigation3.ui.NavDisplay +import com.example.nav3recipes.common.deeplink.EntryScreen +import com.example.nav3recipes.common.deeplink.TextContent +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.HomeKey +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.NavRecipeKey +import androidx.navigation3.runtime.deeplink.DeepLinkRequest +import androidx.navigation3.runtime.deeplink.DeepLinkUri +import androidx.navigation3.runtime.deeplink.UriDeepLinkMatcher +import androidx.navigation3.runtime.deeplink.invoke +import com.example.nav3recipes.ui.setEdgeToEdgeConfig +import kotlinx.serialization.Serializable +import kotlinx.serialization.serializer + + +@Serializable +internal object FallbackKey: NavRecipeKey { + override val name: String = "Fallback Key" +} + +class MainActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + setEdgeToEdgeConfig() + super.onCreate(savedInstanceState) + + // create a DeepLinkRequest with the intent + val request = DeepLinkRequest(intent) + + // try to match DeepLinkRequest to a DeepLinkMatcher + val matchResult = HOME_MATCHER.match(request) + val key = matchResult?.key ?: FallbackKey + + /** + * Then pass starting key to backstack + */ + setContent { + val backStack: NavBackStack = rememberNavBackStack(key) + NavDisplay( + backStack = backStack, + onBack = { backStack.removeLastOrNull() }, + entryProvider = entryProvider { + entry { key -> + EntryScreen(key.name) { + TextContent("Deep linked to Home") + } + } + entry { key -> + EntryScreen("${key.name} ") { + TextContent( + "Failed to deep link - DeepLinkRequest " + + "did not match with any DeepLinkMatcher" + ) + } + } + + } + ) + } + } +} + +/** + * Each matcher is associated with a navigation key that supports this deep link. + * + * A navigation key can be associated with multiple DeepLinkMatchers if it supports more than one deep link. + */ +private val HOME_MATCHER = UriDeepLinkMatcher( + uriPattern = DeepLinkUri(HOME_URI), + serializer = serializer(), +) + +``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-advanced.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-syntheticbackstack.md similarity index 62% rename from navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-advanced.md rename to navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-syntheticbackstack.md index f241291..6eae0e3 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-advanced.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-syntheticbackstack.md @@ -1,34 +1,54 @@ -# Deep Link Advanced Recipe +# Deep Link Synthetic BackStack Recipe -This recipe demonstrates how to apply the principles of navigation in the context of deep links by -managing a synthetic backStack and Task stacks. +This recipe demonstrates how to apply the principles of navigation in the context of deep links by managing a synthetic backStack and Task stacks. # Recipe Structure -This recipe simulates a real-world scenario where "App A" deeplinks -into "App B". +This recipe simulates a real-world scenario where "App A" deep links into "App B". -"App A" is simulated by the module [com.example.nav3recipes.deeplink.advanced](https://developer.android.com/app/src/main/java/com/example/nav3recipes/deeplink/advanced), which -contains the `CreateAdvancedDeepLinkActivity` that allows you to create a deeplink intent and -trigger that in either the existing Task, or in a new Task. +"App A" is simulated by the module [syntheticbackstack](https://developer.android.com/app/src/main/java/com/example/nav3recipes/deeplink/handlerequests/syntheticbackstack), which contains the `SyntheticBackStackDeepLinkActivity` that allows you to create a deeplink intent and trigger that in either the existing Task, or in a new Task. -"App B" is simulated by the module [advanceddeeplinkapp](https://developer.android.com/advanceddeeplinkapp/src/main/java/com/example/nav3recipes/deeplink/advanced), which contains -the MainActivity that you deeplink into. That module shows you how to build a synthetic backStack -and how to manage the Task stack properly in order to support both Back and Up buttons. +"App B" is simulated by the module [syntheticbackstackapp](https://developer.android.com/syntheticbackstackapp/src/main/java/com/example/nav3recipes/deeplink/syntheticbackstack), which contains the `SyntheticBackStackAppActivity` that you deeplink into. That module shows you how to build a synthetic backStack and how to manage the Task stack properly in order to support both Back and Up buttons. + +# How to Use + +Ensure both the main `app` and `syntheticbackstackapp` are installed on the emulator or connected device. Ensure that the installed `syntheticbackstackapp` supports the `"www.nav3deeplink.com"` link. + +On the recipe's landing page, choose the filters and click the button to deep link. It should bring you to the Activity of `syntheticbackstackapp`. + +# How it Works + +The recipe follows the deep link guideline summarized [here](https://developer.android.com/docs/deeplink-guide#summary). + +To see behavior of `Existing Task`: + +1. Open deep link using current task +2. On the device, swipe up to see all recent apps +3. Notice that the new Activity is opened within the Nav3Recipes app +4. Click back button to go back to the original Activity +5. Repeat step 1 +6. Click the up button to go to parent screen +7. On the device, swipe up to see all recent apps +8. Notice that the new Activity is now opened within the Nav3SyntheticBackStack app + +To see behavior of `New Task`: + +1. Open deep link using new task +2. On the device, swipe up to see all recent apps +3. Notice that the new Activity is opened within the Nav3SyntheticBackStack app +4. Click Up or Back button to go to parent screen # Core implementation -The core helper functions for navigateUp and building synthetic backStack can be -found [here](https://developer.android.com/static/advanceddeeplinkapp/src/main/java/com/example/nav3recipes/deeplink/advanced/util/DeepLinkBackStackUtil.kt) +The core helper functions for navigateUp and building synthetic backStack can be found [here](https://developer.android.com/syntheticbackstackapp/src/main/java/com/example/nav3recipes/deeplink/syntheticbackstack/util) # Further Read -Check out the [deep link guide](https://developer.android.com/docs/deeplink-guide) for a -comprehensive guide on Deep linking principles and how to apply them in Navigation 3. -[![](https://developer.android.com/static/images/picto-icons/code.svg) Explore View the full recipe on GitHub.](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/deeplink/advanced) +Check out the [deep link guide](https://developer.android.com/docs/deeplink-guide) for a comprehensive guide on Deep linking principles and how to apply them in Navigation 3. +[![](https://developer.android.com/static/images/picto-icons/code.svg) Explore View the full recipe on GitHub.](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/deeplink/handlerequests/syntheticbackstack) ``` -package com.example.nav3recipes.deeplink.advanced +package com.example.nav3recipes.deeplink.handlerequests.syntheticbackstack import android.content.Intent import android.os.Bundle @@ -53,20 +73,20 @@ internal const val ADVANCED_PATH_BASE = "https://www.nav3deeplink.com" /** * The recipe entry point that allows users to create a deep link and make a request with it. * - * **HOW THIS RECIPE WORKS** This recipe simulates a real-world scenario where "App A" deeplinks + * **HOW THIS RECIPE WORKS** This recipe simulates a real-world scenario where "App A" deep links * into "App B". * - * "App A" is simulated by this current module [com.example.nav3recipes.deeplink.advanced], which - * contains the [AdvancedCreateDeepLinkActivity] that allows you to create a deeplink intent and + * "App A" is simulated by this current module `syntheticbackstack`, which + * contains the [SyntheticBackStackDeepLinkActivity] that allows you to create a deeplink intent and * trigger that in either the existing Task, or in a new Task. * - * "App B" is simulated by the module [com.example.nav3recipes.deeplink.advanced], which contains - * the MainActivity that you deeplink into. That module shows you how to build a synthetic backStack + * "App B" is simulated by the module `syntheticbackstackapp`, which contains + * the SyntheticBackStackAppActivity that you deeplink into. That module shows you how to build a synthetic backStack * and how to manage the Task stack properly in order to support both Back and Up buttons. * * See the [README](README.md) file of current module for more info on advanced deep linking. */ -class AdvancedCreateDeepLinkActivity: ComponentActivity() { +class SyntheticBackStackDeepLinkActivity: ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { setEdgeToEdgeConfig() @@ -152,4 +172,6 @@ private val MENU_OPTIONS_LOCATION = mapOf( private val MENU_OPTIONS_TASK_STACK = mapOf( TAG_TASK_STACK to listOf(TAG_CURRENT_TASK, TAG_NEW_TASK), ) + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-uriarguments.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-uriarguments.md new file mode 100644 index 0000000..5113ed5 --- /dev/null +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/deeplinks-uriarguments.md @@ -0,0 +1,396 @@ +# Deep Link URI Arguments Recipe + +This recipe demonstrates how to parse a deep link URL from an Android Intent into a Navigation key. + +## Recipe components + +It consists of two activities + +1. `UriWithArgumentsDeepLinkActivity` constructs and triggers the deeplink request +2. `MainActivity` parses the intent into the target navigation key. + +## How it works + +The `MainActivity` handles the request with these steps + +1. Declare a `UriDeepLinkMatcher` for each url pattern that can be deep linked into. Each matcher accepts a uri pattern and the KSerializer of the NavKey that supports this deep link. + +2. Create a `DeepLinkRequest` with the incoming intent. + +3. Match all candidate `UriDeepLinkMatchers` with the request and compare the resulting `UriMatchResults` for the best match. + +4. Read the matching key from `UriMatchResult.key` or use default key if no match. + +This recipe focuses on handing an intent and does not include these considerations: + +- Create synthetic backStack +- Multi-modular setup +- DI +- Managing TaskStack +- Up button vs Back Button + +## Demonstrated forms of deeplink + +The `MainActivity` has several backStack keys to demonstrate different types of supported deep links: + +1. `HomeKey` - deeplink with an exact url (no deeplink arguments) +2. `UsersKey` - deeplink with path arguments +3. `SearchKey` - deeplink with query arguments + +See `MainActivity.deepLinkMatchers` for the actual url pattern of each. +[![](https://developer.android.com/static/images/picto-icons/code.svg) Explore View the full recipe on GitHub.](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/deeplink/handlerequests/uriarguments) + +``` +package com.example.nav3recipes.deeplink.handlerequests.uriarguments + +import androidx.navigation3.runtime.NavKey +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.STRING_LITERAL_FILTER +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.STRING_LITERAL_HOME +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.STRING_LITERAL_SEARCH +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.STRING_LITERAL_USERS +import kotlinx.serialization.Serializable + +internal interface NavRecipeKey: NavKey { + val name: String +} + +@Serializable +internal object HomeKey: NavRecipeKey { + override val name: String = STRING_LITERAL_HOME +} + +@Serializable +internal data class UsersKey( + val filter: String, +): NavRecipeKey { + override val name: String = STRING_LITERAL_USERS + companion object { + const val FILTER_KEY = STRING_LITERAL_FILTER + const val FILTER_OPTION_RECENTLY_ADDED = "recentlyAdded" + const val FILTER_OPTION_ALL = "all" + } +} + +@Serializable +internal data class SearchKey( + val firstName: String? = null, + val ageMin: Int? = null, + val ageMax: Int? = null, + val location: String? = null, +): NavRecipeKey { + override val name: String = STRING_LITERAL_SEARCH +} + +``` + +``` +package com.example.nav3recipes.deeplink.handlerequests.uriarguments + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.core.net.toUri +import androidx.navigation3.runtime.NavBackStack +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.deeplink.DeepLinkRequest +import androidx.navigation3.runtime.deeplink.UriDeepLinkMatcher +import androidx.navigation3.runtime.deeplink.invoke +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberNavBackStack +import androidx.navigation3.ui.NavDisplay +import com.example.nav3recipes.common.deeplink.EntryScreen +import com.example.nav3recipes.common.deeplink.FriendsList +import com.example.nav3recipes.common.deeplink.LIST_USERS +import com.example.nav3recipes.common.deeplink.TextContent +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.URL_HOME_EXACT +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.URL_SEARCH +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.URL_USERS_WITH_FILTER +import com.example.nav3recipes.ui.setEdgeToEdgeConfig +import kotlinx.serialization.serializer + +/** + * See README.md for how this recipe works. + */ +class MainActivity : ComponentActivity() { + /** STEP 1. Declare supported deep links */ + internal val deepLinkMatchers: List> = listOf( + // "https://www.nav3recipes.com/home" + UriDeepLinkMatcher(URL_HOME_EXACT.toUri(), serializer()), + // "https://www.nav3recipes.com/users/with/{filter}" + UriDeepLinkMatcher(URL_USERS_WITH_FILTER.toUri(), serializer()), + // "https://www.nav3recipes.com/users/search?{firstName}&{age}&{location}" + UriDeepLinkMatcher(URL_SEARCH.toUri(), serializer()), + ) + + override fun onCreate(savedInstanceState: Bundle?) { + setEdgeToEdgeConfig() + super.onCreate(savedInstanceState) + + /** STEP 2. Create a [DeepLinkRequest] from the intent */ + val request = DeepLinkRequest(intent) + + /** STEP 3. Match the request to the DeepLinkMatchers*/ + // First get all the possible matching UriMatchResult + val matches = deepLinkMatchers.mapNotNull { + // returns null if no match + it.match(request) + } + // compare all matches to find best match + val bestMatch = matches.maxOrNull() + /** STEP 4. Get the key from the match or use default key if no match*/ + val key = bestMatch?.key ?: HomeKey + + /** + * STEP 5. pass the initial key to backstack + */ + setContent { + val backStack: NavBackStack = rememberNavBackStack(key) + NavDisplay( + backStack = backStack, + onBack = { backStack.removeLastOrNull() }, + entryProvider = entryProvider { + entry { key -> + EntryScreen(key.name) { + TextContent("") + } + } + entry { key -> + EntryScreen("${key.name} : ${key.filter}") { + TextContent("") + val list = when { + key.filter.isEmpty() -> LIST_USERS + key.filter == UsersKey.FILTER_OPTION_ALL -> LIST_USERS + else -> LIST_USERS.take(5) + } + FriendsList(list) + } + } + entry { search -> + EntryScreen(search.name) { + TextContent("") + val matchingUsers = LIST_USERS.filter { user -> + (search.firstName == null || user.firstName == search.firstName) && + (search.location == null || user.location == search.location) && + (search.ageMin == null || user.age >= search.ageMin) && + (search.ageMax == null || user.age <= search.ageMax) + } + FriendsList(matchingUsers) + } + } + } + ) + } + } +} + +``` + +``` +package com.example.nav3recipes.deeplink.handlerequests.uriarguments + +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.core.net.toUri +import androidx.lifecycle.compose.dropUnlessResumed +import com.example.nav3recipes.common.deeplink.EMPTY +import com.example.nav3recipes.common.deeplink.EntryScreen +import com.example.nav3recipes.common.deeplink.FIRST_NAME_JOHN +import com.example.nav3recipes.common.deeplink.FIRST_NAME_JULIE +import com.example.nav3recipes.common.deeplink.FIRST_NAME_MARY +import com.example.nav3recipes.common.deeplink.FIRST_NAME_TOM +import com.example.nav3recipes.common.deeplink.LOCATION_BC +import com.example.nav3recipes.common.deeplink.LOCATION_BR +import com.example.nav3recipes.common.deeplink.LOCATION_CA +import com.example.nav3recipes.common.deeplink.LOCATION_US +import com.example.nav3recipes.common.deeplink.MenuDropDown +import com.example.nav3recipes.common.deeplink.MenuTextInput +import com.example.nav3recipes.common.deeplink.PaddedButton +import com.example.nav3recipes.common.deeplink.TextContent +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.PATH_BASE +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.PATH_INCLUDE +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.PATH_SEARCH +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui.STRING_LITERAL_HOME +import com.example.nav3recipes.ui.setEdgeToEdgeConfig + +/** + * See README.md for how this recipe works. + * + * See [MainActivity] for how the requested deeplink is handled. + */ +class UriWithArgumentsDeepLinkActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + setEdgeToEdgeConfig() + super.onCreate(savedInstanceState) + + setContent { + /** + * UI for deeplink sandbox + */ + EntryScreen("Sandbox - Build Your Deeplink") { + TextContent("Base url:\n${PATH_BASE}/") + var showFilterOptions by remember { mutableStateOf(false) } + val selectedPath = remember { mutableStateOf(MENU_OPTIONS_PATH[KEY_PATH]?.first()) } + + var showQueryOptions by remember { mutableStateOf(false) } + var selectedFilter by remember { mutableStateOf("") } + val selectedSearchQuery = remember { mutableStateMapOf() } + + // manage path options + MenuDropDown( + menuOptions = MENU_OPTIONS_PATH, + ) { _, selection -> + selectedPath.value = selection + when (selection) { + PATH_SEARCH -> { + showQueryOptions = true + showFilterOptions = false + } + + PATH_INCLUDE -> { + showQueryOptions = false + showFilterOptions = true + } + + else -> { + showQueryOptions = false + showFilterOptions = false + } + } + } + + // manage path filter options, reset state if menu is closed + LaunchedEffect(showFilterOptions) { + selectedFilter = if (showFilterOptions) { + MENU_OPTIONS_FILTER.values.first().first() + } else { + "" + } + } + if (showFilterOptions) { + MenuDropDown( + menuOptions = MENU_OPTIONS_FILTER, + ) { _, selected -> + selectedFilter = selected + } + } + + // manage query options, reset state if menu is closed + LaunchedEffect(showQueryOptions) { + if (showQueryOptions) { + val initEntry = MENU_OPTIONS_SEARCH.entries.first() + selectedSearchQuery[initEntry.key] = initEntry.value.first() + } else { + selectedSearchQuery.clear() + } + } + if (showQueryOptions) { + MenuTextInput( + menuLabels = MENU_LABELS_SEARCH, + ) { label, selected -> + selectedSearchQuery[label] = selected + } + MenuDropDown( + menuOptions = MENU_OPTIONS_SEARCH, + ) { label, selected -> + selectedSearchQuery[label] = selected + } + } + + // form final deeplink url + val arguments = when (selectedPath.value) { + PATH_INCLUDE -> "/${selectedFilter}" + PATH_SEARCH -> { + buildString { + selectedSearchQuery.forEach { entry -> + if (entry.value.isNotEmpty()) { + val prefix = if (isEmpty()) "?" else "&" + append("$prefix${entry.key}=${entry.value}") + } + } + } + } + + else -> "" + } + val finalUrl = "${PATH_BASE}/${selectedPath.value}$arguments" + TextContent("Final url:\n$finalUrl") + // deeplink to target + PaddedButton("Deeplink Away!", onClick = dropUnlessResumed { + val intent = Intent( + this@UriWithArgumentsDeepLinkActivity, + MainActivity::class.java + ) + // start activity with the url + intent.data = finalUrl.toUri() + startActivity(intent) + }) + } + } + } +} + +private const val KEY_PATH = "path" +private val MENU_OPTIONS_PATH = mapOf( + KEY_PATH to listOf( + STRING_LITERAL_HOME, + PATH_INCLUDE, + PATH_SEARCH, + ), +) + +private val MENU_OPTIONS_FILTER = mapOf( + UsersKey.FILTER_KEY to listOf(UsersKey.FILTER_OPTION_RECENTLY_ADDED, UsersKey.FILTER_OPTION_ALL), +) + +private val MENU_OPTIONS_SEARCH = mapOf( + SearchKey::firstName.name to listOf( + EMPTY, + FIRST_NAME_JOHN, + FIRST_NAME_TOM, + FIRST_NAME_MARY, + FIRST_NAME_JULIE + ), + SearchKey::location.name to listOf(EMPTY, LOCATION_CA, LOCATION_BC, LOCATION_BR, LOCATION_US) +) + +private val MENU_LABELS_SEARCH = listOf(SearchKey::ageMin.name, SearchKey::ageMax.name) + + + +``` + +``` +package com.example.nav3recipes.deeplink.handlerequests.uriarguments.ui + +import com.example.nav3recipes.deeplink.handlerequests.uriarguments.SearchKey + +/** + * String resources + */ +internal const val STRING_LITERAL_FILTER = "filter" +internal const val STRING_LITERAL_HOME = "home" +internal const val STRING_LITERAL_USERS = "users" +internal const val STRING_LITERAL_SEARCH = "search" +internal const val STRING_LITERAL_INCLUDE = "include" +internal const val PATH_BASE = "https://www.nav3recipes.com" +internal const val PATH_INCLUDE = "$STRING_LITERAL_USERS/$STRING_LITERAL_INCLUDE" +internal const val PATH_SEARCH = "$STRING_LITERAL_USERS/$STRING_LITERAL_SEARCH" +internal const val URL_HOME_EXACT = "$PATH_BASE/$STRING_LITERAL_HOME" + +internal const val URL_USERS_WITH_FILTER = "$PATH_BASE/$PATH_INCLUDE/{$STRING_LITERAL_FILTER}" +internal val URL_SEARCH = "$PATH_BASE/$PATH_SEARCH" + + "?${SearchKey::ageMin.name}={${SearchKey::ageMin.name}}" + + "&${SearchKey::ageMax.name}={${SearchKey::ageMax.name}}" + + "&${SearchKey::firstName.name}={${SearchKey::firstName.name}}" + + "&${SearchKey::location.name}={${SearchKey::location.name}}" + + +``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/dialog.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/dialog.md index 6ef8efe..543c21f 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/dialog.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/dialog.md @@ -104,4 +104,6 @@ class DialogActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/lifecycle-owner.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/lifecycle-owner.md new file mode 100644 index 0000000..90c4317 --- /dev/null +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/lifecycle-owner.md @@ -0,0 +1,187 @@ +# LocalLifecycleOwner Recipe + +This recipe demonstrates how to use `LifecycleResumeEffect` in Navigation 3 entries to pause and resume work based on the entry's lifecycle state. + +## How it works + +In Navigation 3, by default each `NavEntry` is provided its own `LifecycleOwner` via `LocalLifecycleOwner.current`. This means that any lifecycle-aware components inside the entry is automatically scoped to the `NavEntry`. + +### `LifecycleResumeEffect` with Dialog Scenes + +1. **RouteA (Screen)**: + + - Uses `LifecycleResumeEffect(Unit)` scoped to the `NavEntry`'s `LocalLifecycleOwner.current` to advance the`LinearProgressIndicator` while in the `RESUMED` state. + - Automatically resets `progressValue` back to `0f` whenever it hits `1f`. +2. **RouteB (Dialog)**: + + - Configured as a dialog using `DialogSceneStrategy.dialog()`. + - When the user opens the RouteB dialog, RouteA remains visible behind the dialog in the `STARTED` state (leaving `RESUMED`). + - `LifecycleResumeEffect` calls `onPauseOrDispose`, pausing the progress indicator. + - When the dialog is dismissed, RouteA returns to `RESUMED`, and `LifecycleResumeEffect` resumes the progress indicator automatically. + +[![](https://developer.android.com/static/images/picto-icons/code.svg) Explore View the full recipe on GitHub.](https://github.com/android/nav3-recipes/tree/main/app/src/main/java/com/example/nav3recipes/lifecycleowner) + +``` +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.nav3recipes.lifecycleowner + +import android.os.Bundle +import android.util.Log +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.snap +import androidx.compose.animation.core.tween +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.dropUnlessResumed +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberNavBackStack +import androidx.navigation3.scene.DialogSceneStrategy +import androidx.navigation3.ui.NavDisplay +import com.example.nav3recipes.content.ContentGreen +import com.example.nav3recipes.ui.setEdgeToEdgeConfig +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.serialization.Serializable +import kotlin.time.Duration.Companion.milliseconds + +@Serializable +private data object RouteA : NavKey + +@Serializable +private data object RouteB : NavKey + +class LifecycleOwnerActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + setEdgeToEdgeConfig() + super.onCreate(savedInstanceState) + setContent { + val backStack = rememberNavBackStack(RouteA) + val dialogStrategy = remember { DialogSceneStrategy() } + + NavDisplay( + backStack = backStack, + onBack = backStack::removeLastOrNull, + sceneStrategies = listOf(dialogStrategy), + entryProvider = entryProvider { + entry { + LogLifecycleEffect("ScreenA") + ContentGreen("Screen A") { + var progressValue by remember { mutableFloatStateOf(0f) } + val coroutineScope = rememberCoroutineScope() + + val animatedProgress by animateFloatAsState( + targetValue = progressValue, + animationSpec = if (progressValue == 0f) snap() else tween(durationMillis = 100, easing = LinearEasing), + label = "ProgressAnimation" + ) + + // LifecycleResumeEffect runs only while ScreenA is in the RESUMED state. + // When the dialog opens, ScreenA transitions to PAUSED, which calls onPauseOrDispose. + LifecycleResumeEffect(Unit) { + val job = coroutineScope.launch { + while (true) { + delay(100.milliseconds) + progressValue += 0.01f + if (progressValue >= 1f) { + progressValue = 0f + } + } + } + onPauseOrDispose { + job.cancel() + } + } + + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.padding(16.dp) + ) { + LinearProgressIndicator(progress = { animatedProgress }) + Spacer(modifier = Modifier.height(16.dp)) + Button(onClick = dropUnlessResumed { backStack.add(RouteB) }) { + Text("Open Dialog") + } + } + } + } + entry(metadata = DialogSceneStrategy.dialog()) { + LogLifecycleEffect("Dialog") + AlertDialog( + onDismissRequest = backStack::removeLastOrNull, + title = { Text("Dialog") }, + text = { + Text("Screen A is no longer in resumed state, pausing the progress indicator.") + }, + confirmButton = { + Button(onClick = dropUnlessResumed { backStack.removeLastOrNull() }) { + Text("Dismiss Dialog") + } + } + ) + } + } + ) + } + } +} + +@Composable +private fun LogLifecycleEffect(screenName: String) { + LifecycleEventEffect(Lifecycle.Event.ON_CREATE) { + Log.d("LifecycleOwner", "$screenName: ON_CREATE") + } + LifecycleEventEffect(Lifecycle.Event.ON_START) { + Log.d("LifecycleOwner", "$screenName: ON_START") + } + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { + Log.d("LifecycleOwner", "$screenName: ON_RESUME") + } + LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { + Log.d("LifecycleOwner", "$screenName: ON_PAUSE") + } + LifecycleEventEffect(Lifecycle.Event.ON_STOP) { + Log.d("LifecycleOwner", "$screenName: ON_STOP") + } + // Note that ON_DESTROY event is not observable from composables. +} + + +``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md index fbaae79..032a997 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md @@ -138,4 +138,6 @@ class MaterialListDetailActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/material-supportingpane.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/material-supportingpane.md index 58a6a7c..d20f52e 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/material-supportingpane.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/material-supportingpane.md @@ -142,4 +142,6 @@ class MaterialSupportingPaneActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/modular-hilt.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/modular-hilt.md index fcc94a2..e4550b8 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/modular-hilt.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/modular-hilt.md @@ -75,6 +75,8 @@ private fun ProfileScreen() { ) } } + + ``` ``` @@ -118,6 +120,8 @@ class HiltModularActivity : ComponentActivity() { } } } + + ``` ``` @@ -236,6 +240,8 @@ private fun ConversationDetailScreen( } } } + + ``` ``` @@ -261,6 +267,7 @@ class Navigator(startDestination: Any) { backStack.removeLastOrNull() } } + ``` ``` @@ -280,4 +287,6 @@ object AppModule { @ActivityRetainedScoped fun provideNavigator() : Navigator = Navigator(startDestination = ConversationList) } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/modular-koin.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/modular-koin.md index d1e7ad6..6e59bdc 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/modular-koin.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/modular-koin.md @@ -66,6 +66,8 @@ private fun ProfileScreen() { ) } } + + ``` ``` @@ -181,6 +183,8 @@ private fun ConversationDetailScreen( } } } + + ``` ``` @@ -200,6 +204,7 @@ class Navigator(startDestination: Any) { backStack.removeLastOrNull() } } + ``` ``` @@ -217,6 +222,7 @@ val appModule = module { } } } + ``` ``` @@ -284,4 +290,6 @@ class KoinModularActivity : ComponentActivity(), AndroidScopeComponent, KoinComp } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/multiple-backstacks.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/multiple-backstacks.md index 81cd794..8831896 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/multiple-backstacks.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/multiple-backstacks.md @@ -2,7 +2,7 @@ This recipe demonstrates how to create multiple back stacks. -The app has three top level routes: `RouteA`, `RouteB` and `RouteC`. These routes have sub routes `RouteA1`, `RouteB1` and `RouteC1` respectively. The content for the sub routes is a counter that can be used to verify state retention through configuration changes and process death. +The app has three top level routes: `RouteA`, `RouteB` and `RouteC`. These routes have sub routes `RouteA1`, `RouteB1` and `RouteC1` respectively. `RouteA1` contains a 100-item scrollable list, while `RouteB1` and `RouteC1` contain counters used to verify state retention through configuration changes and process death. The app's navigation state is held in the `NavigationState` class. The state itself is created using `rememberNavigationState`. @@ -14,6 +14,7 @@ Key behaviors: - This app follows the "exit through home" pattern where the user always exits through the starting back stack. This means that `RouteA`'s entries are *always* in the list of entries. - Navigating to a top level route that is not the starting route *replaces* the other entries. For example, navigating A-\>B-\>C would result in entries for A+C, B's entries are removed. +- When a top-level route is reselected, for example if the user is on `RouteA` and taps `RouteA` on the navigation bar again, the `NavigationBar` signals the reselected key to `Navigator`, which emits it to a `Flow`. `RouteA1` observes this flow and, when it receives `RouteA`, resets its list scroll position to index 0. Important implementation details: @@ -41,11 +42,16 @@ Important implementation details: package com.example.nav3recipes.multiplestacks import androidx.navigation3.runtime.NavKey +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.asSharedFlow /** * Handles navigation events (forward and back) by updating the navigation state. */ class Navigator(val state: NavigationState){ + private val _reselectEvents = MutableSharedFlow(extraBufferCapacity = 1) + val reselectEvents = _reselectEvents.asSharedFlow() + fun navigate(route: NavKey){ if (route in state.backStacks.keys){ // This is a top level route, just switch to it @@ -55,6 +61,10 @@ class Navigator(val state: NavigationState){ } } + fun onReselect(route: NavKey) { + _reselectEvents.tryEmit(route) + } + fun goBack(){ val currentStack = state.backStacks[state.topLevelRoute] ?: error("Stack for ${state.topLevelRoute} not found") @@ -68,6 +78,8 @@ class Navigator(val state: NavigationState){ } } } + + ``` ``` @@ -204,6 +216,8 @@ class NavigationState( listOf(startRoute, topLevelRoute) } } + + ``` ``` @@ -225,10 +239,11 @@ class NavigationState( package com.example.nav3recipes.multiplestacks -import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Camera import androidx.compose.material.icons.filled.Face @@ -239,7 +254,9 @@ import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.unit.dp import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.entryProvider import androidx.navigation3.ui.NavDisplay @@ -277,7 +294,6 @@ data class NavBarItem( ) class MultipleStacksActivity : ComponentActivity() { - @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") override fun onCreate(savedInstanceState: Bundle?) { setEdgeToEdgeConfig() super.onCreate(savedInstanceState) @@ -290,18 +306,26 @@ class MultipleStacksActivity : ComponentActivity() { val navigator = remember { Navigator(navigationState) } val entryProvider = entryProvider { - featureASection(onSubRouteClick = { navigator.navigate(RouteA1) }) + featureASection( + reselectEvents = navigator.reselectEvents, + onSubRouteClick = { navigator.navigate(RouteA1) } + ) featureBSection(onSubRouteClick = { navigator.navigate(RouteB1) }) featureCSection(onSubRouteClick = { navigator.navigate(RouteC1) }) } - Scaffold(bottomBar = { + Scaffold(contentWindowInsets = WindowInsets(0.dp), bottomBar = { NavigationBar { TOP_LEVEL_ROUTES.forEach { (key, value) -> val isSelected = key == navigationState.topLevelRoute NavigationBarItem( selected = isSelected, - onClick = { navigator.navigate(key) }, + onClick = { + navigator.navigate(key) + if (isSelected) { + navigator.onReselect(key) + } + }, icon = { Icon( imageVector = value.icon, @@ -312,15 +336,18 @@ class MultipleStacksActivity : ComponentActivity() { ) } } - }) { + }) { innerPadding -> NavDisplay( entries = navigationState.toDecoratedEntries(entryProvider), - onBack = { navigator.goBack() } + onBack = { navigator.goBack() }, + modifier = Modifier.padding(innerPadding) ) } } } } + + ``` ``` @@ -343,13 +370,17 @@ class MultipleStacksActivity : ComponentActivity() { package com.example.nav3recipes.multiplestacks import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.Button import androidx.compose.material3.Text +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment +import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.dropUnlessResumed import androidx.navigation3.runtime.EntryProviderScope import androidx.navigation3.runtime.NavKey @@ -359,27 +390,34 @@ import com.example.nav3recipes.content.ContentOrange import com.example.nav3recipes.content.ContentPink import com.example.nav3recipes.content.ContentPurple import com.example.nav3recipes.content.ContentRed +import kotlinx.coroutines.flow.Flow fun EntryProviderScope.featureASection( + reselectEvents: Flow, onSubRouteClick: () -> Unit, ) { entry { ContentRed("Route A") { - Column(horizontalAlignment = Alignment.CenterHorizontally) { - Button(onClick = dropUnlessResumed(block = onSubRouteClick)) { - Text("Go to A1") - } + Button(onClick = dropUnlessResumed(block = onSubRouteClick)) { + Text("Go to A1") } } } entry { - ContentPink("Route A1") { - var count by rememberSaveable { - mutableIntStateOf(0) + val scrollState = rememberLazyListState() + LaunchedEffect(reselectEvents) { + reselectEvents.collect { route -> + if (route == RouteA) { + scrollState.scrollToItem(0) + } } + } - Button(onClick = { count++ }) { - Text("Value: $count") + ContentPink("Route A1") { + LazyColumn(state = scrollState) { + items(100) { index -> + Text("Route A item ${index + 1}", fontSize = 24.sp) + } } } } @@ -433,4 +471,6 @@ fun EntryProviderScope.featureCSection( } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/passingarguments.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/passingarguments.md index 2640a22..b00cd74 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/passingarguments.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/passingarguments.md @@ -133,6 +133,8 @@ class RouteBViewModel @AssistedInject constructor( fun create(navKey: RouteB): RouteBViewModel } } + + ``` # Passing Arguments to ViewModels (Basic) @@ -257,6 +259,8 @@ class RouteBViewModel( } } } + + ``` # Passing Arguments to ViewModels (Koin) @@ -368,4 +372,5 @@ fun ScreenB(viewModel: RouteBViewModel) { } class RouteBViewModel(val navKey: RouteB) : ViewModel() + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/results-event.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/results-event.md index ea7d27d..a8c510e 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/results-event.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/results-event.md @@ -41,6 +41,7 @@ import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { var person by mutableStateOf(null) } + ``` ``` @@ -70,6 +71,7 @@ data object Home : NavKey @Serializable class PersonDetailsForm : NavKey + ``` ``` @@ -95,6 +97,7 @@ import kotlinx.serialization.Serializable @Serializable data class Person(val name: String, val favoriteColor: String) + ``` ``` @@ -180,6 +183,7 @@ fun PersonDetailsScreen( } } } + ``` ``` @@ -270,4 +274,6 @@ class ResultEventActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/results-state.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/results-state.md index a73e148..4380a9d 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/results-state.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/results-state.md @@ -41,6 +41,7 @@ import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { var person by mutableStateOf(null) } + ``` ``` @@ -70,6 +71,7 @@ data object Home : NavKey @Serializable class PersonDetailsForm : NavKey + ``` ``` @@ -95,6 +97,7 @@ import kotlinx.serialization.Serializable @Serializable data class Person(val name: String, val favoriteColor: String) + ``` ``` @@ -180,6 +183,7 @@ fun PersonDetailsScreen( } } } + ``` ``` @@ -263,4 +267,6 @@ class ResultStateActivity : ComponentActivity() { } } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/scenes-listdetail.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/scenes-listdetail.md index 32063b3..4a2947b 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/scenes-listdetail.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/scenes-listdetail.md @@ -168,6 +168,8 @@ class ListDetailSceneStrategy(val windowSizeClass: WindowSizeClass) : S ) } } + + ``` ``` @@ -287,6 +289,7 @@ private fun NavBackStack.addDetail(detailRoute: ConversationDetail) { removeIf { it is ConversationDetail } add(detailRoute) } + ``` ``` @@ -432,4 +435,5 @@ fun ProfileScreen() { ) } } + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/scenes-twopane.md b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/scenes-twopane.md index fed0bf9..513494a 100644 --- a/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/scenes-twopane.md +++ b/navigation/navigation-3/references/android/guide/navigation/navigation-3/recipes/scenes-twopane.md @@ -123,6 +123,8 @@ class TwoPaneSceneStrategy(val windowSizeClass: WindowSizeClass) : Scen } + + ``` ``` @@ -241,4 +243,6 @@ private fun NavBackStack.addProductRoute(productId: Int) { add(productRoute) } } + + ``` \ No newline at end of file diff --git a/navigation/navigation-3/references/android/guide/navigation/type-safe-destinations.md b/navigation/navigation-3/references/android/guide/navigation/type-safe-destinations.md index c570000..8959d00 100644 --- a/navigation/navigation-3/references/android/guide/navigation/type-safe-destinations.md +++ b/navigation/navigation-3/references/android/guide/navigation/type-safe-destinations.md @@ -1,11 +1,8 @@ -This guide outlines the process of replacing string-based routes with -serializable Kotlin types to achieve compile-time safety and eliminate runtime -crashes caused by typos or incorrect argument types. +This guide outlines the process of replacing string-based routes with serializable Kotlin types to achieve compile-time safety and eliminate runtime crashes caused by typos or incorrect argument types. ## Prerequisites -Before starting the migration, verify that your project meets the following -requirements: +Before starting the migration, verify that your project meets the following requirements: 1. **Navigation version**: Update to Jetpack Navigation 2.8.0 or higher 2. **Kotlin serialization plugin**: @@ -43,8 +40,7 @@ Replace your constant route strings with `@Serializable` objects and classes. ## Step 2: Update the NavHost Configuration -Update your `NavHost` to use the new generic types in the `composable` and -`dialog` function. +Update your `NavHost` to use the new generic types in the `composable` and `dialog` function. **Before:** @@ -83,8 +79,7 @@ Replace string-interpolated navigation calls with class instances. ## Step 4: Accessing Arguments in ViewModels -If you use a `ViewModel`, you can now extract the route object directly from the -`SavedStateHandle`. +If you use a `ViewModel`, you can now extract the route object directly from the `SavedStateHandle`. **Implementation:** @@ -98,10 +93,9 @@ If you use a `ViewModel`, you can now extract the route object directly from the ## Step 5: (Advanced) Handling Custom Types -If you need to pass complex data classes (not just primitives), you must define -a custom `NavType`. +If you need to pass complex data classes (not just primitives), you must define a custom `NavType`. -1. **Create the Custom Type** : \`\`\`kotlin val SearchFilterType = object : NavType(isNullableAllowed = false) { override fun get(bundle: Bundle, key: String): SearchFilter? = Json.decodeFromString(bundle.getString(key) ?: return null) +1. **Create the Custom Type** : \`\`\`kotlin val SearchFilterType = object : NavType (isNullableAllowed = false) { override fun get(bundle: Bundle, key: String): SearchFilter? = Json.decodeFromString(bundle.getString(key) ?: return null) override fun parseValue(value: String): SearchFilter = Json.decodeFromString(Uri.decode(value)) @@ -124,6 +118,5 @@ a custom `NavType`. - **Sealed Hierarchies**: For large apps, group your routes using a sealed interface or class to keep the navigation structure organized - **Object Instances** : For routes without parameters, always use `object` instead of `class` to avoid unnecessary allocations -- **Nullable Types** : The new API supports nullable types (for example, `data - class Search(val query: String?)`) and provides default values automatically +- **Nullable Types** : The new API supports nullable types (for example, `data class Search(val query: String?)`) and provides default values automatically - **Testing** : Use `navController.currentBackStackEntry?.hasRoute()` to check the current destination in a type-safe manner during UI tests \ No newline at end of file diff --git a/performance/r8-analyzer/SKILL.md b/performance/r8-analyzer/SKILL.md index 2812549..f3ab821 100644 --- a/performance/r8-analyzer/SKILL.md +++ b/performance/r8-analyzer/SKILL.md @@ -7,7 +7,7 @@ description: Analyzes Android build files and R8 keep rules to identify redundan license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-18' + last-updated: '2026-08-06' keywords: - R8 - proguard @@ -20,33 +20,39 @@ metadata: - Inspect `build.gradle`, `build.gradle.kts`, and `gradle.properties`. - Use [references/CONFIGURATION.md](references/CONFIGURATION.md) to identify missing optimizations. -- **AGP** : If \< 9.0, suggest migration to 9.0 for [build time improvement - performance](references/android/topic/performance/app-optimization/enable-app-optimization.md) +- **AGP** : If version is lower than 9.0, suggest migration to 9.0 for [build-time performance improvement](references/android/topic/performance/app-optimization/enable-app-optimization.md). - **Full Mode** : Verify `android.enableR8.fullMode=false` is removed from gradle.properties. ## Step 2. Analysis path selection -- Inspect `build.gradle`, `build.gradle.kts`, and `gradle.properties` and - `libs.versions.toml` to get the R8 version +- Inspect `build.gradle`, `build.gradle.kts`, and `gradle.properties` and `libs.versions.toml` to get the AGP and R8 versions. -- **If R8 \>= 9.3.7-dev** : Proceed to **Path A (Quantitative)**. +- **If AGP \>= 9.3.0** : Proceed to **Path A (Standalone Task)**. -- **If R8 \< 9.3.7-dev** : Proceed to **Path B (Heuristic)**. +- **If AGP \< 9.3.0 and R8 \>= 9.3.7-dev** : Proceed to **Path B (Quantitative)**. -### Path A: Quantitative data generation (R8 \>= 9.3.7-dev) +- If none of the conditions are met, proceed to **Path C (Heuristic)**. -- **Check requirements** : Python and `protobuf` package are mandatory. -- **Generate and analyze** : You MUST run the shell commands described in [references/CONFIGURATION-ANALYZER.md](references/CONFIGURATION-ANALYZER.md) to generate the proto file using R8 configuration analyzer, convert it to json and analyze the result. -- **Report** : Rely entirely on the generated file `analysis.txt` for scores and rule impact metrics. Proceed to Step 3. +### Path A: Standalone Gradle task (AGP \>= 9.3.0) -### Path B: Heuristic evaluation and recommendation (R8 \< 9.3.7-dev) +- **Step 1: Run standalone task** : Run `./gradlew :app:analyzeReleaseR8Config` to evaluate the R8 configuration. You MUST wait for this command to finish before proceeding. +- **Step 2: Convert to JSON** : The report is generated at `app/build/reports/r8/r8-config-analyzer-release.pb`. You MUST explicitly run the conversion script by executing: `python3 .agents/skills/r8-analyzer/scripts/convert_pb_to_json.py`. Wait for this command to finish. +- **Step 3: Analyze** : You MUST explicitly run the analysis script by executing: `python3 .agents/skills/r8-analyzer/scripts/analyze.py`. This outputs `tmp/keepradius/analysis_result.txt`. Wait for this command to finish. + +### Path B: Quantitative data generation (R8 \>= 9.3.7-dev and AGP \< 9.3.0) + +- **Step 1: Check requirements** : Python and `protobuf` package are mandatory. +- **Step 2: Generate and analyze** : You MUST run the shell commands described in [references/CONFIGURATION-ANALYZER.md](references/CONFIGURATION-ANALYZER.md) to generate the proto file using R8 configuration analyzer, convert it to JSON and analyze the result. +- **Step 3: Analyze** : You MUST ensure the analysis produces `tmp/keepradius/analysis_result.txt` for scores and rule impact metrics. + +### Path C: Heuristic evaluation and recommendation (R8 \< 9.3.7-dev) *(Use ONLY if quantitative data generation is not possible)* -- **Manual evaluation** : Inspect `proguard-rules.pro`. -- **Library check** : Compare rules against [references/REDUNDANT-RULES.md](references/REDUNDANT-RULES.md). Suggest **Remove** for bundled rules. -- **Custom rule check** : Use [references/KEEP-RULES-IMPACT-HIERARCHY.md](references/KEEP-RULES-IMPACT-HIERARCHY.md) and [references/REFLECTION-GUIDE.md](references/REFLECTION-GUIDE.md) to prioritize and evaluate. Suggest **Refine** for broad rules (for example, package-wide). -- **Validation** : Suggest Macrobenchmark tests using [UI Automator](references/android/training/testing/other-components/ui-automator.md) for any proposed changes. Proceed to Step 3. +- **Step 1: Manual evaluation** : Inspect `proguard-rules.pro`. +- **Step 2: Library check** : Compare rules against [references/REDUNDANT-RULES.md](references/REDUNDANT-RULES.md). Suggest **Remove** for bundled rules. +- **Step 3: Custom rule check** : Use [references/KEEP-RULES-IMPACT-HIERARCHY.md](references/KEEP-RULES-IMPACT-HIERARCHY.md) and [references/REFLECTION-GUIDE.md](references/REFLECTION-GUIDE.md) to prioritize and evaluate. Suggest **Refine** for broad rules (for example, package-wide). +- **Step 4: Validation** : Suggest Macrobenchmark tests using [UI Automator](references/android/training/testing/other-components/ui-automator.md) for any proposed changes. Proceed to Step 3. ## Step 3. Report generation diff --git a/performance/r8-analyzer/references/CONFIGURATION-ANALYZER.md b/performance/r8-analyzer/references/CONFIGURATION-ANALYZER.md index 4039dcf..84cf3d1 100644 --- a/performance/r8-analyzer/references/CONFIGURATION-ANALYZER.md +++ b/performance/r8-analyzer/references/CONFIGURATION-ANALYZER.md @@ -6,17 +6,13 @@ On each step, keep the user informed of the progress by displaying the output. ### 2. Generate proto -The report and files must be generated at `{project_root}/tmp/r8analysis`. If -the folder is not present, create it. For example: +The report and files must be generated at `{project_root}/tmp/r8analysis`. If the folder is not present, create it. For example: mkdir -p "$PWD/tmp/r8analysis" ### 3. Remove existing files -To make sure that this invocation doesn't source data from previous runs, remove -the intermediate files `keepruleradius.json` and `analysis_result.txt` and -remove the proto files in the `{project_root}/tmp/r8analysis` folder. Example -bash commands: +To make sure that this invocation doesn't source data from previous runs, remove the intermediate files `keepruleradius.json` and `analysis_result.txt` and remove the proto files in the `{project_root}/tmp/r8analysis` folder. Example bash commands: # Remove the intermediate JSON and the directory containing protobuf files rm tmp/r8analysis/keepruleradius.json @@ -29,19 +25,14 @@ bash commands: ### 4. Generate the Configuration Analyzer report -Run the R8 enabled build with the system property -"-Dcom.android.tools.r8.dumpkeepradiustodirectory=$PWD/tmp/r8analysis" to -generate Configuration Analyzer report +Run the R8 enabled build with the system property "-Dcom.android.tools.r8.dumpkeepradiustodirectory=$PWD/tmp/r8analysis" to generate Configuration Analyzer report ./gradlew assembleRelease \ -Dcom.android.tools.r8.dumpkeepradiustodirectory=$PWD/tmp/r8analysis ### 5. Convert to JSON -To convert the generated protobuf files in `{project_root}/tmp/r8analysis` into -json, run the following script. The json must be generated in -`{project_root}/tmp/r8analysis`. Ensure `keep_radius_pb2.py` (from Step 10) is -in the same directory. +To convert the generated protobuf files in `{project_root}/tmp/r8analysis` into json, run the following script. The json must be generated in `{project_root}/tmp/r8analysis`. Ensure `keep_radius_pb2.py` (from Step 10) is in the same directory. import sys import os @@ -93,8 +84,7 @@ in the same directory. ### 6. Analyze -Run the following analysis script on the generated JSON to get the impact of the -keep rules and sort it. +Run the following analysis script on the generated JSON to get the impact of the keep rules and sort it. import json, sys @@ -150,8 +140,7 @@ Outputs `analysis_result.txt` containing scores and rule impacts. ### 7. Report impactful rules -Identify the keep rules with the highest impact and the subsumed rules using the -following script. +Identify the keep rules with the highest impact and the subsumed rules using the following script. import json, sys @@ -198,27 +187,22 @@ following script. if __name__ == "__main__": report("tmp/r8analysis/keepruleradius.json") -Add this data to the `analysis_result.txt` with the top impactful rules and -subsumed rules. +Add this data to the `analysis_result.txt` with the top impactful rules and subsumed rules. ### 8. Compare with previous report -If `{project_root}/tmp/r8analysis/history.txt` exists, use the following script -to compare the previous run. Use this to compare with the current values +If `{project_root}/tmp/r8analysis/history.txt` exists, use the following script to compare the previous run. Use this to compare with the current values ### 9. Remove generated files -After the final report and analysis results are generated, remove the -intermediate files `keepruleradius.json` and `analysis_result.txt` and remove -the proto files in "{project_root}/tmp/r8analysis" folder +After the final report and analysis results are generated, remove the intermediate files `keepruleradius.json` and `analysis_result.txt` and remove the proto files in "{project_root}/tmp/r8analysis" folder rm tmp/r8analysis/keepruleradius.json rm tmp/r8analysis/*.pb ### 10. Protobuf Python bindings -The following script `keep_radius_pb2.py` is required by the conversion script -in Step 5. +The following script `keep_radius_pb2.py` is required by the conversion script in Step 5. from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool diff --git a/performance/r8-analyzer/references/CONFIGURATION.md b/performance/r8-analyzer/references/CONFIGURATION.md index ae04947..81263a9 100644 --- a/performance/r8-analyzer/references/CONFIGURATION.md +++ b/performance/r8-analyzer/references/CONFIGURATION.md @@ -1,12 +1,8 @@ -To achieve maximum utilization of R8, the codebase must be configured correctly -depending on the build script language (Kotlin DSL versus Groovy DSL). +To achieve maximum utilization of R8, the codebase must be configured correctly depending on the build script language (Kotlin DSL versus Groovy DSL). ## 1. App Modules (`com.android.application`) -The app's `build.gradle` or `build.gradle.kts` file must enable minification -and resource shrinking within the `release` build type or the apps custom build -type for release and performance testing. It MUST use the optimized default file -(`proguard-android-optimize.txt`). +The app's `build.gradle` or `build.gradle.kts` file must enable minification and resource shrinking within the `release` build type or the apps custom build type for release and performance testing. It MUST use the optimized default file (`proguard-android-optimize.txt`). **Kotlin DSL (`build.gradle.kts`):** @@ -38,7 +34,6 @@ type for release and performance testing. It MUST use the optimized default file - **AGP 8.0+** : Enabled by default. Ensure `android.enableR8.fullMode=false` is **NOT** present. - **Pre-AGP 8.0** : Explicitly enable with `android.enableR8.fullMode=true`. -**Optimized Resource Shrinking:** If the AGP version of the project is less than -9.0 and more than 8.6, explicitly enable the new resource shrinker: +**Optimized Resource Shrinking:** If the AGP version of the project is less than 9.0 and more than 8.6, explicitly enable the new resource shrinker: android.r8.optimizedResourceShrinking=true \ No newline at end of file diff --git a/performance/r8-analyzer/references/KEEP-RULES-IMPACT-HIERARCHY.md b/performance/r8-analyzer/references/KEEP-RULES-IMPACT-HIERARCHY.md index 2e07317..c01a9be 100644 --- a/performance/r8-analyzer/references/KEEP-RULES-IMPACT-HIERARCHY.md +++ b/performance/r8-analyzer/references/KEEP-RULES-IMPACT-HIERARCHY.md @@ -1,53 +1,38 @@ -Keep rules prevent optimization of R8, these rules are listed in the order of -the scope of what it retains in the codebase. +Keep rules prevent optimization of R8, these rules are listed in the order of the scope of what it retains in the codebase. ## 1. Package-Wide Wildcards -The following types of keep rules prevents all the optimization of R8 in a -package, these must be avoided at any costs and must be refined to target a -specific class or classes. +The following types of keep rules prevents all the optimization of R8 in a package, these must be avoided at any costs and must be refined to target a specific class or classes. -keep class com.example.package.** { *; } - Prevents optimization of all the classess including members in the package and subpackages -keep class com.example.package.* { *; } - Prevents optimization of all the classes including members in the package -keep class **.package.** { *; } - Prevents optimization of all the classess including members in all the package containing name - package. -Depending on the package level the number of classes gets affected changes, so -if the package level is higher, more classes are affected. Suggest to refine -the keep rule +Depending on the package level the number of classes gets affected changes, so if the package level is higher, more classes are affected. Suggest to refine the keep rule ## 2. Inversion operator -Avoid using the inversion operator ! in keep rules because it will -unintentionally prevent optimization in every class in your application. So if -you have any keep rule with !operator, make sure you remove that with a narrow -and specific keep rule +Avoid using the inversion operator ! in keep rules because it will unintentionally prevent optimization in every class in your application. So if you have any keep rule with !operator, make sure you remove that with a narrow and specific keep rule -keep class !com.example.MyClass{*;} -This keeps the entire app -other than this class. Optimization are disabled for the entire class other -than this class. +This keeps the entire app other than this class. Optimization are disabled for the entire class other than this class. ## 3. Keep Rules for both class and members -Keep rules with -keep option and wildcard(`*`) inside braces forces R8 to retain -specific classes and their members exactly as defined. These type of keep rules -prevent any optimization in the entire class and keeps the entire class +Keep rules with -keep option and wildcard(`*`) inside braces forces R8 to retain specific classes and their members exactly as defined. These type of keep rules prevent any optimization in the entire class and keeps the entire class -keep class com.example.MyClass { *; } ## 4. Keepclassmembers -Keep rules with -keepclassmembers and wildcard(`*`) inside braces option Forces -R8 to retain the members that are defined. +Keep rules with -keepclassmembers and wildcard(`*`) inside braces option Forces R8 to retain the members that are defined. -keepclassmembers class com.example.MyClass { *; } ## 5. Modifiers with Keep Specification --Keeps the class and **all** members, but uses modifiers to allow specific -optimizations (like obfuscation). Retains significant code (members) but allows -some flexibility. +-Keeps the class and **all** members, but uses modifiers to allow specific optimizations (like obfuscation). Retains significant code (members) but allows some flexibility. -keep,allowobfuscation class com.example.MyClass { *; } -keep,allowshrinking class com.example.MyClass { *; } @@ -60,15 +45,13 @@ Keeps the class and modifier but no optimizations are enabled ## 7. Class-Name Only Preservation -Keeps only the class name. R8 will remove all methods and fields if they are not -used. +Keeps only the class name. R8 will remove all methods and fields if they are not used. -keep class com.example.MyClass ## 8. Modifiers without Member Specification -Keeps the class entry point using modifiers, but implies no specific member -retention logic in the rule itself +Keeps the class entry point using modifiers, but implies no specific member retention logic in the rule itself -keep,allowobfuscation class com.example.MyClass -keep,allowshrinking class com.example.MyClass @@ -76,8 +59,7 @@ retention logic in the rule itself ## 9. Conditional Keep Rules -Only triggers if specific conditions are met (e.g., if class members exist). -These are the most narrow and optimization-friendly rules. +Only triggers if specific conditions are met (e.g., if class members exist). These are the most narrow and optimization-friendly rules. -keepclassmembers class com.example.MyClass { ; } -keepclasseswithmembers class * { native ; } \ No newline at end of file diff --git a/performance/r8-analyzer/references/REDUNDANT-RULES.md b/performance/r8-analyzer/references/REDUNDANT-RULES.md index 0021890..0bfe0e2 100644 --- a/performance/r8-analyzer/references/REDUNDANT-RULES.md +++ b/performance/r8-analyzer/references/REDUNDANT-RULES.md @@ -1,36 +1,20 @@ -This document outlines common "bad" or redundant keep rules for standard Android -development and popular libraries. Modern toolchains and libraries include their -own consumer keep rules embedded in their AAR/JAR files, making many manual -configurations unnecessary or even harmful to code optimization. +This document outlines common "bad" or redundant keep rules for standard Android development and popular libraries. Modern toolchains and libraries include their own consumer keep rules embedded in their AAR/JAR files, making many manual configurations unnecessary or even harmful to code optimization. *** ** * ** *** ## Case: Global Keep Rules -**Common Mistakes:** -`proguard --dontshrink --dontobfuscate --dontoptimize` +**Common Mistakes:** `proguard -dontshrink -dontobfuscate -dontoptimize` -**The Fix:** These keep rules completely disable the core optimizations of R8 -for the entire codebase. They must be removed from the codebase. +**The Fix:** These keep rules completely disable the core optimizations of R8 for the entire codebase. They must be removed from the codebase. *** ** * ** *** ## Case: Android Components -Keep rules required for Android components like Activity, Fragment, ViewModel, -Views, Services or Broadcast receivers are redundant. AAPT2 and R8 contain the -logic to automatically keep components declared in the `AndroidManifest.xml` or -referenced in XML layout files. +Keep rules required for Android components like Activity, Fragment, ViewModel, Views, Services or Broadcast receivers are redundant. AAPT2 and R8 contain the logic to automatically keep components declared in the `AndroidManifest.xml` or referenced in XML layout files. -**Common Mistakes:** -`proguard --keep public class * extends android.app.Activity --keep public class * extends android.app.Service --keep public class * extends android.view.View --keepclassmembers class * extends android.app.Fragment { public void *(android.view.View); }` +**Common Mistakes:** `proguard -keep public class * extends android.app.Activity -keep public class * extends android.app.Service -keep public class * extends android.view.View -keepclassmembers class * extends android.app.Fragment { public void *(android.view.View); }` **The Fix:** Delete these manual rules. AAPT2 handles this automatically. @@ -38,18 +22,11 @@ referenced in XML layout files. ## Case: Official Android and Kotlin Libraries -Keep rules targeting official library packages like AndroidX, Kotlin, and -Kotlinx are redundant as they are bundled within the libraries themselves. -Manual rules are often broader than what is strictly needed. +Keep rules targeting official library packages like AndroidX, Kotlin, and Kotlinx are redundant as they are bundled within the libraries themselves. Manual rules are often broader than what is strictly needed. -**Common Mistakes:** -`proguard --keep class androidx.** { *; } --keep class kotlinx.** { *; } --keep class kotlin.** { *; }` +**Common Mistakes:** `proguard -keep class androidx.** { *; } -keep class kotlinx.** { *; } -keep class kotlin.** { *; }` -**The Fix:** Delete these manual rules. Rely on the consumer keep rules packaged -within these dependencies. +**The Fix:** Delete these manual rules. Rely on the consumer keep rules packaged within these dependencies. *** ** * ** *** @@ -57,18 +34,14 @@ within these dependencies. ### Overly Broad Data Model Rules -The most common mistake is keeping entire packages of data models (POJOs/DTOs), -keeping data models at all for deserialization is unnecessary. +The most common mistake is keeping entire packages of data models (POJOs/DTOs), keeping data models at all for deserialization is unnecessary. -keep class com.example.app.models.** { *; } -keep class com.example.app.package.models.* { *; } ### Redundant Interface \& Adapter Rules -These rules added for TypeAdapter are unnecessary and are already covered by -the library, and prevent R8 from effectively shrinking and optimizing custom -adapters. R8 can determine if the adapter implementation are used. Keeping them -globally prevents the removal of unused adapter implementations. +These rules added for TypeAdapter are unnecessary and are already covered by the library, and prevent R8 from effectively shrinking and optimizing custom adapters. R8 can determine if the adapter implementation are used. Keeping them globally prevents the removal of unused adapter implementations. -keep class * extends com.google.gson.TypeAdapter -keep class * implements com.google.gson.TypeAdapterFactory @@ -77,8 +50,7 @@ globally prevents the removal of unused adapter implementations. ### Unnecessary TypeToken Rules -There is no need to handle generic type erasure, Gson's own rules handle the -necessary `TypeToken` preservation. +There is no need to handle generic type erasure, Gson's own rules handle the necessary `TypeToken` preservation. -keep class com.google.gson.reflect.TypeToken { *; } -keep class * extends com.google.gson.reflect.TypeToken @@ -86,8 +58,7 @@ necessary `TypeToken` preservation. ### Internal and Example Packages -Keeping internal library logic prevents the compiler from stripping away dead -code within the library. +Keeping internal library logic prevents the compiler from stripping away dead code within the library. -keep class com.google.gson.internal.** { *; } -keep class com.google.gson.internal.reflect.** { *; } @@ -101,22 +72,17 @@ code within the library. **The Fix:** 1. Use `@SerializedName` on every field in your data classes uses so that the field is retained after R8 optimization -2. Modern Gson (**v2.11.0+** ) bundles its own rules ([View Gson's embedded - ProGuard - rules](https://github.com/google/gson/blob/main/gson/src/main/resources/META-INF/proguard/gson.pro)). The bundled keep rules retains the `@SerializedName` annotated fields. If you are on an older version, move towards Gson version 2.11 because it has the necessary keep rules and delete the keep rules that target the classes used for gson serialization and deserialization +2. Modern Gson (**v2.11.0+** ) bundles its own rules ([View Gson's embedded ProGuard rules](https://github.com/google/gson/blob/main/gson/src/main/resources/META-INF/proguard/gson.pro)). The bundled keep rules retains the `@SerializedName` annotated fields. If you are on an older version, move towards Gson version 2.11 because it has the necessary keep rules and delete the keep rules that target the classes used for gson serialization and deserialization *** ** * ** *** ## Case: Retrofit -Retrofit has shipped with its own consumer keep rules from 2.9.0 and higher, so -any keep rules for the library or classes depending on Retrofit is detrimental -to the optimization process. +Retrofit has shipped with its own consumer keep rules from 2.9.0 and higher, so any keep rules for the library or classes depending on Retrofit is detrimental to the optimization process. ### Blanket Library Preservation -This is the most harmful Retrofit rule as it disables any shrinking for the -entire library. +This is the most harmful Retrofit rule as it disables any shrinking for the entire library. -keep class retrofit2.** { *; } -keep class retrofit2.api.** { *; } @@ -124,70 +90,54 @@ entire library. ### Manual Annotation Keeps -Retrofit's consumer rules automatically keep the interfaces annotated with -`@GET`, `@POST`, `@DELETE`, `@PUT`, `@HEAD`, `@OPTIONS`, `@PATCH`, making these -manual rules obsolete. +Retrofit's consumer rules automatically keep the interfaces annotated with `@GET`, `@POST`, `@DELETE`, `@PUT`, `@HEAD`, `@OPTIONS`, `@PATCH`, making these manual rules obsolete. `-keepclasseswithmembers class * { @retrofit2.http.* ; }` ### Redundant Network Response and Adapter Rules -Network responses and third-party adapter wrappers (like RxJava) are often -overly preserved by developers out of caution. +Network responses and third-party adapter wrappers (like RxJava) are often overly preserved by developers out of caution. -keep,allowobfuscation,allowshrinking class retrofit2.Response -keep class retrofit2.adapter.rxjava2.Result { *; } -Fix: Verify you are using Retrofit 2.9.0 and higher. Retrofit from 2.9.0 bundles -rules that detect its own HTTP annotations (@GET, @POST) ([View Retrofit's -embedded ProGuard -rules](https://github.com/square/retrofit/blob/master/retrofit/src/main/resources/META-INF/proguard/retrofit2.pro)). -It will automatically keep the method signatures it needs to work. +Fix: Verify you are using Retrofit 2.9.0 and higher. Retrofit from 2.9.0 bundles rules that detect its own HTTP annotations (@GET, @POST) ([View Retrofit's embedded ProGuard rules](https://github.com/square/retrofit/blob/master/retrofit/src/main/resources/META-INF/proguard/retrofit2.pro)). It will automatically keep the method signatures it needs to work. *** ** * ** *** ## Case: Kotlin Coroutines -Kotlin Coroutines comes heavily optimized out of the box with embedded R8 rules -(`kotlinx-coroutines-core` includes its own rules). +Kotlin Coroutines comes heavily optimized out of the box with embedded R8 rules (`kotlinx-coroutines-core` includes its own rules). ### Blanket Coroutine Library Rules -Keeping everything under `kotlinx.coroutines` is extremely detrimental to app -size, as coroutines contain a vast amount of internal APIs that aren't used. +Keeping everything under `kotlinx.coroutines` is extremely detrimental to app size, as coroutines contain a vast amount of internal APIs that aren't used. `-keepclassmembers class kotlinx.coroutines.** { *; }` ### Redundant Internal Continuations -These low-level coroutine elements are preserved safely by the library's own -consumer rules. Manually adding these prevents R8 from performing internal -optimizations (such as removing unused continuations or inlining). +These low-level coroutine elements are preserved safely by the library's own consumer rules. Manually adding these prevents R8 from performing internal optimizations (such as removing unused continuations or inlining). -keepclassmembers class kotlin.coroutines.SafeContinuation { *; } -keep,allowobfuscation,allowshrinking class kotlin.coroutines.Continuation ### Dispatcher and Exception Handler Rules -Sometimes developers notice crashes related to Missing Classes on old Android -versions and add these rules, but if you are using an up-to-date version of -Coroutines, these are handled automatically or are not an issue. +Sometimes developers notice crashes related to Missing Classes on old Android versions and add these rules, but if you are using an up-to-date version of Coroutines, these are handled automatically or are not an issue. -keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {} -keepnames class kotlinx.coroutines.CoroutineExceptionHandler {} -keepnames class kotlinx.coroutines.android.AndroidExceptionPreHandler {} -keepnames class kotlinx.coroutines.android.AndroidDispatcherFactory {} -**Fix** Remove any broad `kotlinx` keep rules. Coroutines (**v1.7.0+** ) bundle -the necessary keep rules ([View Coroutines' embedded ProGuard -rules](https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/jvm/resources/META-INF/proguard/coroutines.pro)). +**Fix** Remove any broad `kotlinx` keep rules. Coroutines (**v1.7.0+** ) bundle the necessary keep rules ([View Coroutines' embedded ProGuard rules](https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/jvm/resources/META-INF/proguard/coroutines.pro)). *** ** * ** *** ## Case: Parcelable -**Common Mistakes:** Legacy projects often contain `-keep class * implements -android.os.Parcelable { public static final android.os.Parcelable$Creator *; }`. +**Common Mistakes:** Legacy projects often contain `-keep class * implements android.os.Parcelable { public static final android.os.Parcelable$Creator *; }`. **The Fix:** @@ -201,15 +151,12 @@ android.os.Parcelable { public static final android.os.Parcelable$Creator *; }`. ## Case: Room Database -**Common Mistakes:** Keeping DAO interfaces or the generated `_Impl` classes -manually. +**Common Mistakes:** Keeping DAO interfaces or the generated `_Impl` classes manually. -keep class * extends androidx.room.RoomDatabase -keep class *_*Impl { *; } -**The Fix:** Room generates its own ProGuard rules for the code it creates. -Manual rules are redundant and prevent R8 from optimizing the database access -layers. +**The Fix:** Room generates its own ProGuard rules for the code it creates. Manual rules are redundant and prevent R8 from optimizing the database access layers. - **Ideal Rule:** **None.** Delete all manual Room or DAO keeps. @@ -217,6 +164,4 @@ layers. ## Summary -If you have updated your libraries to the versions mentioned, your -`proguard-rules.pro` must not contain any keep rules for the libraries -mentioned here. \ No newline at end of file +If you have updated your libraries to the versions mentioned, your `proguard-rules.pro` must not contain any keep rules for the libraries mentioned here. \ No newline at end of file diff --git a/performance/r8-analyzer/references/REFLECTION-GUIDE.md b/performance/r8-analyzer/references/REFLECTION-GUIDE.md index 8f23679..dd1cca5 100644 --- a/performance/r8-analyzer/references/REFLECTION-GUIDE.md +++ b/performance/r8-analyzer/references/REFLECTION-GUIDE.md @@ -1,139 +1,81 @@ -A categorized summary of the keep rule examples, including the code patterns to -look for (imports/usage) and the corresponding suggested rules. +A categorized summary of the keep rule examples, including the code patterns to look for (imports/usage) and the corresponding suggested rules. ### 1. Reflection: Classes Loaded by Name **Scenario:** A library or app loads a class dynamically using a string name -- **Look for:** - `Class.forName("...")`, - `getDeclaredConstructor().newInstance()`, or interfaces used for dynamic loading. +- **Look for:** `Class.forName("...")`, `getDeclaredConstructor().newInstance()`, or interfaces used for dynamic loading. -- **Example Code:** - `kotlin - val taskClass = Class.forName(className) - val task = taskClass.getDeclaredConstructor().newInstance() as StartupTask` +- **Example Code:** `kotlin val taskClass = Class.forName(className) val task = taskClass.getDeclaredConstructor().newInstance() as StartupTask` -- **Suggested Keep Rule:** - \`\`\`proguard +- **Suggested Keep Rule:** \`\`\`proguard - -keep class \* implements com.example.library.StartupTask { - (); } \`\`\` + -keep class \* implements com.example.library.StartupTask { (); } \`\`\` ### 2. Reflection: Classes Passed using `::class.java` **Scenario:** An app passes a class reference directly to a library function. - **Look for:** `::class.java` (Kotlin) or `.class` (Java) passed as an argument. -- **Example Code:** - `kotlin - fun register(clazz: Class) { } - // Usage: - register(MyService::class.java)` +- **Example Code:** `kotlin fun register(clazz: Class) { } // Usage: register(MyService::class.java)` -- **Suggested Keep Rule:** - \`\`\`proguard +- **Suggested Keep Rule:** \`\`\`proguard # Keep the class itself (R8 usually handles this, but explicit rules ensure stability) - -keep class com.example.app.MyService { - (); } \`\`\` + -keep class com.example.app.MyService { (); } \`\`\` ### 3. Annotation-Based Reflection (Methods/Classes) -**Scenario:** Using custom annotations to mark methods or classes for reflective -execution. +**Scenario:** Using custom annotations to mark methods or classes for reflective execution. -**Look for:** Custom `@interface` definitions and `getDeclaredMethods()` -filtered by annotation. -**Example Code:** -`kotlin -annotation class ReflectiveExecutor -// Logic: find methods annotated with @ReflectiveExecutor and invoke them` +**Look for:** Custom `@interface` definitions and `getDeclaredMethods()` filtered by annotation. **Example Code:** `kotlin annotation class ReflectiveExecutor // Logic: find methods annotated with @ReflectiveExecutor and invoke them` - **Suggested Keep Rule:** \`\`\`proguard # Keep the annotation itself -keep @interface com.example.library.ReflectiveExecutor -# Keep members of any class annotated with this specific annotation --keepclassmembers class \* { -@com.example.library.ReflectiveExecutor \*; -} -\`\`\` +# Keep members of any class annotated with this specific annotation -keepclassmembers class \* { @com.example.library.ReflectiveExecutor \*; } \`\`\` ### 4. Optional Dependencies (Soft Dependencies) -**Scenario:** A core library checks if an optional module is present in the -classpath. +**Scenario:** A core library checks if an optional module is present in the classpath. - **Look for:** `try-catch` blocks around `Class.forName()` used to toggle features. - **Example Code:** \`\`\`kotlin private const val VIDEO_TRACKER_CLASS = "com.example.analytics.video.VideoEventTracker" -try { -Class.forName(VIDEO_TRACKER_CLASS).getDeclaredConstructor().newInstance() -} catch (e: ClassNotFoundException) { /\* skip feature \*/ } -\`\`\` +try { Class.forName(VIDEO_TRACKER_CLASS).getDeclaredConstructor().newInstance() } catch (e: ClassNotFoundException) { /\* skip feature \*/ } \`\`\` -- **Suggested Keep Rule:** `proguard - # Preserve the optional class so the check doesn't fail due to shrinking - -keep class com.example.analytics.video.VideoEventTracker { - (); - }` +- **Suggested Keep Rule:** `proguard # Preserve the optional class so the check doesn't fail due to shrinking -keep class com.example.analytics.video.VideoEventTracker { (); }` ### 5. Accessing Private Members -**Scenario:** Using reflection to access internal fields or methods not exposed -with public APIs. +**Scenario:** Using reflection to access internal fields or methods not exposed with public APIs. - **Look for:** `getDeclaredField("...")` or `getDeclaredMethod("...")` followed by `isAccessible = true`. -- **Example Code:** - `kotlin - val secretField = instance::class.java.getDeclaredField("secretMessage") - secretField.isAccessible = true` +- **Example Code:** `kotlin val secretField = instance::class.java.getDeclaredField("secretMessage") secretField.isAccessible = true` -- **Suggested Keep Rule:** - \`\`\`proguard +- **Suggested Keep Rule:** \`\`\`proguard # Specifically keep the private field/method by name and type - -keepclassmembers class com.example.LibraryClass { - private java.lang.String secretMessage; - } - \`\`\` + -keepclassmembers class com.example.LibraryClass { private java.lang.String secretMessage; } \`\`\` ### 6. Parcelable (Manual Implementation) -**Scenario:** Implementing `Parcelable` without using the `@Parcelize` -annotation. +**Scenario:** Implementing `Parcelable` without using the `@Parcelize` annotation. - **Look for:** `implements Parcelable` and a static `CREATOR` field. -- **Example Code:** - `kotlin - class MyData : Parcelable { - // Manual implementation with CREATOR field - }` +- **Example Code:** `kotlin class MyData : Parcelable { // Manual implementation with CREATOR field }` -- **Suggested Keep Rule:** - *(Note: If using `import kotlinx.parcelize.Parcelize`, R8/ProGuard rules are - generated automatically. If manual, use the following:)* - `proguard - -keepclassmembers class * implements android.os.Parcelable { - static android.os.Parcelable$Creator CREATOR; - }` +- **Suggested Keep Rule:** *(Note: If using `import kotlinx.parcelize.Parcelize`, R8/ProGuard rules are generated automatically. If manual, use the following:)* `proguard -keepclassmembers class * implements android.os.Parcelable { static android.os.Parcelable$Creator CREATOR; }` ### 7. Enums and Obfuscation -**Scenario:** App uses `Enum.valueOf("STRING_NAME")` indirectly (e.g.,using JSON -deserialization) and the enum names get obfuscated. +**Scenario:** App uses `Enum.valueOf("STRING_NAME")` indirectly (e.g.,using JSON deserialization) and the enum names get obfuscated. - **Look for:** Unnecessary generic Enum keep rules in ProGuard files. -- **Example Code:** - \`\`\`proguard +- **Example Code:** \`\`\`proguard # Unnecessary rule - -keepclassmembers enum \* { \*; } - \`\`\` -- **Suggested Keep Rule:** - \*(Note: The default `proguard-android-optimize.txt` already contains the optimal - rules for Enums (keeping `values()` and `valueOf(String)`). Any additional - manual rules for Enums are redundant.) # No manual rule needed. Use default - proguard-android-optimize.txt. \ No newline at end of file + -keepclassmembers enum \* { \*; } \`\`\` +- **Suggested Keep Rule:** \*(Note: The default `proguard-android-optimize.txt` already contains the optimal rules for Enums (keeping `values()` and `valueOf(String)`). Any additional manual rules for Enums are redundant.) # No manual rule needed. Use default proguard-android-optimize.txt. \ No newline at end of file diff --git a/performance/r8-analyzer/references/REPORT_FORMAT.md b/performance/r8-analyzer/references/REPORT_FORMAT.md index 629c777..3527b6d 100644 --- a/performance/r8-analyzer/references/REPORT_FORMAT.md +++ b/performance/r8-analyzer/references/REPORT_FORMAT.md @@ -11,8 +11,7 @@ - \[Rule\]: Disables R8 globally. **Action**: Remove. -If there is -dontobfuscate, -dontoptimize or -dontshrink in the codebase, -mention in this section +If there is -dontobfuscate, -dontoptimize or -dontshrink in the codebase, mention in this section ## 3. Optimization summary @@ -20,8 +19,7 @@ mention in this section - **Shrinking score**: \[X\]% of code will be optimized by R8 by removing unused classes, fields and methods. \[100-X\]% of codebase contains redundant classes, fields and methods that can't be removed by R8. - **Obfuscation score**: \[X\]% of the codebase is available for R8 to obfuscate. -Increasing these scores increases the codebase available to R8 for -optimizations. +Increasing these scores increases the codebase available to R8 for optimizations. ## 4. Keep rules evaluation @@ -42,10 +40,4 @@ optimizations. ## 6. Historical analysis summary -*(Only include this section if a previous report existed. Summarize the changes -in optimization scores here to track progress. For example:)* The previous app -had scores: Optimization (XX%), Obfuscation (XX%), and Shrinking (XX%). The -current app has scores: Optimization (YY%), Obfuscation (YY%), and Shrinking -(YY%). -**Change**: Optimization improved by ZZ%, Obfuscation improved by ZZ%, and -Shrinking improved by ZZ%. \ No newline at end of file +*(Only include this section if a previous report existed. Summarize the changes in optimization scores here to track progress. For example:)* The previous app had scores: Optimization (XX%), Obfuscation (XX%), and Shrinking (XX%). The current app has scores: Optimization (YY%), Obfuscation (YY%), and Shrinking (YY%). **Change**: Optimization improved by ZZ%, Obfuscation improved by ZZ%, and Shrinking improved by ZZ%. \ No newline at end of file diff --git a/performance/r8-analyzer/references/android/topic/performance/app-optimization/enable-app-optimization.md b/performance/r8-analyzer/references/android/topic/performance/app-optimization/enable-app-optimization.md index a80f19d..95c82e3 100644 --- a/performance/r8-analyzer/references/android/topic/performance/app-optimization/enable-app-optimization.md +++ b/performance/r8-analyzer/references/android/topic/performance/app-optimization/enable-app-optimization.md @@ -1,7 +1,18 @@ -For the best user experience, you should optimize your app to make it as small -and fast as possible. Our app optimizer, called R8, streamlines your app by -removing unused code and resources, rewriting code to optimize runtime -performance, and more. To your users, this means: +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/performance/r8-analyzer) + +### R8 Analyzer + +Use the R8 Analyzer [Android skill](https://developer.android.com/tools/agents/android-skills) to analyze build files and identify redundant, broad, or subsumed [keep rules](https://developer.android.com/topic/performance/app-optimization/keep-rules-overview). To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill r8-analyzer + +
+ +For the best user experience, you should optimize your app to make it as small and fast as possible. Our app optimizer, called R8, streamlines your app by removing unused code and resources, rewriting code to optimize runtime performance, and more. To your users, this means: - Faster startup time - Reduced memory usage @@ -9,49 +20,27 @@ performance, and more. To your users, this means: - Fewer [ANRs](https://developer.android.com/topic/performance/anrs/keep-your-app-responsive) > [!IMPORTANT] -> **Important:** You should always enable optimization for your app's release build; however, you probably don't want to enable it for tests or libraries. For more information about using R8 with tests, see [Test and troubleshoot the -> optimization](https://developer.android.com/topic/performance/app-optimization/test-and-troubleshoot-the-optimization). For more information about enabling R8 from libraries, see [Optimization for library authors](https://developer.android.com/topic/performance/app-optimization/library-optimization). - -> [!IMPORTANT] -> **Important:** We released an agent skill that you can use to improve your app performance with R8. Try out the skill from the [Android skills repository](https://github.com/android/skills). +> **Important:** You should always enable optimization for your app's release build; however, you probably don't want to enable it for tests or libraries. For more information about using R8 with tests, see [Test and troubleshoot the optimization](https://developer.android.com/topic/performance/app-optimization/test-and-troubleshoot-the-optimization). For more information about enabling R8 from libraries, see [Optimization for library authors](https://developer.android.com/topic/performance/app-optimization/library-optimization). ## R8 optimization overview -R8 uses a multi-phase process to optimize your app for size and speed. Key -operations include the following: +R8 uses a multi-phase process to optimize your app for size and speed. Key operations include the following: -- **Code shrinking (also known as tree shaking)** : R8 identifies and removes - unreachable code from your application and its library dependencies. By - analyzing the entry points of your app (such as `Activities` or `Services` - defined in the manifest), R8 builds a graph of referenced code and removes - anything that remains unreferenced. +- **Code shrinking (also known as tree shaking)** : R8 identifies and removes unreachable code from your application and its library dependencies. By analyzing the entry points of your app (such as `Activities` or `Services` defined in the manifest), R8 builds a graph of referenced code and removes anything that remains unreferenced. -- **Logical optimizations**: R8 rewrites your code to improve execution - efficiency and reduce overhead. Key techniques include: +- **Logical optimizations**: R8 rewrites your code to improve execution efficiency and reduce overhead. Key techniques include: - - **Method inlining**: R8 replaces a method call site with the actual body - of the called method. This eliminates the overhead of a function call - and lets R8 conduct further optimizations. + - **Method inlining**: R8 replaces a method call site with the actual body of the called method. This eliminates the overhead of a function call and lets R8 conduct further optimizations. - - **Class merging**: R8 combines sets of classes and interfaces into a - single class. This reduces the number of classes in the app, lowering - memory pressure and improving startup speed. + - **Class merging**: R8 combines sets of classes and interfaces into a single class. This reduces the number of classes in the app, lowering memory pressure and improving startup speed. -- **Obfuscation (also known as minification)** : To reduce the size of the DEX - file, R8 shortens the names of classes, fields, and methods (for example, - `com.example.MyActivity` could become `a.b.a`). +- **Obfuscation (also known as minification)** : To reduce the size of the DEX file, R8 shortens the names of classes, fields, and methods (for example, `com.example.MyActivity` could become `a.b.a`). -Since 8.12.0 version of Android Gradle Plugin (AGP), R8 also optimizes resources -as part of its optimization phases. For more information, see [Optimized -resource shrinking](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization#optimize-resource-shrinking). +Since 8.12.0 version of Android Gradle Plugin (AGP), R8 also optimizes resources as part of its optimization phases. For more information, see [Optimized resource shrinking](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization#optimize-resource-shrinking). ## Enable optimization -To enable app optimization for your app use the appropriate DSL based on your -project's AGP version. We recommend enabling app optimization only in the final -version of your app that you test before publishing---usually your release -build---because the optimizations increase the build time of your project and can -make debugging harder due to the way it modifies code. +To enable app optimization for your app use the appropriate DSL based on your project's AGP version. We recommend enabling app optimization only in the final version of your app that you test before publishing---usually your release build---because the optimizations increase the build time of your project and can make debugging harder due to the way it modifies code. ### For AGP versions 9.3 and higher @@ -61,8 +50,7 @@ To enable app optimization for AGP 9.3 and higher: - Add your [keep rules](https://developer.android.com/topic/performance/app-optimization/add-keep-rules) to a file with the suffix `.keep` in the `src//keepRules` source set. For example, `src/main/keepRules/custom-rules.keep`. > [!NOTE] -> **Note:** The updated DSL enables both code and resource optimization. It also includes a set of default keep rules for the Android platform, equivalent to "proguard-android-optimize.txt". To omit the default rules, see [Omit default -> rules](https://developer.android.com/topic/performance/app-optimization/keep-rules-overview#omit-default). +> **Note:** The updated DSL enables both code and resource optimization. It also includes a set of default keep rules for the Android platform, equivalent to "proguard-android-optimize.txt". To omit the default rules, see [Omit default rules](https://developer.android.com/topic/performance/app-optimization/keep-rules-overview#omit-default). ### Kotlin @@ -90,10 +78,7 @@ To enable app optimization for AGP 9.3 and higher: ### Legacy DSL for AGP versions lower than 9.3 -To enable app optimization, set `isMinifyEnabled = true` (for code optimization) -and `isShrinkResources = true` (for resource optimization) in your [release -build's](https://developer.android.com/studio/publish/preparing#turn-off-debugging) app-level build script. We recommend that you always enable both -settings. +To enable app optimization, set `isMinifyEnabled = true` (for code optimization) and `isShrinkResources = true` (for resource optimization) in your [release build's](https://developer.android.com/studio/publish/preparing#turn-off-debugging) app-level build script. We recommend that you always enable both settings. ### Legacy DSL (Kotlin) @@ -141,9 +126,7 @@ settings. ## Improve R8 optimization -The performance benefits of R8 are directly correlated to how much of your -codebase R8 is able to optimize. To get the maximum benefits out of R8, follow -best practices: +The performance benefits of R8 are directly correlated to how much of your codebase R8 is able to optimize. To get the maximum benefits out of R8, follow best practices: - Enable R8 in [full mode](https://developer.android.com/topic/performance/app-optimization/full-mode) - Enable [obfuscation, optimization, and shrinking](https://developer.android.com/topic/performance/app-optimization/adopt-optimizations-incrementally) @@ -158,70 +141,48 @@ The R8 Configuration Analyzer lets you do the following: - Find the broadest keep rules - those which prevent the most optimization - and understand what optimization they prevent to refine them. -The R8 Configuration Analyzer is available in AGP version 9.3.0-alpha05 or from -R8 version 9.3.7-dev. For more information, see [Analyze R8 configuration](https://developer.android.com/topic/performance/app-optimization/r8-configuration-analyzer). +The R8 Configuration Analyzer is available in AGP version 9.3.0-alpha05 or from R8 version 9.3.7-dev. For more information, see [Analyze R8 configuration](https://developer.android.com/topic/performance/app-optimization/r8-configuration-analyzer). ## Optimize resource shrinking for even smaller apps -The 8.12.0 version of AGP introduces optimized resource shrinking, which aims to -integrate resource and code optimization to create even smaller and faster apps. -Before optimized resource shrinking, Android Asset Packaging Tool (AAPT2) -generated keep rules that effectively treating resource shrinking separately -from code, often retaining inaccessible code or resources that referenced each -other. +The 8.12.0 version of AGP introduces optimized resource shrinking, which aims to integrate resource and code optimization to create even smaller and faster apps. Before optimized resource shrinking, Android Asset Packaging Tool (AAPT2) generated keep rules that effectively treating resource shrinking separately from code, often retaining inaccessible code or resources that referenced each other. -With optimized resource shrinking, resources are considered like a part of -program code, forming the reference graph. When a collection of code or -resources is not referenced, it is not protected by a keep rule, and can be -removed. +With optimized resource shrinking, resources are considered like a part of program code, forming the reference graph. When a collection of code or resources is not referenced, it is not protected by a keep rule, and can be removed. ### Enable optimized resource shrinking -To enable the new optimized resource shrinking pipeline for AGP 8.12 or 8.13, -add the following to your project's `gradle.properties` file: +To enable the new optimized resource shrinking pipeline for AGP 8.12 or 8.13, add the following to your project's `gradle.properties` file: -If you are using AGP 9.0.0 or a newer version, you don't need to set -`android.r8.optimizedResourceShrinking=true`. Optimized resource shrinking is -automatically applied when `isShrinkResources = true` is enabled in your build -configuration. +If you are using AGP 9.0.0 or a newer version, you don't need to set `android.r8.optimizedResourceShrinking=true`. Optimized resource shrinking is automatically applied when `isShrinkResources = true` is enabled in your build configuration. ## Verify and configure R8 optimization settings -To enable R8 to use its [full optimization capabilities](https://developer.android.com/topic/performance/app-optimization/full-mode), remove the -following line from your project's `gradle.properties` file, if it exists: +To enable R8 to use its [full optimization capabilities](https://developer.android.com/topic/performance/app-optimization/full-mode), remove the following line from your project's `gradle.properties` file, if it exists: `bash android.enableR8.fullMode=false # Remove this line from your codebase.` -Note that enabling app optimization makes stack traces difficult to understand, -especially if R8 renames class or method names. To get stack traces that -correctly correspond to your source code, see [Recover the original stack -trace](https://developer.android.com/topic/performance/app-optimization/test-and-troubleshoot-the-optimization#recover-original-stack-trace). +Note that enabling app optimization makes stack traces difficult to understand, especially if R8 renames class or method names. To get stack traces that correctly correspond to your source code, see [Recover the original stack trace](https://developer.android.com/topic/performance/app-optimization/test-and-troubleshoot-the-optimization#recover-original-stack-trace). -If R8 is enabled, you should also [create Startup Profiles](https://developer.android.com/topic/performance/baselineprofiles/dex-layout-optimizations) for even better -startup performance. +If R8 is enabled, you should also [create Startup Profiles](https://developer.android.com/topic/performance/baselineprofiles/dex-layout-optimizations) for even better startup performance. -If you enable app optimization and it causes errors, here are some strategies to -fix them: +If you enable app optimization and it causes errors, here are some strategies to fix them: - [Add keep rules](https://developer.android.com/topic/performance/app-optimization/add-keep-rules) to keep some code untouched. - [Adopt optimizations incrementally](https://developer.android.com/topic/performance/app-optimization/adopt-optimizations-incrementally). -- Update your code to [use libraries that are better suited for - optimization](https://developer.android.com/topic/performance/app-optimization/choose-libraries-wisely). +- Update your code to [use libraries that are better suited for optimization](https://developer.android.com/topic/performance/app-optimization/choose-libraries-wisely). > [!CAUTION] > **Caution:** Tools that replace or modify R8's output can negatively impact runtime performance. R8 is careful about including and testing many optimizations at the code level, in [DEX layout](https://developer.android.com/topic/performance/baselineprofiles/dex-layout-optimizations), and in correctly producing Baseline Profiles - other tools producing or modifying DEX files can break these optimizations, or otherwise regress performance. -If you are interested in optimizing your build speed, see [Configure how R8 -runs](https://developer.android.com/build/r8-execution-profiles) for information on how to configure R8 based on your environment. +If you are interested in optimizing your build speed, see [Configure how R8 runs](https://developer.android.com/build/r8-execution-profiles) for information on how to configure R8 based on your environment. ## AGP and R8 version behavior changes -The following table outlines the key features introduced in various versions of -the Android Gradle Plugin (AGP) and the R8 compiler. +The following table outlines the key features introduced in various versions of the Android Gradle Plugin (AGP) and the R8 compiler. | AGP version | Features introduced | |---|---| -| 9.3 | **Simplified DSL:** New \`optimization {}\` block enables requires less configuration- optimized resource shrinking is always enabled, default Android keep rules are opt-out.
**\`keepRules\` source set:** If you use the new DSL, you must place your keep rules in the `src//keepRules` source set, in files with the suffix `.keep`. The source sets are also compatible with the legacy DSL.
**KMP (Kotlin MultiPlatform) consumer rules:** KMP no longer requires setting `publish = true`, and supports the `src//keepRules` source set with the `.keep` extension.
Note that the legacy DSL is still supported. | +| 9.3 | **Simplified DSL:** New \`optimization {}\` block enables requires less configuration- optimized resource shrinking is always enabled, default Android keep rules are opt-out. **\`keepRules\` source set:** If you use the new DSL, you must place your keep rules in the `src//keepRules` source set, in files with the suffix `.keep`. The source sets are also compatible with the legacy DSL. **KMP (Kotlin MultiPlatform) consumer rules:** KMP no longer requires setting `publish = true`, and supports the `src//keepRules` source set with the `.keep` extension. Note that the legacy DSL is still supported. | | 9.1 | **Classes repackaged by default:** R8 repackages classes (moving them to the unnamed package, at the top level) to compact DEX further, eliminating the need to specify `-repackageclasses` option. For information about how this works and how to opt out, see [global options](https://developer.android.com/topic/performance/app-optimization/global-options#global-options). | | 9.0 | **Optimized resource shrinking:** Enabled by default (controlled using `android.r8.optimizedResourceShrinking`). [Optimized resource shrinking](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization#optimize-resource-shrinking) helps integrate resource shrinking with the code optimization pipeline, leading to smaller, faster apps. By optimizing both code and resource references simultaneously, it identifies and removes resources referenced exclusively from unused code. This is a significant improvement over the previous separate optimization processes. This is especially useful for apps that share substantial resources and code across different form factor verticals, with measured improvements of over 50% in app size. The resulting size reduction leads to smaller downloads, faster installations, and a better user experience with faster startup, improved rendering, and fewer ANRs. **Library rule filtering:** Support for global options (for example, `-dontobfuscate`) in library consumer rules has been dropped, and apps will filter them out. For more information, see [Add global options](https://developer.android.com/topic/performance/app-optimization/global-options). **Kotlin null checks:** Optimized by default (controlled using `-processkotlinnullchecks`). This version also introduced significant improvements in build speed. For more information, see [Global options for additional optimization](https://developer.android.com/topic/performance/app-optimization/global-options#global-options). **Optimize specific packages:** You can use `packageScope` to optimize specific packages. This is in experimental support. For more information, see [Optimize specified packages with `packageScope`](https://developer.android.com/topic/performance/app-optimization/optimize-specified-packages). **Optimized by default:** Support for `getDefaultProguardFile("proguard-android.txt")` has been dropped, because it includes `-dontoptimize`, which should be avoided. Instead, use `"proguard-android-optimize.txt"`. If you need to globally disable optimization in your app, [add the flag manually to a proguard file](https://developer.android.com/topic/performance/app-optimization/global-options#global-options-2). | | 8.12 | **Optimized resource shrinking:** Initial support added (controlled using `android.r8.optimizedResourceShrinking`). [Optimized resource shrinking](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization#optimize-resource-shrinking) helps integrate resource shrinking with the code optimization pipeline. You must manually enable it in this version of AGP. **Logcat retracing:** Support for automatic retracing in the Android Studio [Logcat window](https://developer.android.com/studio/debug/logcat). | diff --git a/performance/r8-analyzer/references/android/training/testing/other-components/ui-automator.md b/performance/r8-analyzer/references/android/training/testing/other-components/ui-automator.md index 2b5b253..75d0d08 100644 --- a/performance/r8-analyzer/references/android/training/testing/other-components/ui-automator.md +++ b/performance/r8-analyzer/references/android/training/testing/other-components/ui-automator.md @@ -1,34 +1,26 @@ -The UI Automator testing framework provides a set of APIs to build UI tests that -interact with user apps and system apps. +The UI Automator testing framework provides a set of APIs to build UI tests that interact with user apps and system apps. > [!NOTE] > **Note:** This documentation covers the modern approach to writing UI Automator tests, introduced with [UI Automator 2.4](https://developer.android.com/jetpack/androidx/releases/test-uiautomator#2.4.0). This approach makes your tests more concise, readable, and robust. The API is under development, and we strongly recommend using it for any new development with UI Automator. The [legacy API guidance](https://developer.android.com/training/testing/other-components/ui-automator-legacy) is also available. ## Introduction to modern UI Automator testing -UI Automator 2.4 introduces a streamlined, Kotlin-friendly Domain Specific -Language (DSL) that simplifies writing UI tests for Android. This new API -surface focuses on predicate-based element finding and explicit control over app -states. Use it to create more maintainable and reliable automated tests. +UI Automator 2.4 introduces a streamlined, Kotlin-friendly Domain Specific Language (DSL) that simplifies writing UI tests for Android. This new API surface focuses on predicate-based element finding and explicit control over app states. Use it to create more maintainable and reliable automated tests. -UI Automator lets you test an app from outside of the app's process. This -lets you test release versions with minification applied. UI Automator also -helps when writing macrobenchmark tests. +UI Automator lets you test an app from outside of the app's process. This lets you test release versions with minification applied. UI Automator also helps when writing macrobenchmark tests. Key features of the modern approach include: - A dedicated `uiAutomator` test scope for cleaner and more expressive test code. - Methods like `onElement`, `onElements`, and `onElementOrNull` for finding UI elements with clear predicates. -- Built-in waiting mechanism for conditional elements `onElement*(timeoutMs: - Long = 10000)` +- Built-in waiting mechanism for conditional elements `onElement*(timeoutMs: Long = 10000)` - Explicit app state management such as `waitForStable` and `waitForAppToBeVisible`. - Direct interaction with accessibility window nodes for multi-window testing scenarios. - Built-in screenshot capabilities and a `ResultsReporter` for visual testing and debugging. ## Set up your project -To begin using the modern UI Automator APIs, update your project's -`build.gradle.kts` file to include the [latest dependency](https://developer.android.com/jetpack/androidx/releases/test-uiautomator#2.4.0): +To begin using the modern UI Automator APIs, update your project's `build.gradle.kts` file to include the [latest dependency](https://developer.android.com/jetpack/androidx/releases/test-uiautomator#2.4.0): ### Kotlin @@ -50,9 +42,7 @@ The following sections describe core concepts of the modern UI Automator API. ### The uiAutomator test scope -Access all new UI Automator APIs within the **`uiAutomator { ... }`** -block. This function creates a `UiAutomatorTestScope` that provides a concise -and type-safe environment for your test operations. +Access all new UI Automator APIs within the **`uiAutomator { ... }`** block. This function creates a `UiAutomatorTestScope` that provides a concise and type-safe environment for your test operations. uiAutomator { // All your UI Automator actions go here @@ -62,13 +52,9 @@ and type-safe environment for your test operations. ### Find UI elements -Use UI Automator APIs with predicates to locate UI elements. These predicates -let you define conditions for properties such as text, selected or focused -state, and content description. +Use UI Automator APIs with predicates to locate UI elements. These predicates let you define conditions for properties such as text, selected or focused state, and content description. -- `onElement { predicate }`: Returns the first UI element that matches the - predicate within a default timeout. The function throws an exception if it - doesn't locate a matching element. +- `onElement { predicate }`: Returns the first UI element that matches the predicate within a default timeout. The function throws an exception if it doesn't locate a matching element. // Find a button with the text "Submit" and click it onElement { textAsString() == "Submit" }.click() @@ -81,15 +67,12 @@ state, and content description. clickAllow() } -- `onElementOrNull { predicate }`: Similar to `onElement`, but returns - `null` if the function finds no matching element within the timeout. It - doesn't throw an exception. Use this method for optional elements. +- `onElementOrNull { predicate }`: Similar to `onElement`, but returns `null` if the function finds no matching element within the timeout. It doesn't throw an exception. Use this method for optional elements. val optionalButton = onElementOrNull { textAsString() == "Skip" } optionalButton?.click() // Click only if the button exists -- `onElements { predicate }`: Waits until at least one UI element matches - the given predicate, then returns a list of all matching UI elements. +- `onElements { predicate }`: Waits until at least one UI element matches the given predicate, then returns a list of all matching UI elements. // Get all items in a list Ui element val listItems = onElements { className == "android.widget.TextView" && isClickable } @@ -97,9 +80,7 @@ state, and content description. Here are some tips for using `onElement` calls: -- Chain `onElement` calls for nested elements: You can chain `onElement` - calls to find elements within other elements, following a parent-child - hierarchy. +- Chain `onElement` calls for nested elements: You can chain `onElement` calls to find elements within other elements, following a parent-child hierarchy. // Find a parent Ui element with ID "first", then its child with ID "second", // then its grandchild with ID "third", and click it. @@ -108,8 +89,7 @@ Here are some tips for using `onElement` calls: .onElement { viewIdResourceName == "third" } .click() -- Specify a timeout for `onElement*` functions by passing a value representing - milliseconds. +- Specify a timeout for `onElement*` functions by passing a value representing milliseconds. // Find a Ui element with a zero timeout (instant check) onElement(0) { viewIdResourceName == "something" }.click() @@ -119,8 +99,7 @@ Here are some tips for using `onElement` calls: ### Interact with UI elements -Interact with UI elements by simulating clicks or setting text in editable -fields. +Interact with UI elements by simulating clicks or setting text in editable fields. // Click a Ui element onElement { textAsString() == "Tap Me" }.click() @@ -133,8 +112,7 @@ fields. ## Handle app states and watchers -Manage the lifecycle of your app and handle unexpected UI elements that might -appear during your tests. +Manage the lifecycle of your app and handle unexpected UI elements that might appear during your tests. ### App lifecycle management @@ -155,9 +133,7 @@ The APIs provide ways to control the state of the app under test: ### Handle unexpected UI -The `watchFor` API lets you define handlers for unexpected UI elements, -such as permission dialogs, that might appear during your test flow. This -uses the internal watcher mechanism but offers more flexibility. +The `watchFor` API lets you define handlers for unexpected UI elements, such as permission dialogs, that might appear during your test flow. This uses the internal watcher mechanism but offers more flexibility. import androidx.test.uiautomator.PermissionDialog @@ -180,24 +156,19 @@ uses the internal watcher mechanism but offers more flexibility. onElement { textAsString() == "Request Permissions" }.click() } -`PermissionDialog` is an example of a `ScopedWatcher`, where `T` is the -object passed as a scope to the block in `watchFor`. You can create custom -watchers based on this pattern. +`PermissionDialog` is an example of a `ScopedWatcher`, where `T` is the object passed as a scope to the block in `watchFor`. You can create custom watchers based on this pattern. ### Wait for app visibility and stability -Sometimes tests need to wait for elements to become visible or stable. -UI Automator offers several APIs to help with this. +Sometimes tests need to wait for elements to become visible or stable. UI Automator offers several APIs to help with this. -The `waitForAppToBeVisible("com.example.targetapp")` waits for a UI element with -the given package name to appear on the screen within a customizable timeout. +The `waitForAppToBeVisible("com.example.targetapp")` waits for a UI element with the given package name to appear on the screen within a customizable timeout. // Wait for the app to be visible after launching it startApp("com.example.targetapp") waitForAppToBeVisible("com.example.targetapp") -Use the `waitForStable()` API to verify that the app's UI is considered stable -before interacting with it. +Use the `waitForStable()` API to verify that the app's UI is considered stable before interacting with it. // Wait for the entire active window to become stable activeWindow().waitForStable() @@ -210,26 +181,11 @@ before interacting with it. ## Use UI Automator for Macrobenchmarks and Baseline Profiles -Use UI Automator for performance testing with [Jetpack Macrobenchmark](https://developer.android.com/topic/performance/benchmarking/macrobenchmark-overview) -and for generating [Baseline Profiles](https://developer.android.com/topic/performance/baselineprofiles/overview), as it provides a reliable way to -interact with your app and measure performance from an end-user perspective. +Use UI Automator for performance testing with [Jetpack Macrobenchmark](https://developer.android.com/topic/performance/benchmarking/macrobenchmark-overview) and for generating [Baseline Profiles](https://developer.android.com/topic/performance/baselineprofiles/overview), as it provides a reliable way to interact with your app and measure performance from an end-user perspective. -Macrobenchmark uses UI Automator APIs to drive the UI and measure interactions. -For example, in startup benchmarks, you can use `onElement` to detect when UI -content is fully loaded, enabling you to measure [Time to Full Display -(TTFD)](https://developer.android.com/topic/performance/vitals/launch-time#time-full). In jank benchmarks, UI Automator APIs are used to scroll lists or -run animations to measure frame timings. Functions like `startActivity()` or -`startIntent()` are useful for getting the app into the correct state before -measurement begins. +Macrobenchmark uses UI Automator APIs to drive the UI and measure interactions. For example, in startup benchmarks, you can use `onElement` to detect when UI content is fully loaded, enabling you to measure [Time to Full Display (TTFD)](https://developer.android.com/topic/performance/vitals/launch-time#time-full). In jank benchmarks, UI Automator APIs are used to scroll lists or run animations to measure frame timings. Functions like `startActivity()` or `startIntent()` are useful for getting the app into the correct state before measurement begins. -When [generating Baseline Profiles](https://developer.android.com/topic/performance/baselineprofiles/create-baselineprofile), you automate your app's critical user -journeys (CUJs) to record which classes and methods require pre-compilation. UI -Automator is an ideal tool for writing these automation scripts. The modern -DSL's predicate-based element finding and built-in wait mechanisms (`onElement`) -lead to more robust and deterministic test execution compared to other methods. -This stability reduces flakiness and ensures that the generated Baseline Profile -accurately reflects the code paths executed during your most important user -flows. +When [generating Baseline Profiles](https://developer.android.com/topic/performance/baselineprofiles/create-baselineprofile), you automate your app's critical user journeys (CUJs) to record which classes and methods require pre-compilation. UI Automator is an ideal tool for writing these automation scripts. The modern DSL's predicate-based element finding and built-in wait mechanisms (`onElement`) lead to more robust and deterministic test execution compared to other methods. This stability reduces flakiness and ensures that the generated Baseline Profile accurately reflects the code paths executed during your most important user flows. ## Advanced features @@ -237,9 +193,7 @@ The following features are useful for more complex testing scenarios. ### Interact with multiple windows -The UI Automator APIs let you directly interact with and inspect UI -elements. This is particularly useful for scenarios involving multiple windows, -such as Picture-in-Picture (PiP) mode or split-screen layouts. +The UI Automator APIs let you directly interact with and inspect UI elements. This is particularly useful for scenarios involving multiple windows, such as Picture-in-Picture (PiP) mode or split-screen layouts. // Find the first window that is in Picture-in-Picture mode val pipWindow = windows() @@ -250,9 +204,7 @@ such as Picture-in-Picture (PiP) mode or split-screen layouts. ### Screenshots and visual assertions -Capture screenshots of the entire screen, specific windows, or -individual UI elements directly within your tests. This is helpful for visual -regression testing and debugging. +Capture screenshots of the entire screen, specific windows, or individual UI elements directly within your tests. This is helpful for visual regression testing and debugging. uiautomator { // Take a screenshot of the entire active window @@ -270,14 +222,11 @@ regression testing and debugging. pipWindowScreenshot.saveToFile(File("/sdcard/Download/pip_screenshot.png")) } -The `saveToFile` extension function for Bitmap simplifies saving the captured -image to a specified path. +The `saveToFile` extension function for Bitmap simplifies saving the captured image to a specified path. ### Use ResultsReporter for debugging -The `ResultsReporter` helps you associate test artifacts, like screenshots, -directly with your test results in Android Studio for easier inspection and -debugging. +The `ResultsReporter` helps you associate test artifacts, like screenshots, directly with your test results in Android Studio for easier inspection and debugging. uiAutomator { startApp("com.example.targetapp") @@ -299,8 +248,7 @@ debugging. ## Migrate from older UI Automator versions -If you have existing UI Automator tests written with older API surfaces, use the -following table as a reference to migrate to the modern approach: +If you have existing UI Automator tests written with older API surfaces, use the following table as a reference to migrate to the modern approach: | Action type | Old UI Automator method | New UI Automator method | |---|---|---| diff --git a/play/engage-sdk-integration/SKILL.md b/play/engage-sdk-integration/SKILL.md index 0493cd7..9479934 100644 --- a/play/engage-sdk-integration/SKILL.md +++ b/play/engage-sdk-integration/SKILL.md @@ -6,7 +6,7 @@ description: Helps developers integrate, debug, and resolve Play Engage SDK impl license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-18' + last-updated: '2026-08-06' keywords: - android - engage @@ -15,9 +15,7 @@ metadata: - google play --- -This skill guides you through integrating the Play Engage SDK into an Android -app. It ensures that the code follows the mandatory structure and uses the -required Engage entities for each vertical. +This skill guides you through integrating the Play Engage SDK into an Android app. It ensures that the code follows the mandatory structure and uses the required Engage entities for each vertical. ## Workflow @@ -54,8 +52,7 @@ Follow these steps to assist the developer: - Ask the developer to provide the source of actual data you'll publish. - Once you identify the data source, use it to fetch the data in the app's local model schema. - Use `{ENGAGE_CODE_DIR}/ItemToEntityConverter` to convert this data to an Engage entity. - - Use obtained Engage entity model data with `{ENGAGE_CODE_DIR}/ - ClusterRequestFactory` to get cluster requests. + - Use obtained Engage entity model data with `{ENGAGE_CODE_DIR}/ ClusterRequestFactory` to get cluster requests. - Call corresponding cluster publishing method obtained from `{VERTICAL}.md` in the **[references/schemas/](references/schemas)** directory with the obtained request in previous step in `{ENGAGE_CODE_DIR}/EngageWorker`. 5. **Gradle and manifest updates:** @@ -72,9 +69,7 @@ Follow these steps to assist the developer: - Fix import errors. For package `com.google.android.engage` or classes starting with `AppEngage`, verify the package name in the `{VERTICAL}.md` in **[references/schemas/](references/schemas)** directory or [common.md](references/common.md). - Fix any other errors. - Execute a full Gradle build and resolve any remaining compilation issues. Repeat this step until the Gradle build is successful. -7. **User checklist:** At the end of code generation, notify the user to go - through this checklist to verify that the integration is complete and as - intended: +7. **User checklist:** At the end of code generation, notify the user to go through this checklist to verify that the integration is complete and as intended: - \[ \] Verify that all the Engage-related files are created in `{ENGAGE_CODE_DIR}/`: - `Constants` @@ -92,8 +87,7 @@ Follow these steps to assist the developer: ## Reference materials -- **FAQ:** [Engage FAQ](references/android/guide/playcore/engage/faq.md) - Refer to this document for answers to frequently - asked questions from developers. +- **FAQ:** [Engage FAQ](references/android/guide/playcore/engage/faq.md) - Refer to this document for answers to frequently asked questions from developers. - **Vertical-specific guides:** @@ -102,7 +96,7 @@ Follow these steps to assist the developer: - [Listen Vertical](references/android/guide/playcore/engage/listen.md) - [Read Vertical](references/android/guide/playcore/engage/read.md) - [Shopping Vertical](references/android/guide/playcore/engage/shopping.md) - - [Social Vertical](https://developer.android.com/guide/playcore/engage/social) + - [Social Vertical](references/android/guide/playcore/engage/social.md) - [Travel Vertical](references/android/guide/playcore/engage/travel.md) - [Health and Fitness Vertical](references/android/guide/playcore/engage/healthandfitness.md) - [Other Verticals](references/android/guide/playcore/engage/otherverticals.md) diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/faq.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/faq.md index 3ed6401..e0d1f4a 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/faq.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/faq.md @@ -2,47 +2,29 @@ #### Who manages the content publishing job? -The app developer manages the content publishing job and sends requests to the -Engage Service. In this way, developer partners have more control over when and -how to publish content to the users. This avoids waking up the partner app too -frequently to publish content. +The app developer manages the content publishing job and sends requests to the Engage Service. In this way, developer partners have more control over when and how to publish content to the users. This avoids waking up the partner app too frequently to publish content. #### Does a developer need to publish all cluster types? -While technically developers are free to publish just one cluster, we **strongly -advise** including more. Otherwise, developers miss the opportunity to drive -better engagement with their content. We **highly recommend** publishing all -cluster types for each vertical. +While technically developers are free to publish just one cluster, we **strongly advise** including more. Otherwise, developers miss the opportunity to drive better engagement with their content. We **highly recommend** publishing all cluster types for each vertical. #### How often should the developer partner be publishing data using the work manager while the app is running? -This is to be decided by the developer partner. Google recommends publishing -once or twice per day for general recommendation content, and to use an -event-driven methodology for shopping cart, reorder, and other continuation -content (for example, start the worker as a callback of the user adding items -to the cart or the user stopping a movie halfway). -For **social** apps, it's critical to publish updated recommendation clusters -**after each app usage**. Social app users are more interested in the most -recent recommendations and ideally would like to see a post at most once. +This is to be decided by the developer partner. Google recommends publishing once or twice per day for general recommendation content, and to use an event-driven methodology for shopping cart, reorder, and other continuation content (for example, start the worker as a callback of the user adding items to the cart or the user stopping a movie halfway). For **social** apps, it's critical to publish updated recommendation clusters **after each app usage**. Social app users are more interested in the most recent recommendations and ideally would like to see a post at most once. #### When should the developer call delete APIs? -Delete APIs should only be called when there is no content to publish. **Don't** -call delete and publish APIs subsequently to replace content; the publish -APIs remove the earlier content automatically. +Delete APIs should only be called when there is no content to publish. **Don't** call delete and publish APIs subsequently to replace content; the publish APIs remove the earlier content automatically. ## Broadcast Intent FAQs #### Why do Android app developers need to register for broadcast intents? -In order to serve fresh content to the user, you should use broadcast intents to -trigger a data sync in cases where users might not use the app frequently. +In order to serve fresh content to the user, you should use broadcast intents to trigger a data sync in cases where users might not use the app frequently. #### Unable to test broadcast intent -The verification app doesn't support testing broadcast intent with -permission. You have to remove permissions while testing and -add them back before switching the SDK to prod version in [Step 6](https://developer.android.com/guide/playcore/engage/workflow#switch-to-prod). +The verification app doesn't support testing broadcast intent with permission. You have to remove permissions while testing and add them back before switching the SDK to prod version in [Step 6](https://developer.android.com/guide/playcore/engage/workflow#switch-to-prod). #### Background execution not allowed @@ -77,27 +59,19 @@ While integrating with the SDK, you may come across the following errors: #### Validation errors at the app, cluster, entity level -Summaries at the app, cluster, and entity levels display a count of -validation errors. These errors correspond to missing required fields or -invalid values provided. Error messages show up in red beneath each relevant -field. Fix all validation errors and check for correctness before sharing -the APK. +Summaries at the app, cluster, and entity levels display a count of validation errors. These errors correspond to missing required fields or invalid values provided. Error messages show up in red beneath each relevant field. Fix all validation errors and check for correctness before sharing the APK. #### Testing Deep links -The deep links are associated with the package name. A good way to test -deep links is using the adb tool. +The deep links are associated with the package name. A good way to test deep links is using the adb tool. adb shell am start -W -a android.intent.action.VIEW -d #### How can I calculate the impact of the integration? -The deep links are a great way to track the attribution. The deep link URLs -that take users to your app can be included with additional tracking params. -For example - "http://xx/deeplink?source_tag=engage". +The deep links are a great way to track the attribution. The deep link URLs that take users to your app can be included with additional tracking params. For example - "http://xx/deeplink?source_tag=engage". -Developers can add their own tracking params and provide attribution to -calculate impact. +Developers can add their own tracking params and provide attribution to calculate impact. ## Engage for TV 2.0 FAQs @@ -105,33 +79,24 @@ calculate impact. #### What is Engage? -Engage takes the "pick up where you left off" experience to the next level! It's -a significant upgrade that allows viewers to seamlessly resume their content -across a wider range of devices. Imagine starting a movie on your Google TV and -then effortlessly continuing it on your phone during your commute -- that's the -power of Engage. +Engage takes the "pick up where you left off" experience to the next level! It's a significant upgrade that allows viewers to seamlessly resume their content across a wider range of devices. Imagine starting a movie on your Google TV and then effortlessly continuing it on your phone during your commute -- that's the power of Engage. -This new system is designed to boost viewer engagement and retention by -providing a smooth, frictionless experience across the entire Google ecosystem. +This new system is designed to boost viewer engagement and retention by providing a smooth, frictionless experience across the entire Google ecosystem. #### Is Video Discovery API the same as Engage? -Yes, they are the same. The Engage SDK is a library that includes support for -the continue watching row. Engage supports more content entity types than video, -which is why the integration is no longer named "Video Discovery". +Yes, they are the same. The Engage SDK is a library that includes support for the continue watching row. Engage supports more content entity types than video, which is why the integration is no longer named "Video Discovery". #### What are the benefits of using Engage? -Answer: Engage makes it easier than ever for viewers to pick up where they left -off on your content, no matter what device they're using. Here's how it works: +Answer: Engage makes it easier than ever for viewers to pick up where they left off on your content, no matter what device they're using. Here's how it works: - Seamless experience across Google: Start watching on your Google TV, and continue seamlessly on your Android phone, iPhone, or Android tablet. It even works on devices where you haven't installed the app yet! - Increased engagement and retention: Engage helps bring users back to your app, even on new devices. By letting users resume their favorite shows, you increase the chances they'll keep watching. - Wider reach: Beyond Google TV, Engage works across other Android media experiences, like Play Collections and other Google media apps. - Backward compatible: If you're already using the older "[Watch Next](https://developer.android.com/training/tv/discovery/watch-next-add-programs)" feature, no problem! Engage is backward compatible, so your existing integration will still work. -Important Note: All new Continue Watching integrations must use Engage. The -older "Cross Device Play Next" system is being phased out. +Important Note: All new Continue Watching integrations must use Engage. The older "Cross Device Play Next" system is being phased out. #### What surfaces support Engage? @@ -145,8 +110,7 @@ older "Cross Device Play Next" system is being phased out. #### Is Engage SDK for Continue Watching? -Yes, the Engage SDK supports content for the continue watching row. It is -required to integrate with Engage. +Yes, the Engage SDK supports content for the continue watching row. It is required to integrate with Engage. #### Is Engage available for everyone? @@ -155,85 +119,53 @@ Engage is being rolled out in phases. - Early Access: We're initially granting access to a select group of partners through an Early Access Program (EAP). - Expanding Access: We're working hard to make Engage available to all developers soon. -For a smooth and successful launch, we have safeguards in place to manage the -rollout. This involves both an allowlist on the Engage side and a separate check -within the Engage SDK. Whether you are an EAP partner or wants to be onboard -soon, please contact us so that we can set up the access permissions before you -begin with Engage SDK integration. +For a smooth and successful launch, we have safeguards in place to manage the rollout. This involves both an allowlist on the Engage side and a separate check within the Engage SDK. Whether you are an EAP partner or wants to be onboard soon, please contact us so that we can set up the access permissions before you begin with Engage SDK integration. #### Is there a recommended image size we should provide? -Image requirements have been updated in the [Create Entities](https://developer.android.com/guide/playcore/engage/watch#image-specs) -section. +Image requirements have been updated in the [Create Entities](https://developer.android.com/guide/playcore/engage/watch#image-specs) section. #### With this new API documentation, will the Continue Watching data pulled by the Google server from the client and will it be reflected in all the devices? -The new API offers significant improvements for content on the continue watching -row, including: +The new API offers significant improvements for content on the continue watching row, including: -- **Seamless experience across Google TVs:** Users can start watching on one - Google TV and resume on any other Google TV logged in with the same account. - This feature also works with older Android TV versions. +- **Seamless experience across Google TVs:** Users can start watching on one Google TV and resume on any other Google TV logged in with the same account. This feature also works with older Android TV versions. -- **Mobile app integration:** Content from Engage is surfaced on the Google TV - mobile app for Android and iOS, allowing users to seamlessly switch between - their TV and mobile devices. +- **Mobile app integration:** Content from Engage is surfaced on the Google TV mobile app for Android and iOS, allowing users to seamlessly switch between their TV and mobile devices. -- **Enhanced user retention:** Even on devices without the app installed or - where the user isn't logged in, content in the continue watching row - encourages users to re-engage with your app, boosting retention. +- **Enhanced user retention:** Even on devices without the app installed or where the user isn't logged in, content in the continue watching row encourages users to re-engage with your app, boosting retention. -- **Expansion to other platforms:** Engage extends to other Google media - platforms like Android, Play Collections, tablets, and other Google media - apps \& surfaces on Android, maximizing user engagement across devices. +- **Expansion to other platforms:** Engage extends to other Google media platforms like Android, Play Collections, tablets, and other Google media apps \& surfaces on Android, maximizing user engagement across devices. #### What is the limit on the number of entities I can publish to the Continuation cluster? -Each developer partner is limited to a maximum of 5 entities in the Continuation -cluster. This limit is for fair distribution of content on the "continue -watching" row on Google TV, which is a shared space for multiple media -providers. +Each developer partner is limited to a maximum of 5 entities in the Continuation cluster. This limit is for fair distribution of content on the "continue watching" row on Google TV, which is a shared space for multiple media providers. #### What happens if I try to publish more than 5 entities? -Engage SDK will reject your publish request if it exceeds the 5-entity limit. -You'll need to reduce the number of entities in your request to successfully -publish. You should only include the entities where the users have left off -watching, so in most cases, there will be only a few such entities. When there -are more than 5 such entities, you could choose the more recent ones to publish. +Engage SDK will reject your publish request if it exceeds the 5-entity limit. You'll need to reduce the number of entities in your request to successfully publish. You should only include the entities where the users have left off watching, so in most cases, there will be only a few such entities. When there are more than 5 such entities, you could choose the more recent ones to publish. #### Why is there a limit on the number of entities? -The continue watching row on Google TV displays content from various media -providers. Limiting the number of entities per provider so that users see a -diverse selection of content from all their favorite sources, promoting a fair -and balanced user experience. +The continue watching row on Google TV displays content from various media providers. Limiting the number of entities per provider so that users see a diverse selection of content from all their favorite sources, promoting a fair and balanced user experience. ### Verification App Questions #### Is it mandatory to test my app with the verification app before submission? -Yes, testing your app with the verification app is essential before submitting -your APK. +Yes, testing your app with the verification app is essential before submitting your APK. -While we understand you might be confident in your implementation, the Engage -integration has many intricate components. The verification app acts as a safety -net, catching potential issues early on and saving you valuable time and effort -in the long run. +While we understand you might be confident in your implementation, the Engage integration has many intricate components. The verification app acts as a safety net, catching potential issues early on and saving you valuable time and effort in the long run. -Think of it as a quick checkup that helps guarantee a smooth launch and a great -user experience. +Think of it as a quick checkup that helps guarantee a smooth launch and a great user experience. -By identifying and addressing any problems beforehand, you can avoid the -frustration of rejections and resubmissions. +By identifying and addressing any problems beforehand, you can avoid the frustration of rejections and resubmissions. -To submit your APK, you'll need to include a screenshot showing that your app -has passed the verification process. +To submit your APK, you'll need to include a screenshot showing that your app has passed the verification process. #### What are some common mistakes to watch out for during integration? -The verification app is designed to catch potential issues with your Engage -integration. Here are some common mistakes that developers often encounter: +The verification app is designed to catch potential issues with your Engage integration. Here are some common mistakes that developers often encounter: For all content types (movies, TV episodes, live streams, video clips): @@ -258,29 +190,23 @@ For Video Clips: - Creator Information: Specify the creator of the video clip. -Remember: The verification app will flag these issues, allowing you to fix them -before submitting your app. This saves you time and ensures a smoother -experience for your users. +Remember: The verification app will flag these issues, allowing you to fix them before submitting your app. This saves you time and ensures a smoother experience for your users. ### Account and Profile Questions #### My app uses anonymous user logins. Is AccountProfile still required for Engage? -`AccountProfile` is designed for apps that use individual user accounts. -However, we understand that some apps, like yours, may rely on anonymous logins. -Here's how Engage works in this scenario: +`AccountProfile` is designed for apps that use individual user accounts. However, we understand that some apps, like yours, may rely on anonymous logins. Here's how Engage works in this scenario: - `AccountProfile` is technically required, but you can still integrate Engage even if your app doesn't have a user account system. - Limited to on-device use: The cross-device capabilities of Engage relies on identifying users across different devices. Since anonymous logins don't provide this, the feature will be limited to the user's current device. - How to configure: To set this up, you'll need to disable cross-device syncing. This makes sure that continuation entries only appear on the specific device where the content was started. -In summary: While you can integrate Engage with anonymous logins, users will -only be able to resume content on the same device. +In summary: While you can integrate Engage with anonymous logins, users will only be able to resume content on the same device. #### Can I use AccountProfile with only `accountId` and no `profileId`, even when my app supports both accountId and `profileId`? -AccountProfile requires both `accountId` and `profileId` to function correctly. -Here's why: +AccountProfile requires both `accountId` and `profileId` to function correctly. Here's why: - Consistent identification: `accountId` identifies the user, while `profileId` distinguishes between different profiles within that user's account (if applicable). Providing both makes sure that Engage accurately tracks and displays content for each individual profile. - Preventing errors: Using `accountId` and `profileId` inconsistently across different API calls can lead to unexpected behavior and errors. For example, if you include both when adding content to Engage but only use `accountId` when deleting content, the system may not be able to correctly identify and remove the intended items. @@ -293,49 +219,29 @@ Here's why: #### How does Google use the `profileId` on their side? -If the service offers different profiles to watch content, `accountId` and -`profileId` would be used to associate the content watched on the device to the -signed-in Google Account on the device. Google would record the ContinueWatching -data against the combination of `accountId` and `profileId`. Any Google device -that has that same Google Account logged in, would get the latest updated data -from the same associated `accountId` and `profileId`, in its ContinueWatching -row. +If the service offers different profiles to watch content, `accountId` and `profileId` would be used to associate the content watched on the device to the signed-in Google Account on the device. Google would record the ContinueWatching data against the combination of `accountId` and `profileId`. Any Google device that has that same Google Account logged in, would get the latest updated data from the same associated `accountId` and `profileId`, in its ContinueWatching row. #### Is account linking required to implement Engage? -Account Linking is not needed. It is being deprioritized and all related use -cases will be covered by the new Device Entitlements API. +Account Linking is not needed. It is being deprioritized and all related use cases will be covered by the new Device Entitlements API. ### Sync Across Devices Questions #### What does "sync across devices" mean when users give consent? -With the user's "sync across device" consent, the content they're watching will -be saved to Google TV servers, letting them seamlessly pick up where they left -off on any signed-in device. Without consent, their watch history remains local -to the current device. +With the user's "sync across device" consent, the content they're watching will be saved to Google TV servers, letting them seamlessly pick up where they left off on any signed-in device. Without consent, their watch history remains local to the current device. #### Can we set "sync across devices" to false? -The `setUserConsentToSyncAcrossDevices` flag controls whether a user's -ContinuationCluster data is synchronized across their devices (TV, phone, -tablet, etc.). If this flag is set to false, then continue watching content is -only surfaced on same device. +The `setUserConsentToSyncAcrossDevices` flag controls whether a user's ContinuationCluster data is synchronized across their devices (TV, phone, tablet, etc.). If this flag is set to false, then continue watching content is only surfaced on same device. -To get the most out of our cross-device feature, we strongly advise your app to -obtain user consent and set SyncAcrossDevices to true. +To get the most out of our cross-device feature, we strongly advise your app to obtain user consent and set SyncAcrossDevices to true. #### How is user consent for sharing watch history obtained on non-Android devices? What data points are shared to 3P servers from non-Android devices? -The consent is collected at the user level (profile or account level). Once -consent is obtained, the continue watching payloads based on engagement can be -sent anywhere so Google can reflect the users' ubiquity resumption state across -all entities that they have partial or next engagement with, on any device -(without having to re-ask consent on every device or platform). Partners will -send the users latest continue watching state (as per spec) associated with -profile ID (that was deposited on android). +The consent is collected at the user level (profile or account level). Once consent is obtained, the continue watching payloads based on engagement can be sent anywhere so Google can reflect the users' ubiquity resumption state across all entities that they have partial or next engagement with, on any device (without having to re-ask consent on every device or platform). Partners will send the users latest continue watching state (as per spec) associated with profile ID (that was deposited on android). ### REST API Questions @@ -347,25 +253,19 @@ The ETA for REST API is March 2025, this is documented in Engage Developer Docs. #### Is Engage replacing the Watch Next API? -Engage will be backward compatible on all Android TV devices that support the -Watch Next API. To integrate on Google TV and other surfaces that support -Engage, developers should use the Engage SDK. +Engage will be backward compatible on all Android TV devices that support the Watch Next API. To integrate on Google TV and other surfaces that support Engage, developers should use the Engage SDK. ### Testing and Integration Questions #### What is the difference between LastPlayBackPositionTimeMillis and duration? -LastPlayBackPositionTimeMillis should reflect the playback duration in -milliseconds where the user stopped watching (e.g., 605000 ms for 10 minutes and -5 seconds). It should never be greater than the entity's total duration. +LastPlayBackPositionTimeMillis should reflect the playback duration in milliseconds where the user stopped watching (e.g., 605000 ms for 10 minutes and 5 seconds). It should never be greater than the entity's total duration. -Whereas, **LastEngagementTime** is the timestamp when the user last engaged with -the content. +Whereas, **LastEngagementTime** is the timestamp when the user last engaged with the content. #### What are the test cases we should perform? -The following are test cases for Google TV that our QA performs. Similar test -cases can be performed on other surfaces as well. +The following are test cases for Google TV that our QA performs. Similar test cases can be performed on other surfaces as well. 1. Watch a video, which is longer than 20 minutes for about 5 minutes. Exit app. The video card should be displayed in the continue watching row. Note: We only display 5 cards per 3p app in CW 2. Selecting the newly appeared card in the continue watching row should continue playing the video from the right point in the video.Note: Any New or old content should resume playback from where it was left off last @@ -384,15 +284,9 @@ cases can be performed on other surfaces as well. 15. episode 1 drops and doesn't reappear in continue watching row \[on second device and on turning on the test device\] 1. episode 2 (if available), should appear in continue watching row \[on second device and on turning on the test device\] 16. First scenario: TV1: GoogleAccount: mom, 3p account / profile: account 1 / profile_1. Watch content and verify CW data displays contents watched by 3P account_1/profile_1 -17. TV2: GoogleAccount: mom. Verify CW data from the first scenario. Now login - to the 3p app as a different account. 3p account / profile: account_2 / - profile_2. Watch content and verify CW data displays contents watched by 3p - account_2/profile_2 +17. TV2: GoogleAccount: mom. Verify CW data from the first scenario. Now login to the 3p app as a different account. 3p account / profile: account_2 / profile_2. Watch content and verify CW data displays contents watched by 3p account_2/profile_2 -18. GoogleAccount: mom. New device case /3P app not installed. On a new - device(FDR the device), Verify CW displays data from the last used 3P app - that was used by the GoogleAccount. Note: CW row shouldn't show 3P contents - if the GAIA is not yet associated with a 3P profile on other device +18. GoogleAccount: mom. New device case /3P app not installed. On a new device(FDR the device), Verify CW displays data from the last used 3P app that was used by the GoogleAccount. Note: CW row shouldn't show 3P contents if the GAIA is not yet associated with a 3P profile on other device 1. GoogleAccount: mom. New device case /3P app installed but not logged in. On a new device(FDR the device), Verify CW displays data from the last used 3P app that was used by the GoogleAccount. 19. @@ -404,8 +298,7 @@ cases can be performed on other surfaces as well. #### We are not seeing continuation content showing up on Google TV iOS app. What happened? -You will need to send iOS deeplinks for content to appear in the continue -watching row on iOS devices. +You will need to send iOS deeplinks for content to appear in the continue watching row on iOS devices. #### How often should I update content information for the continue watching row? Should I update it frequently, like every 15 seconds? @@ -416,8 +309,7 @@ No, frequent updates are not recommended. Here's why: When to update content information for the continue watching row: -Focus on capturing meaningful changes in the user's viewing progress. Here are -the key scenarios: +Focus on capturing meaningful changes in the user's viewing progress. Here are the key scenarios: - Playback Paused or Stopped: When a user pauses or stops watching, send an update to store their current position. - App Closed or Backgrounded: If a user exits the app or switches to another app while watching a video, send an update to save their progress. @@ -425,15 +317,12 @@ the key scenarios: How to efficiently update: -Instead of timed updates, utilize events within your video player or app -lifecycle to trigger updates. For example: +Instead of timed updates, utilize events within your video player or app lifecycle to trigger updates. For example: - `onPause`, `onStop`: When the video playback pauses or stops. - `onAppClose`, `onAppBackgrounded`: When the app closes or moves to the background. -By following these guidelines, you'll ensure efficient use of resources while -still providing a seamless experience in the continue watching row for your -users. +By following these guidelines, you'll ensure efficient use of resources while still providing a seamless experience in the continue watching row for your users. > [!NOTE] > **Note:** Please contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if you have any questions that are not covered here. \ No newline at end of file diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/food.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/food.md index dea9db9..72aa976 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/food.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/food.md @@ -1,59 +1,32 @@ -Boost app engagement by reaching your users where they are. Integrate Engage SDK -to deliver personalized recommendations and continuation content directly to -users across multiple on-device surfaces, like -**[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment -Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds -less than 50 KB (compressed) to the average APK and takes most apps about a -week of developer time. Learn more at our **[business -site](http://play.google.com/console/about/programs/EngageSDK)**. +Boost app engagement by reaching your users where they are. Integrate Engage SDK to deliver personalized recommendations and continuation content directly to users across multiple on-device surfaces, like **[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds less than 50 KB (compressed) to the average APK and takes most apps about a week of developer time. Learn more at our **[business site](http://play.google.com/console/about/programs/EngageSDK)**. -This guide contains instructions for developer partners to deliver food content -(food ordering, food or restaurant reviews \& discovery, meal subscriptions, -recipes) to Engage content surfaces. +This guide contains instructions for developer partners to deliver food content (food ordering, food or restaurant reviews \& discovery, meal subscriptions, recipes) to Engage content surfaces. ## Integration detail ### Terminology -This integration includes the following five cluster types: **Recommendation** , -**Featured** , **Food Shopping Cart** , **Food Shopping List** , and **Reorder**. +This integration includes the following five cluster types: **Recommendation** , **Featured** , **Food Shopping Cart** , **Food Shopping List** , and **Reorder**. -- **Recommendation** clusters show personalized food-related suggestions from an - individual developer partner. These recommendations can be personalized to the - user or generalized (for example, new on sale). Use them to surface recipes, - stores, dishes, groceries, and so on as you see fit. +- **Recommendation** clusters show personalized food-related suggestions from an individual developer partner. These recommendations can be personalized to the user or generalized (for example, new on sale). Use them to surface recipes, stores, dishes, groceries, and so on as you see fit. - A Recommendation cluster can be made of `ProductEntity`, `StoreEntity`, or `RecipeEntity` listings, but not a mix of different entity types. ![](https://developer.android.com/static/images/guide/playcore/engage/food-entities.png) **Figure :**\`ProductEntity\`, \`StoreEntity\`, and \`RecipeEntity\`. (\*UI for illustrative purposes only) -- The **Featured** cluster showcases a selection of entities from multiple - developer partners in one UI grouping. There will be a single Featured - cluster, which is surfaced near the top of the UI with a priority placement - above all Recommendation clusters. Each developer partner will be allowed to - broadcast up to 10 entities in the Featured cluster. +- The **Featured** cluster showcases a selection of entities from multiple developer partners in one UI grouping. There will be a single Featured cluster, which is surfaced near the top of the UI with a priority placement above all Recommendation clusters. Each developer partner will be allowed to broadcast up to 10 entities in the Featured cluster. ![](https://developer.android.com/static/images/guide/playcore/engage/food-featured.png) **Figure :** Featured cluster with the \`RecipeEntity\`. (\*UI for illustrative purposes only) -- The **Food Shopping Cart** cluster shows a sneak peek of grocery shopping - carts from multiple developer partners in one UI grouping, prompting users to - complete their outstanding carts. There is a single Food Shopping Cart - cluster. +- The **Food Shopping Cart** cluster shows a sneak peek of grocery shopping carts from multiple developer partners in one UI grouping, prompting users to complete their outstanding carts. There is a single Food Shopping Cart cluster. - - Food Shopping Cart Cluster must show the total count of items in the - cart and may also include images for X items in the user's cart. + - Food Shopping Cart Cluster must show the total count of items in the cart and may also include images for X items in the user's cart. ![](https://developer.android.com/static/images/guide/playcore/engage/food-shopping-cart.png) **Figure:** Food Shopping Cart cluster from a single partner. (\*UI for illustrative purposes only) -- The **Food Shopping List** cluster shows a sneak peek of the grocery shopping - lists from multiple developer partners in one UI grouping, prompting users to - return to the corresponding app to update and complete their lists. There is a - single Food Shopping List cluster. +- The **Food Shopping List** cluster shows a sneak peek of the grocery shopping lists from multiple developer partners in one UI grouping, prompting users to return to the corresponding app to update and complete their lists. There is a single Food Shopping List cluster. ![](https://developer.android.com/static/images/guide/playcore/engage/food-shopping-list.png) **Figure:** Food Shopping List cluster from a single partner. (\*UI for illustrative purposes only) -- The **Reorder** cluster shows a sneak peek of the previous orders from - multiple developer partners in one UI grouping, prompting users to reorder. - There is a single Reorder cluster. +- The **Reorder** cluster shows a sneak peek of the previous orders from multiple developer partners in one UI grouping, prompting users to reorder. There is a single Reorder cluster. - - Reorder cluster must show the total count of items in the - user's previous order and must also include one of the following: + - Reorder cluster must show the total count of items in the user's previous order and must also include one of the following: - Images for X items in the user's previous order. - Labels for X items in the user's previous order. @@ -73,11 +46,9 @@ Add the `com.google.android.engage:engage-core` library to your app: ### Summary -The design is based on an implementation of a [bound -service](https://developer.android.com/guide/components/bound-services). +The design is based on an implementation of a [bound service](https://developer.android.com/guide/components/bound-services). -The data a client can publish is subject to the following limits for different -cluster types: +The data a client can publish is subject to the following limits for different cluster types: | Cluster type | Cluster limits | Maximum entity limits in a cluster | |---|---|---| @@ -89,8 +60,7 @@ cluster types: ### Step 1: Provide entity data -The SDK has defined different entities to represent each item type. We support -the following entities for the Food category: +The SDK has defined different entities to represent each item type. We support the following entities for the Food category: 1. `ProductEntity` 2. `StoreEntity` @@ -103,9 +73,7 @@ The charts below outline available attributes and requirements for each type. #### `ProductEntity` -The `ProductEntity` object represents an individual item (such as a grocery -item, dish from a restaurant, or a promotion) that developer partners want to -publish. +The `ProductEntity` object represents an individual item (such as a grocery item, dish from a restaurant, or a promotion) that developer partners want to publish.
@@ -133,8 +101,7 @@ publish. #### `StoreEntity` -The `StoreEntity` object represents an individual store that developer partners -want to publish, such as a restaurant or a grocery store. +The `StoreEntity` object represents an individual store that developer partners want to publish, such as a restaurant or a grocery store.
@@ -160,8 +127,7 @@ want to publish, such as a restaurant or a grocery store. #### `RecipeEntity` -The `RecipeEntity` object represents a recipe item that developer partners want -to publish. +The `RecipeEntity` object represents a recipe item that developer partners want to publish.
@@ -264,10 +230,7 @@ PNG, JPG, static GIF, WebP ### Step 2: Provide Cluster data -It is recommended to have the content publish job executed in the background -(for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) -and scheduled on a regular basis or on an event basis (for example, every time -the user opens the app or when the user just added something to their cart). +It is recommended to have the content publish job executed in the background (for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) and scheduled on a regular basis or on an event basis (for example, every time the user opens the app or when the user just added something to their cart). `AppEngageFoodClient` is responsible for publishing food clusters. @@ -291,16 +254,29 @@ There are following APIs to publish clusters in the client: #### `isServiceAvailable` -This API is used to check if the service is available for integration and -whether the content can be presented on the device. +This API is used to check if the service is available for integration and whether the content can be presented on the device. ##### For Engage SDK v1.6.0 and higher (Recommended) -You can check the service availability for every cluster type that you intend to -publish. The `isServiceAvailable` API accepts a request object, -`ServiceAvailabilityRequest`, which contains the cluster types for which service -availability needs to be checked. You can find the `ClusterType` enum values -required for `ServiceAvailabilityRequest` from the following table. +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/play/engage-sdk-integration) + +### Engage SDK integration + +To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill engage-sdk-integration + +If your team uses AI coding tools (such as Gemini in Android Studio), you can automate this migration by prompting your AI assistant: + + Use the engage-sdk-integration skill to use Engage SDK 1.6.0 and refactor isServiceAvailable to pass ServiceAvailabilityRequest for publishing all cluster types. + +
+ +You can check the service availability for every cluster type that you intend to publish. The `isServiceAvailable` API accepts a request object, `ServiceAvailabilityRequest`, which contains the cluster types for which service availability needs to be checked. You can find the `ClusterType` enum values required for `ServiceAvailabilityRequest` from the following table. | Cluster Type | Cluster Type Constant | Integer Value | |---|---|---| @@ -361,26 +337,11 @@ required for `ServiceAvailabilityRequest` from the following table. ###### Conditional Service Availability Feature -Some integrated apps request a special configuration that enables and disables -the Engage service intermittently in order to reduce their serving cost. This -intermittent content ingestion strategy, although possible, negatively affects -the user and the product -- stale content will not be presented and some surfaces -will not be served at all. +Some integrated apps request a special configuration that enables and disables the Engage service intermittently in order to reduce their serving cost. This intermittent content ingestion strategy, although possible, negatively affects the user and the product -- stale content will not be presented and some surfaces will not be served at all. -Starting with v1.6.0, the Engage SDK allows checking availability for specific -cluster types. This provides more flexibility so that if the intermittent -content strategy was adopted by a given application, some cluster types can -follow that intermittent strategy while other cluster types are always enabled -(i.e. continuation clusters). +Starting with v1.6.0, the Engage SDK allows checking availability for specific cluster types. This provides more flexibility so that if the intermittent content strategy was adopted by a given application, some cluster types can follow that intermittent strategy while other cluster types are always enabled (i.e. continuation clusters). -If the Engage service should not be 'continuously' enabled on all supported -devices for whatever reason, and is configured for intermittent ingestion for -any set of devices, all continuation cluster publications (e.g. Food Shopping -Cart, Food Shopping List, and Reorder) will be still enabled by default -configuration, and the rest of the cluster types will be enabled and disabled -intermittently. If intermittent ingestion applies to you but this default -configuration is not suitable for your needs, please contact -engage-developers@google.com. +If the Engage service should not be 'continuously' enabled on all supported devices for whatever reason, and is configured for intermittent ingestion for any set of devices, all continuation cluster publications (e.g. Food Shopping Cart, Food Shopping List, and Reorder) will be still enabled by default configuration, and the rest of the cluster types will be enabled and disabled intermittently. If intermittent ingestion applies to you but this default configuration is not suitable for your needs, please contact engage-developers@google.com. ##### For SDK versions prior to v1.6.0 (Deprecated) @@ -461,14 +422,12 @@ A `RecommendationCluster` object can have the following attributes: .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - All existing Recommendation Cluster data is removed. - Data from the request is parsed and stored in new Recommendation Clusters. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFeaturedCluster` @@ -497,14 +456,12 @@ This API is used to publish a `FeaturedCluster` object. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FeaturedCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Featured Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFoodShoppingCarts` @@ -533,14 +490,12 @@ This API is used to publish a list of `FoodShoppingCart` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FoodShoppingCart` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Shopping Cart Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFoodShoppingLists` @@ -569,14 +524,12 @@ This API is used to publish a list of `FoodShoppingList` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FoodShoppingList` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Shopping List Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishReorderCluster` @@ -605,20 +558,16 @@ This API is used to publish a `FoodReorderCluster` object. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FoodReorderCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Reorder Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishUserAccountManagementRequest` -This API is used to publish a Sign In card . The signin action directs users to -the app's sign in page so that the app can publish content (or provide more -personalized content) +This API is used to publish a Sign In card . The signin action directs users to the app's sign in page so that the app can publish content (or provide more personalized content) The following metadata is part of the Sign In Card - @@ -671,21 +620,16 @@ The following metadata is part of the Sign In Card - .setSignInCardEntity(SIGN_IN_CARD_ENTITY) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `UserAccountManagementCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated UserAccountManagementCluster Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `updatePublishStatus` -If for any internal business reason, none of the clusters is published, -we **strongly recommend** updating the publish status using the -**updatePublishStatus** API. -This is important because : +If for any internal business reason, none of the clusters is published, we **strongly recommend** updating the publish status using the **updatePublishStatus** API. This is important because : - Providing the status in all scenarios, even when the content is published (STATUS == PUBLISHED), is critical to populate dashboards that use this explicit status to convey the health and other metrics of your integration. - If no content is published but the integration status isn't broken (STATUS == NOT_PUBLISHED), Google can avoid triggering alerts in the app health dashboards. It confirms that content is not published due to an **expected** situation from the provider's standpoint. @@ -725,11 +669,7 @@ The list of eligible publish status codes are : // Reach out to engage-developers@ before using this enum. AppEngagePublishStatusCode.NOT_PUBLISHED_OTHER -If the content is not published due to a user not logged in, -Google would recommend publishing the Sign In Card. -If for any reason providers are not able to publish the Sign In Card -then we recommend calling the **updatePublishStatus** API -with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** +If the content is not published due to a user not logged in, Google would recommend publishing the Sign In Card. If for any reason providers are not able to publish the Sign In Card then we recommend calling the **updatePublishStatus** API with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** ### Kotlin @@ -760,9 +700,7 @@ This API is used to delete the content of Recommendation Clusters. client.deleteRecommendationClusters(); -When the service receives the request, it removes the existing data from the -Recommendation Clusters. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Recommendation Clusters. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -782,9 +720,7 @@ This API is used to delete the content of Featured Cluster. client.deleteFeaturedCluster(); -When the service receives the request, it removes the existing data from the -Featured Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Featured Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -804,9 +740,7 @@ This API is used to delete the content of Food Shopping Cart Cluster. client.deleteFoodShoppingCartCluster(); -When the service receives the request, it removes the existing data from the -Food Shopping Cart Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Food Shopping Cart Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is availaile from version 1.1.0 onwards. @@ -826,9 +760,7 @@ This API is used to delete the content of Food Shopping List Cluster. client.deleteFoodShoppingListCluster(); -When the service receives the request, it removes the existing data from the -Food Shopping List Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Food Shopping List Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -848,9 +780,7 @@ This API is used to delete the content of FoodReorderCluster. client.deleteReorderCluster(); -When the service receives the request, it removes the existing data from the -Reorder Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Reorder Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -870,9 +800,7 @@ This API is used to delete the content of UserAccountManagement Cluster. client.deleteUserManagementCluster(); -When the service receives the request, it removes the existing data from the -UserAccountManagement Cluster. In case of an error, the entire request is -rejected and the existing state is maintained. +When the service receives the request, it removes the existing data from the UserAccountManagement Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -902,15 +830,11 @@ This API is used to delete the content of a given cluster type. ... .build()); -When the service receives the request, it removes the existing data from all -clusters matching the specified cluster types. Clients can choose to pass one or -many cluster types. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from all clusters matching the specified cluster types. Clients can choose to pass one or many cluster types. In case of an error, the entire request is rejected and the existing state is maintained. #### Error handling -It is highly recommended to listen to the task result from the publish APIs such -that a follow-up action can be taken to recover and resubmit an successful task. +It is highly recommended to listen to the task result from the publish APIs such that a follow-up action can be taken to recover and resubmit an successful task. client.publishRecommendationClusters( new PublishRecommendationClustersRequest.Builder() @@ -932,8 +856,7 @@ that a follow-up action can be taken to recover and resubmit an successful task. } }); -The error is returned as an `AppEngageException` with the cause included as an -error code. +The error is returned as an `AppEngageException` with the cause included as an error code. | Error code | Error name | Note | |---|---|---| @@ -947,23 +870,13 @@ error code. ### Step 3: Handle broadcast intents -In addition to making publish content API calls through a job, it is also -required to set up a -[`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive -the request for a content publish. +In addition to making publish content API calls through a job, it is also required to set up a [`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive the request for a content publish. -The goal of broadcast intents is mainly for app reactivation and forcing data -sync. Broadcast intents are not designed to be sent very frequently. It is only -triggered when the Engage Service determines the content might be stale (for -example, a week old). That way, there is more confidence that the user can have -a fresh content experience, even if the application has not been executed for a -long period of time. +The goal of broadcast intents is mainly for app reactivation and forcing data sync. Broadcast intents are not designed to be sent very frequently. It is only triggered when the Engage Service determines the content might be stale (for example, a week old). That way, there is more confidence that the user can have a fresh content experience, even if the application has not been executed for a long period of time. The `BroadcastReceiver` must be set up in the following two ways: -- Dynamically register an instance of the `BroadcastReceiver` class using - `Context.registerReceiver()`. This enables communication from applications - that are still live in memory. +- Dynamically register an instance of the `BroadcastReceiver` class using `Context.registerReceiver()`. This enables communication from applications that are still live in memory. ### Kotlin @@ -1069,10 +982,7 @@ The `BroadcastReceiver` must be set up in the following two ways: } -- Statically declare an implementation with the `` tag in your - `AndroidManifest.xml` file. This allows the application to receive broadcast - intents when it is not running, and also allows the application to publish - the content. +- Statically declare an implementation with the `` tag in your `AndroidManifest.xml` file. This allows the application to receive broadcast intents when it is not running, and also allows the application to publish the content. -The following [intents](https://developer.android.com/reference/android/content/Intent) will be sent by the -service: +The following [intents](https://developer.android.com/reference/android/content/Intent) will be sent by the service: - `com.google.android.engage.action.PUBLISH_RECOMMENDATION` It is recommended to start a `publishRecommendationClusters` call when receiving this intent. - `com.google.android.engage.action.PUBLISH_FEATURED` It is recommended to start a `publishFeaturedCluster` call when receiving this intent. @@ -1109,18 +1018,15 @@ service: ## Integration workflow -For a step-by-step guide on verifying your integration after it is complete, see -[Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). +For a step-by-step guide on verifying your integration after it is complete, see [Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). ## FAQs -See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for -FAQs. +See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for FAQs. ## Contact -Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during -the integration process. Our team will reply as soon as possible. +Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during the integration process. Our team will reply as soon as possible. ## Next steps diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/healthandfitness.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/healthandfitness.md index 3d6a779..5cd2518 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/healthandfitness.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/healthandfitness.md @@ -1,83 +1,43 @@ -Boost app engagement by reaching your users where they are. Integrate Engage SDK -to deliver personalized recommendations and continuation content directly to -users across multiple on-device surfaces, like -**[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment -Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds -less than 50 KB (compressed) to the average APK and takes most apps about a -week of developer time. Learn more at our **[business -site](http://play.google.com/console/about/programs/EngageSDK)**. +Boost app engagement by reaching your users where they are. Integrate Engage SDK to deliver personalized recommendations and continuation content directly to users across multiple on-device surfaces, like **[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds less than 50 KB (compressed) to the average APK and takes most apps about a week of developer time. Learn more at our **[business site](http://play.google.com/console/about/programs/EngageSDK)**. -This guide contains instructions for developer partners to deliver health and -fitness content to Engage content surfaces. +This guide contains instructions for developer partners to deliver health and fitness content to Engage content surfaces. ## Integration detail ### Terminology -This integration includes the following three cluster types: **Recommendation** , -**Featured** , and **Continuation**. +This integration includes the following three cluster types: **Recommendation** , **Featured** , and **Continuation**. -- **Recommendation** clusters show personalized health and fitness suggestions - from an individual developer partner. These recommendations can be - personalized to the user or generalized (for example, trending fitness \& - health). Use these to surface articles or people related to health and - fitness. +- **Recommendation** clusters show personalized health and fitness suggestions from an individual developer partner. These recommendations can be personalized to the user or generalized (for example, trending fitness \& health). Use these to surface articles or people related to health and fitness. - A Recommendation cluster can be made of `ArticleEntity`, `PersonEntity`, or `EventEntity` but not a mix of different entity types. Your recommendations take the following structure: - - **Recommendation Cluster:** A UI view that contains a group of - recommendations from the same developer partner. + - **Recommendation Cluster:** A UI view that contains a group of recommendations from the same developer partner. - - **Entity:** An object representing a single item in a cluster. This - integration offers some entities that would be surfaced using the - Recommendation Cluster: + - **Entity:** An object representing a single item in a cluster. This integration offers some entities that would be surfaced using the Recommendation Cluster: - - **ArticleEntity**: ArticleEntity represents a recommendation for - text-based content related to health \& fitness. It can be used for - articles, blogposts, marketing content, news snippets, etc. + - **ArticleEntity**: ArticleEntity represents a recommendation for text-based content related to health \& fitness. It can be used for articles, blogposts, marketing content, news snippets, etc. ![](https://developer.android.com/static/images/guide/playcore/engage/article-entity-health-and-fitness.png) **Figure 1:** UI showing a single ArticleEntity within Recommendations cluster. - - **PersonEntity**: PersonEntity represents a person. The - recommendations could be to highlight a coach or any person related - to health and fitness, etc. + - **PersonEntity**: PersonEntity represents a person. The recommendations could be to highlight a coach or any person related to health and fitness, etc. ![](https://developer.android.com/static/images/guide/playcore/engage/person-entity-health-and-fitness.png) **Figure 2:** UI showing a single PersonEntity within Recommendations cluster. - - **EventEntity**: EventEntity represents an event happening in the - future. Event start time is a critical piece of information that - needs to be conveyed to the users This entity could be used for - surfacing events like blood donation camp, training sessions, gym or - yoga classes etc. related to health and fitness. + - **EventEntity**: EventEntity represents an event happening in the future. Event start time is a critical piece of information that needs to be conveyed to the users This entity could be used for surfacing events like blood donation camp, training sessions, gym or yoga classes etc. related to health and fitness. ![](https://developer.android.com/static/images/guide/playcore/engage/event-entity-health-and-fitness.png) **Figure 3:** UI showing a single EventEntity within Recommendations cluster. -- The **Continuation** cluster shows content recently engaged by users from - multiple developer partners in a single UI grouping. Each developer partner - will be allowed to broadcast a maximum of 10 entities in the Continuation - cluster. +- The **Continuation** cluster shows content recently engaged by users from multiple developer partners in a single UI grouping. Each developer partner will be allowed to broadcast a maximum of 10 entities in the Continuation cluster. Your continuation content can take the following structure: - - **ArticleEntity**: ArticleEntity represents a recommendation for - text-based content that is related to health \& fitness. This entity can - be used to represent unfinished news articles or other content that the - user would like to continue consuming from where they left it. Ex: News - snippet, blogpost snippet about health or fitness related topics. + - **ArticleEntity**: ArticleEntity represents a recommendation for text-based content that is related to health \& fitness. This entity can be used to represent unfinished news articles or other content that the user would like to continue consuming from where they left it. Ex: News snippet, blogpost snippet about health or fitness related topics. ![](https://developer.android.com/static/images/guide/playcore/engage/article-entity-continuation-health-and-fitness.png) **Figure 6.** UI showing a single ArticleEntity within a Continuation cluster. - - **EventReservationEntity**: EventReservationEntity represents - reservation for an event and helps users track upcoming or ongoing - fitness and health events reservations. Ex: Training sessions + - **EventReservationEntity**: EventReservationEntity represents reservation for an event and helps users track upcoming or ongoing fitness and health events reservations. Ex: Training sessions ![](https://developer.android.com/static/images/guide/playcore/engage/event-reservation-entity-health-and-fitness.png) **Figure 8.** UI showing a single EventReservationEntity within a Continuation cluster. -- The **Featured** cluster showcases a selection of entities from multiple - developer partners in one UI grouping. There will be a single Featured - cluster, which is surfaced near the top of the UI with a priority placement - above all Recommendation clusters. Each developer partner will be allowed to - broadcast up to 10 entities in the Featured cluster. +- The **Featured** cluster showcases a selection of entities from multiple developer partners in one UI grouping. There will be a single Featured cluster, which is surfaced near the top of the UI with a priority placement above all Recommendation clusters. Each developer partner will be allowed to broadcast up to 10 entities in the Featured cluster. - - **GenericFeaturedEntity**: GenericFeaturedEntity differs from - Recommendation item in that Featured item should be used for a single - top content from developers and should represent the single most - important content that will be interesting and relevant to users. + - **GenericFeaturedEntity**: GenericFeaturedEntity differs from Recommendation item in that Featured item should be used for a single top content from developers and should represent the single most important content that will be interesting and relevant to users. ![](https://developer.android.com/static/images/guide/playcore/engage/featured-item-health-and-fitness.png) **Figure 12:** UI showing a single hero GenericFeaturedEntity card within a Featured cluster @@ -94,11 +54,9 @@ Add the `com.google.android.engage:engage-core` library to your app: ### Summary -The design is based on an implementation of a -[bound service](https://developer.android.com/guide/components/bound-services). +The design is based on an implementation of a [bound service](https://developer.android.com/guide/components/bound-services). -The data a client can publish is subject to the following limits for different -cluster types: +The data a client can publish is subject to the following limits for different cluster types: | Cluster type | Cluster limits | Minimum entity limits in a cluster | Maximum entity limits in a cluster | |---|---|---|---| @@ -108,8 +66,7 @@ cluster types: ### Step 1: Provide entity data -The SDK has defined different entities to represent each item type. We support -the following entities for the Health \& Fitness category: +The SDK has defined different entities to represent each item type. We support the following entities for the Health \& Fitness category: 1. `GenericFeaturedEntity` 2. `ArticleEntity` @@ -255,8 +212,7 @@ Required specifications for image assets are listed in this table: | Landscape (1.91x1) | 600x314 | 1200x628 | | Portrait (4x5) | 480x600 | 960x1200 | -The images are required to be hosted on public CDNs so that Google can access -them. +The images are required to be hosted on public CDNs so that Google can access them. *File formats* @@ -273,8 +229,7 @@ PNG, JPG, static GIF, WebP #### Content Category -The content category allows apps to publish content belonging to multiple -categories. This maps the content with some of the predefined categories namely: +The content category allows apps to publish content belonging to multiple categories. This maps the content with some of the predefined categories namely: - `TYPE_EDUCATION` - `TYPE_SPORTS` @@ -294,33 +249,25 @@ categories. This maps the content with some of the predefined categories namely: - `TYPE_PARENTING` - `TYPE_DATING` -The images are required to be hosted on public CDNs so that Google can access -them. +The images are required to be hosted on public CDNs so that Google can access them. *Guidelines to use the content categories* 1. Some entities like **ArticleEntity** and **GenericFeaturedEntity** are eligible to use any of the content categories. For other entities like **EventEntity** , **EventReservationEntity** , **PersonEntity**, only a subset of these categories are eligible. Check the list of categories eligible for an entity type before populating the list. -2. Use the specific entity type for some content categories over a combination - of the Generic entities and the ContentCategory: +2. Use the specific entity type for some content categories over a combination of the Generic entities and the ContentCategory: - TYPE_MOVIES_AND_TV_SHOWS - Check out the entities from [Watch integration guide](https://developer.android.com/guide/playcore/engage/watch) before using the generic entities. - TYPE_BOOKS - Check out the [EbookEntity](https://developer.android.com/guide/playcore/engage/read#ebookentity) before using the generic entities. - TYPE_AUDIOBOOKS - Check out [AudiobookEntity](https://developer.android.com/guide/playcore/engage/read#audiobookentity) before using the generic entities. - TYPE_SHOPPING - Check out [ShoppingEntity](https://developer.android.com/guide/playcore/engage/shopping#shoppingEntity) before using the generic entities. - TYPE_FOOD_AND_DRINK - Check out entities from [Food Integration guide](https://developer.android.com/guide/playcore/engage/food) before using the generic entities. -3. The ContentCategory field is optional and should be left blank if the - content doesn't belong to any of the categories mentioned earlier. +3. The ContentCategory field is optional and should be left blank if the content doesn't belong to any of the categories mentioned earlier. -4. In case multiple content categories are provided, provide them in the order - of relevance to the content with the most relevant content category placed - first in the list. +4. In case multiple content categories are provided, provide them in the order of relevance to the content with the most relevant content category placed first in the list. ### Step 2: Provide Cluster data -It is recommended to have the content publish job executed in the background -(for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) -and scheduled on a regular basis or on an event basis (for example, every time -the user opens the app or when the user just added something to their cart). +It is recommended to have the content publish job executed in the background (for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) and scheduled on a regular basis or on an event basis (for example, every time the user opens the app or when the user just added something to their cart). `AppEngagePublishClient` is responsible for publishing clusters. @@ -340,16 +287,29 @@ There are following APIs to publish clusters in the client: #### `isServiceAvailable` -This API is used to check if the service is available for integration and -whether the content can be presented on the device. +This API is used to check if the service is available for integration and whether the content can be presented on the device. ##### For Engage SDK v1.6.0 and higher (Recommended) -You can check the service availability for every cluster type that you intend to -publish. The `isServiceAvailable` API accepts a request object, -`ServiceAvailabilityRequest`, which contains the cluster types for which service -availability needs to be checked. You can find the `ClusterType` enum values -required for `ServiceAvailabilityRequest` from the following table. +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/play/engage-sdk-integration) + +### Engage SDK integration + +To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill engage-sdk-integration + +If your team uses AI coding tools (such as Gemini in Android Studio), you can automate this migration by prompting your AI assistant: + + Use the engage-sdk-integration skill to use Engage SDK 1.6.0 and refactor isServiceAvailable to pass ServiceAvailabilityRequest for publishing all cluster types. + +
+ +You can check the service availability for every cluster type that you intend to publish. The `isServiceAvailable` API accepts a request object, `ServiceAvailabilityRequest`, which contains the cluster types for which service availability needs to be checked. You can find the `ClusterType` enum values required for `ServiceAvailabilityRequest` from the following table. | Cluster Type | Cluster Type Constant | Integer Value | |---|---|---| @@ -407,26 +367,11 @@ required for `ServiceAvailabilityRequest` from the following table. ###### Conditional Service Availability Feature -Some integrated apps request a special configuration that enables and disables -the Engage service intermittently in order to reduce their serving cost. This -intermittent content ingestion strategy, although possible, negatively affects -the user and the product -- stale content will not be presented and some surfaces -will not be served at all. +Some integrated apps request a special configuration that enables and disables the Engage service intermittently in order to reduce their serving cost. This intermittent content ingestion strategy, although possible, negatively affects the user and the product -- stale content will not be presented and some surfaces will not be served at all. -Starting with v1.6.0, the Engage SDK allows checking availability for specific -cluster types. This provides more flexibility so that if the intermittent -content strategy was adopted by a given application, some cluster types can -follow that intermittent strategy while other cluster types are always enabled -(i.e. continuation clusters). +Starting with v1.6.0, the Engage SDK allows checking availability for specific cluster types. This provides more flexibility so that if the intermittent content strategy was adopted by a given application, some cluster types can follow that intermittent strategy while other cluster types are always enabled (i.e. continuation clusters). -If the Engage service should not be 'continuously' enabled on all supported -devices for whatever reason, and is configured for intermittent ingestion for -any set of devices, all continuation cluster publications (e.g. Continue -Reading and Event Reservations) will be still enabled by default -configuration, and the rest of the cluster types will be enabled and disabled -intermittently. If intermittent ingestion applies to you but this default -configuration is not suitable for your needs, please contact -engage-developers@google.com. +If the Engage service should not be 'continuously' enabled on all supported devices for whatever reason, and is configured for intermittent ingestion for any set of devices, all continuation cluster publications (e.g. Continue Reading and Event Reservations) will be still enabled by default configuration, and the rest of the cluster types will be enabled and disabled intermittently. If intermittent ingestion applies to you but this default configuration is not suitable for your needs, please contact engage-developers@google.com. ##### For SDK versions prior to v1.6.0 (Deprecated) @@ -500,14 +445,12 @@ This API is used to publish a list of `RecommendationCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `RecommendationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Recommendation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFeaturedCluster` @@ -538,14 +481,12 @@ This API is used to publish a list of `FeaturedCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FeaturedCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Featured Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishContinuationCluster` @@ -576,20 +517,16 @@ This API is used to publish a `ContinuationCluster` object. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ContinuationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Continuation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishUserAccountManagementRequest` -This API is used to publish a Sign In card . The signin action directs users to -the app's sign in page so that the app can publish content (or provide more -personalized content) +This API is used to publish a Sign In card . The signin action directs users to the app's sign in page so that the app can publish content (or provide more personalized content) The following metadata is part of the Sign In Card - @@ -642,20 +579,16 @@ The following metadata is part of the Sign In Card - .setSignInCardEntity(SIGN_IN_CARD_ENTITY) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `UserAccountManagementCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated UserAccountManagementCluster Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `updatePublishStatus` -If for any internal business reason, none of the clusters is published, we -**strongly recommend** updating the publish status using the -**updatePublishStatus** API. This is important because : +If for any internal business reason, none of the clusters is published, we **strongly recommend** updating the publish status using the **updatePublishStatus** API. This is important because : - Providing the status in all scenarios, even when the content is published (STATUS == PUBLISHED), is critical to populate dashboards that use this explicit status to convey the health and other metrics of your integration. - If no content is published but the integration status isn't broken (STATUS == NOT_PUBLISHED), Google can avoid triggering alerts in the app health dashboards. It confirms that content is not published due to an **expected** situation from the provider's standpoint. @@ -695,11 +628,7 @@ The list of eligible publish status codes are : // Reach out to engage-developers@ before using this enum. AppEngagePublishStatusCode.NOT_PUBLISHED_OTHER -If the content is not published due to a user not logged in, Google would -recommend publishing the Sign In Card. If for any reason providers are not able -to publish the Sign In Card then we recommend calling the -**updatePublishStatus** API with the status code -**NOT_PUBLISHED_REQUIRES_SIGN_IN** +If the content is not published due to a user not logged in, Google would recommend publishing the Sign In Card. If for any reason providers are not able to publish the Sign In Card then we recommend calling the **updatePublishStatus** API with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** ### Kotlin @@ -730,9 +659,7 @@ This API is used to delete the content of Recommendation Clusters. client.deleteRecommendationClusters(); -When the service receives the request, it removes the existing data from the -Recommendation Clusters. In case of an error, the entire request is rejected and -the existing state is maintained. +When the service receives the request, it removes the existing data from the Recommendation Clusters. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -752,9 +679,7 @@ This API is used to delete the content of Featured Cluster. client.deleteFeaturedCluster(); -When the service receives the request, it removes the existing data from the -Featured Cluster. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from the Featured Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -774,9 +699,7 @@ This API is used to delete the content of Continuation Cluster. client.deleteContinuationCluster(); -When the service receives the request, it removes the existing data from the -Continuation Cluster. In case of an error, the entire request is rejected and -the existing state is maintained. +When the service receives the request, it removes the existing data from the Continuation Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -796,9 +719,7 @@ This API is used to delete the content of UserAccountManagement Cluster. client.deleteUserManagementCluster(); -When the service receives the request, it removes the existing data from the -UserAccountManagement Cluster. In case of an error, the entire request is -rejected and the existing state is maintained. +When the service receives the request, it removes the existing data from the UserAccountManagement Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -828,15 +749,11 @@ This API is used to delete the content of a given cluster type. .addClusterType(ClusterType.TYPE_RECOMMENDATION) .build()); -When the service receives the request, it removes the existing data from all -clusters matching the specified cluster types. Clients can choose to pass one or -many cluster types. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from all clusters matching the specified cluster types. Clients can choose to pass one or many cluster types. In case of an error, the entire request is rejected and the existing state is maintained. #### Error handling -It is highly recommended to listen to the task result from the publish APIs such -that a follow-up action can be taken to recover and resubmit an successful task. +It is highly recommended to listen to the task result from the publish APIs such that a follow-up action can be taken to recover and resubmit an successful task. ### Kotlin @@ -880,8 +797,7 @@ that a follow-up action can be taken to recover and resubmit an successful task. } }); -The error is returned as an `AppEngageException` with the cause included as an -error code. +The error is returned as an `AppEngageException` with the cause included as an error code. | Error code | Error name | Note | |---|---|---| @@ -895,23 +811,13 @@ error code. ### Step 3: Handle broadcast intents -In addition to making publish content API calls through a job, it is also -required to set up a -[`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive -the request for a content publish. +In addition to making publish content API calls through a job, it is also required to set up a [`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive the request for a content publish. -The goal of broadcast intents is mainly for app reactivation and forcing data -sync. Broadcast intents are not designed to be sent very frequently. It is only -triggered when the Engage Service determines the content might be stale (for -example, a week old). That way, there is more confidence that the user can have -a fresh content experience, even if the application has not been executed for a -long period of time. +The goal of broadcast intents is mainly for app reactivation and forcing data sync. Broadcast intents are not designed to be sent very frequently. It is only triggered when the Engage Service determines the content might be stale (for example, a week old). That way, there is more confidence that the user can have a fresh content experience, even if the application has not been executed for a long period of time. The `BroadcastReceiver` must be set up in the following two ways: -- Dynamically register an instance of the `BroadcastReceiver` class using - `Context.registerReceiver()`. This enables communication from applications - that are still live in memory. +- Dynamically register an instance of the `BroadcastReceiver` class using `Context.registerReceiver()`. This enables communication from applications that are still live in memory. ### Kotlin @@ -982,10 +888,7 @@ The `BroadcastReceiver` must be set up in the following two ways: } -- Statically declare an implementation with the `` tag in your - `AndroidManifest.xml` file. This allows the application to receive broadcast - intents when it is not running, and also allows the application to publish - the content. +- Statically declare an implementation with the `` tag in your `AndroidManifest.xml` file. This allows the application to receive broadcast intents when it is not running, and also allows the application to publish the content. -The following [intents](https://developer.android.com/reference/android/content/Intent) is sent by the -service: +The following [intents](https://developer.android.com/reference/android/content/Intent) is sent by the service: - `com.google.android.engage.action.PUBLISH_RECOMMENDATION` It is recommended to start a `publishRecommendationClusters` call when receiving this intent. - `com.google.android.engage.action.PUBLISH_FEATURED` It is recommended to start a `publishFeaturedCluster` call when receiving this intent. @@ -1014,19 +916,15 @@ service: ## Integration workflow -For a step-by-step guide on verifying your integration after it is complete, see -[Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). +For a step-by-step guide on verifying your integration after it is complete, see [Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). ## FAQs -See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for -FAQs. +See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for FAQs. ## Contact -Contact -[`engage-developers@google.com`](mailto:engage-developers@google.com) if there are -any questions during the integration process. +Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during the integration process. ## Next steps diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/listen.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/listen.md index 1bdb7c3..1285698 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/listen.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/listen.md @@ -1,47 +1,26 @@ -Boost app engagement by reaching your users where they are. Integrate Engage SDK -to deliver personalized recommendations and continuation content directly to -users across multiple on-device surfaces, like -**[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment -Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds -less than 50 KB (compressed) to the average APK and takes most apps about a -week of developer time. Learn more at our **[business -site](http://play.google.com/console/about/programs/EngageSDK)**. +Boost app engagement by reaching your users where they are. Integrate Engage SDK to deliver personalized recommendations and continuation content directly to users across multiple on-device surfaces, like **[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds less than 50 KB (compressed) to the average APK and takes most apps about a week of developer time. Learn more at our **[business site](http://play.google.com/console/about/programs/EngageSDK)**. -This guide contains instructions for developer partners to deliver audio content -(music, podcasts, audiobooks, live radio) to Engage content surfaces. +This guide contains instructions for developer partners to deliver audio content (music, podcasts, audiobooks, live radio) to Engage content surfaces. ## Integration detail ### Terminology -This integration includes the following three cluster types: **Recommendation** , -**Continuation** , and **Featured**. +This integration includes the following three cluster types: **Recommendation** , **Continuation** , and **Featured**. -- **Recommendation** clusters show personalized suggestions for content to read - from an individual developer partner. +- **Recommendation** clusters show personalized suggestions for content to read from an individual developer partner. Your recommendations take the following structure: - - **Recommendation Cluster:** A UI view that contains a group of - recommendations from the same developer partner. + - **Recommendation Cluster:** A UI view that contains a group of recommendations from the same developer partner. ![](https://developer.android.com/static/images/guide/playcore/engage/listen-term-1.png) **Figure 1.** Entertainment Space UI showing a Recommendation Cluster from a single partner. - - **Entity:** An object representing a single item in a cluster. An entity - can be a playlist, an audiobook, a podcast, and more. See the [Provide - entity data](https://developer.android.com/guide/playcore/engage/listen#provide-entity-data) section for a list of supported entity - types. + - **Entity:** An object representing a single item in a cluster. An entity can be a playlist, an audiobook, a podcast, and more. See the [Provide entity data](https://developer.android.com/guide/playcore/engage/listen#provide-entity-data) section for a list of supported entity types. ![](https://developer.android.com/static/images/guide/playcore/engage/listen-term-2.png) **Figure 2.** Entertainment Space UI showing a single Entity within a single partner's Recommendation Cluster. -- The **Continuation** cluster shows audio content recently engaged by users - from multiple developer partners in a single UI grouping. Each developer - partner will be allowed to broadcast a maximum of 10 entities in the - Continuation cluster. +- The **Continuation** cluster shows audio content recently engaged by users from multiple developer partners in a single UI grouping. Each developer partner will be allowed to broadcast a maximum of 10 entities in the Continuation cluster. ![](https://developer.android.com/static/images/guide/playcore/engage/listen-term-3.png) **Figure 3.** Entertainment Space UI showing a Continuation cluster with unfinished recommendations from multiple partners (only one recommendation is currently visible). -- The **Featured** cluster showcases a selection of items from multiple - developer partners in a single UI grouping. There will be a single Featured - cluster, which will be surfaced near the top of the UI with a priority - placement above all Recommendation clusters. Each developer partner will be - allowed to broadcast up to 10 entities in the Featured cluster. +- The **Featured** cluster showcases a selection of items from multiple developer partners in a single UI grouping. There will be a single Featured cluster, which will be surfaced near the top of the UI with a priority placement above all Recommendation clusters. Each developer partner will be allowed to broadcast up to 10 entities in the Featured cluster. ![](https://developer.android.com/static/images/guide/playcore/engage/listen-term-4.png) **Figure 4.** Entertainment Space UI showing a Featured cluster with recommendations from multiple partners (only one recommendation is currently visible). @@ -58,11 +37,9 @@ Add the `com.google.android.engage:engage-core` library to your app: ### Summary -The design is based on an implementation of a [bound -service](https://developer.android.com/guide/components/bound-services). +The design is based on an implementation of a [bound service](https://developer.android.com/guide/components/bound-services). -The data a client can publish is subject to the following limits for different -cluster types: +The data a client can publish is subject to the following limits for different cluster types: | Cluster type | Cluster limits | Maximum entity limits in a cluster | |---|---|---| @@ -72,8 +49,7 @@ cluster types: ### Step 1: Provide entity data -The SDK has defined different entities to represent each item type. We support -the following entities for the Listen category: +The SDK has defined different entities to represent each item type. We support the following entities for the Listen category: 1. `MusicAlbumEntity` 2. `MusicArtistEntity` @@ -89,8 +65,7 @@ The charts below outline available attributes and requirements for each type. #### `MusicAlbumEntity` -The `MusicAlbumEntity` object represents a music album (for example, *Midnights* -by Taylor Swift). +The `MusicAlbumEntity` object represents a music album (for example, *Midnights* by Taylor Swift). | Attribute | Requirement | Notes | |---|---|---| @@ -126,8 +101,7 @@ The `MusicArtistEntity` object represents a music arist (for example, Adele). #### `MusicTrackEntity` -The `MusicTrackEntity` object represents a music track (for example, *Yellow* by -Coldplay). +The `MusicTrackEntity` object represents a music track (for example, *Yellow* by Coldplay). | Attribute | Requirement | Notes | |---|---|---| @@ -146,8 +120,7 @@ Coldplay). #### `MusicVideoEntity` -The `MusicVideoEntity` object represents a music video (for example, -*The Weeknd - Take My Breath (Official Music Video)*). +The `MusicVideoEntity` object represents a music video (for example, *The Weeknd - Take My Breath (Official Music Video)*). | Attribute | Requirement | Notes | |---|---|---| @@ -167,8 +140,7 @@ The `MusicVideoEntity` object represents a music video (for example, #### `PlaylistEntity` -The `PlaylistEntity` object represents a music playlist (for example, the US Top -10 Playlist). +The `PlaylistEntity` object represents a music playlist (for example, the US Top 10 Playlist). | Attribute | Requirement | Notes | |---|---|---| @@ -186,8 +158,7 @@ The `PlaylistEntity` object represents a music playlist (for example, the US Top #### `PodcastSeriesEntity` -The `PodcastSeriesEntity` object represents a podcast series (for example, *This -American Life*). +The `PodcastSeriesEntity` object represents a podcast series (for example, *This American Life*). | Attribute | Requirement | Notes | |---|---|---| @@ -206,8 +177,7 @@ American Life*). #### `PodcastEpisodeEntity` -The `PodcastEpisodeEntity` object represents a podcast series (for example, -*Spark Bird, Episode 754: This American Life*). +The `PodcastEpisodeEntity` object represents a podcast series (for example, *Spark Bird, Episode 754: This American Life*). | Attribute | Requirement | Notes | |---|---|---| @@ -232,8 +202,7 @@ The `PodcastEpisodeEntity` object represents a podcast series (for example, #### `LiveRadioStationEntity` -The `LiveRadioStationEntity` object represents a live radio station (for -example, 98.1 The Breeze). +The `LiveRadioStationEntity` object represents a live radio station (for example, 98.1 The Breeze). | Attribute | Requirement | Notes | |---|---|---| @@ -249,8 +218,7 @@ example, 98.1 The Breeze). #### `AudiobookEntity` -The `AudiobookEntity` object represents an audiobook (for example, the audiobook -of *Becoming* by Michelle Obama). +The `AudiobookEntity` object represents an audiobook (for example, the audiobook of *Becoming* by Michelle Obama). | Attribute | Requirement | Notes | |---|---|---| @@ -338,13 +306,9 @@ PNG, JPG, static GIF, WebP ### Step 2: Provide Cluster data -It's recommended to have the content publish job executed in the background -(for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) -and scheduled on a regular basis or on an event basis (for example, every time -the user opens the app or when the user just added something to their cart). +It's recommended to have the content publish job executed in the background (for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) and scheduled on a regular basis or on an event basis (for example, every time the user opens the app or when the user just added something to their cart). -`AppEngagePublishClient` is responsible for publishing clusters. Following -APIs are available in the client: +`AppEngagePublishClient` is responsible for publishing clusters. Following APIs are available in the client: - `isServiceAvailable` - `publishRecommendationClusters` @@ -360,16 +324,29 @@ APIs are available in the client: #### `isServiceAvailable` -This API is used to check if the service is available for integration and -whether the content can be presented on the device. +This API is used to check if the service is available for integration and whether the content can be presented on the device. ##### For Engage SDK v1.6.0 and higher (Recommended) -You can check the service availability for every cluster type that you intend to -publish. The `isServiceAvailable` API accepts a request object, -`ServiceAvailabilityRequest`, which contains the cluster types for which service -availability needs to be checked. You can find the `ClusterType` enum values -required for `ServiceAvailabilityRequest` from the following table. +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/play/engage-sdk-integration) + +### Engage SDK integration + +To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill engage-sdk-integration + +If your team uses AI coding tools (such as Gemini in Android Studio), you can automate this migration by prompting your AI assistant: + + Use the engage-sdk-integration skill to use Engage SDK 1.6.0 and refactor isServiceAvailable to pass ServiceAvailabilityRequest for publishing all cluster types. + +
+ +You can check the service availability for every cluster type that you intend to publish. The `isServiceAvailable` API accepts a request object, `ServiceAvailabilityRequest`, which contains the cluster types for which service availability needs to be checked. You can find the `ClusterType` enum values required for `ServiceAvailabilityRequest` from the following table. | Cluster Type | Cluster Type Constant | Integer Value | |---|---|---| @@ -427,25 +404,11 @@ required for `ServiceAvailabilityRequest` from the following table. ###### Conditional Service Availability Feature -Some integrated apps request a special configuration that enables and disables -the Engage service intermittently in order to reduce their serving cost. This -intermittent content ingestion strategy, although possible, negatively affects -the user and the product -- stale content will not be presented and some surfaces -will not be served at all. +Some integrated apps request a special configuration that enables and disables the Engage service intermittently in order to reduce their serving cost. This intermittent content ingestion strategy, although possible, negatively affects the user and the product -- stale content will not be presented and some surfaces will not be served at all. -Starting with v1.6.0, the Engage SDK allows checking availability for specific -cluster types. This provides more flexibility so that if the intermittent -content strategy was adopted by a given application, some cluster types can -follow that intermittent strategy while other cluster types are always enabled -(i.e. continuation clusters). +Starting with v1.6.0, the Engage SDK allows checking availability for specific cluster types. This provides more flexibility so that if the intermittent content strategy was adopted by a given application, some cluster types can follow that intermittent strategy while other cluster types are always enabled (i.e. continuation clusters). -If the Engage service should not be 'continuously' enabled on all supported -devices for whatever reason, and is configured for intermittent ingestion for -any set of devices, all continuation cluster publications (e.g. Continue -Listening) will be still enabled by default configuration, and the rest of -the cluster types will be enabled and disabled intermittently. If -intermittent ingestion applies to you but this default configuration is not -suitable for your needs, please contact engage-developers@google.com. +If the Engage service should not be 'continuously' enabled on all supported devices for whatever reason, and is configured for intermittent ingestion for any set of devices, all continuation cluster publications (e.g. Continue Listening) will be still enabled by default configuration, and the rest of the cluster types will be enabled and disabled intermittently. If intermittent ingestion applies to you but this default configuration is not suitable for your needs, please contact engage-developers@google.com. ##### For SDK versions prior to v1.6.0 (Deprecated) @@ -517,14 +480,12 @@ This API is used to publish a list of `RecommendationCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `RecommendationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Recommendation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFeaturedCluster` @@ -553,14 +514,12 @@ This API is used to publish a list of `FeaturedCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FeaturedCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Featured Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishContinuationCluster` @@ -591,20 +550,16 @@ This API is used to publish a `ContinuationCluster` object. .build()) .build()) -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ContinuationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Continuation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishUserAccountManagementRequest` -This API is used to publish a Sign In card . The signin action directs users to -the app's sign in page so that the app can publish content (or provide more -personalized content) +This API is used to publish a Sign In card . The signin action directs users to the app's sign in page so that the app can publish content (or provide more personalized content) The following metadata is part of the Sign In Card - @@ -657,21 +612,16 @@ The following metadata is part of the Sign In Card - .setSignInCardEntity(SIGN_IN_CARD_ENTITY) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `UserAccountManagementCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated UserAccountManagementCluster Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `updatePublishStatus` -If for any internal business reason, none of the clusters is published, -we **strongly recommend** updating the publish status using the -**updatePublishStatus** API. -This is important because : +If for any internal business reason, none of the clusters is published, we **strongly recommend** updating the publish status using the **updatePublishStatus** API. This is important because : - Providing the status in all scenarios, even when the content is published (STATUS == PUBLISHED), is critical to populate dashboards that use this explicit status to convey the health and other metrics of your integration. - If no content is published but the integration status isn't broken (STATUS == NOT_PUBLISHED), Google can avoid triggering alerts in the app health dashboards. It confirms that content is not published due to an **expected** situation from the provider's standpoint. @@ -711,11 +661,7 @@ The list of eligible publish status codes are : // Reach out to engage-developers@ before using this enum. AppEngagePublishStatusCode.NOT_PUBLISHED_OTHER -If the content is not published due to a user not logged in, -Google would recommend publishing the Sign In Card. -If for any reason providers are not able to publish the Sign In Card -then we recommend calling the **updatePublishStatus** API -with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** +If the content is not published due to a user not logged in, Google would recommend publishing the Sign In Card. If for any reason providers are not able to publish the Sign In Card then we recommend calling the **updatePublishStatus** API with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** ### Kotlin @@ -746,9 +692,7 @@ This API is used to delete the content of Recommendation Clusters. client.deleteRecommendationClusters(); -When the service receives the request, it removes the existing data from the -Recommendation Clusters. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Recommendation Clusters. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -768,9 +712,7 @@ This API is used to delete the content of Featured Cluster. client.deleteFeaturedCluster(); -When the service receives the request, it removes the existing data from the -Featured Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Featured Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -790,9 +732,7 @@ This API is used to delete the content of Continuation Cluster. client.deleteContinuationCluster(); -When the service receives the request, it removes the existing data from the -Continuation Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Continuation Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -812,9 +752,7 @@ This API is used to delete the content of UserAccountManagement Cluster. client.deleteUserManagementCluster(); -When the service receives the request, it removes the existing data from the -UserAccountManagement Cluster. In case of an error, the entire request is -rejected and the existing state is maintained. +When the service receives the request, it removes the existing data from the UserAccountManagement Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -844,15 +782,11 @@ This API is used to delete the content of a given cluster type. ... .build()); -When the service receives the request, it removes the existing data from all -clusters matching the specified cluster types. Clients can choose to pass one or -many cluster types. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from all clusters matching the specified cluster types. Clients can choose to pass one or many cluster types. In case of an error, the entire request is rejected and the existing state is maintained. #### Error handling -It is highly recommended to listen to the task result from the publish APIs such -that a follow-up action can be taken to recover and resubmit an successful task. +It is highly recommended to listen to the task result from the publish APIs such that a follow-up action can be taken to recover and resubmit an successful task. client.publishRecommendationClusters( new PublishRecommendationClustersRequest.Builder() @@ -874,8 +808,7 @@ that a follow-up action can be taken to recover and resubmit an successful task. } }); -The error is returned as an `AppEngageException` with the cause included as an -error code. +The error is returned as an `AppEngageException` with the cause included as an error code. | Error code | Error name | Note | |---|---|---| @@ -889,23 +822,13 @@ error code. ### Step 3: Handle broadcast intents -In addition to making publish content API calls through a job, it is also -required to set up a -[`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive -the request for a content publish. +In addition to making publish content API calls through a job, it is also required to set up a [`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive the request for a content publish. -The goal of broadcast intents is mainly for app reactivation and forcing data -sync. Broadcast intents are not designed to be sent very frequently. It is only -triggered when the Engage Service determines the content might be stale (for -example, a week old). That way, there is more confidence that the user can have -a fresh content experience, even if the application has not been executed for a -long period of time. +The goal of broadcast intents is mainly for app reactivation and forcing data sync. Broadcast intents are not designed to be sent very frequently. It is only triggered when the Engage Service determines the content might be stale (for example, a week old). That way, there is more confidence that the user can have a fresh content experience, even if the application has not been executed for a long period of time. The `BroadcastReceiver` must be set up in the following two ways: -- Dynamically register an instance of the `BroadcastReceiver` class using - `Context.registerReceiver()`. This enables communication from applications - that are still live in memory. +- Dynamically register an instance of the `BroadcastReceiver` class using `Context.registerReceiver()`. This enables communication from applications that are still live in memory. ### Kotlin @@ -976,10 +899,7 @@ The `BroadcastReceiver` must be set up in the following two ways: } -- Statically declare an implementation with the `` tag in your - `AndroidManifest.xml` file. This allows the application to receive broadcast - intents when it is not running, and also allows the application to publish - the content. +- Statically declare an implementation with the `` tag in your `AndroidManifest.xml` file. This allows the application to receive broadcast intents when it is not running, and also allows the application to publish the content. -The following [intents](https://developer.android.com/reference/android/content/Intent) will be sent by the -service: +The following [intents](https://developer.android.com/reference/android/content/Intent) will be sent by the service: - `com.google.android.engage.action.PUBLISH_RECOMMENDATION` It is recommended to start a `publishRecommendationClusters` call when receiving this intent. - `com.google.android.engage.action.PUBLISH_FEATURED` It is recommended to start a `publishFeaturedCluster` call when receiving this intent. @@ -1008,20 +927,15 @@ service: ## Integration workflow -For a step-by-step guide on verifying your integration after it is complete, see -[Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). +For a step-by-step guide on verifying your integration after it is complete, see [Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). ## FAQs -See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for -FAQs. +See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for FAQs. ## Contact -Contact -[`engage-developers@google.com`](mailto:engage-developers@google.com) if there are -any questions during the integration process. Our team will reply as soon as -possible. +Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during the integration process. Our team will reply as soon as possible. ## Next steps diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/otherverticals.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/otherverticals.md index f1e7de9..67463e0 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/otherverticals.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/otherverticals.md @@ -1,86 +1,43 @@ -Boost app engagement by reaching your users where they are. Integrate Engage SDK -to deliver personalized recommendations and continuation content directly to -users across multiple on-device surfaces, like -**[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment -Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds -less than 50 KB (compressed) to the average APK and takes most apps about a -week of developer time. Learn more at our **[business -site](http://play.google.com/console/about/programs/EngageSDK)**. +Boost app engagement by reaching your users where they are. Integrate Engage SDK to deliver personalized recommendations and continuation content directly to users across multiple on-device surfaces, like **[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds less than 50 KB (compressed) to the average APK and takes most apps about a week of developer time. Learn more at our **[business site](http://play.google.com/console/about/programs/EngageSDK)**. -This document contains instructions for developer partners to integrate new -content like reservations, events, lodging, places of interest, people and other -content that might not belong to any of these categories. +This document contains instructions for developer partners to integrate new content like reservations, events, lodging, places of interest, people and other content that might not belong to any of these categories. ## Integration detail ### Terminology -This integration includes the following three cluster types: **Recommendation** , -**Featured** , and **Continuation**. +This integration includes the following three cluster types: **Recommendation** , **Featured** , and **Continuation**. -- **Recommendation** clusters show personalized suggestions from an individual - developer partner. It is a UI view that contains a group of recommendations - from the same developer partner. +- **Recommendation** clusters show personalized suggestions from an individual developer partner. It is a UI view that contains a group of recommendations from the same developer partner. - - **ArticleEntity**: ArticleEntity that represents a text-based - recommendation for content that is relevant to more than one category - of content. ArticleEntity item allows developers to provide a variety of - text and image content with more metadata to articulate the information - to the users compared to GenericFeaturedEntity. Ex: Marketing content, - News snippet + - **ArticleEntity**: ArticleEntity that represents a text-based recommendation for content that is relevant to more than one category of content. ArticleEntity item allows developers to provide a variety of text and image content with more metadata to articulate the information to the users compared to GenericFeaturedEntity. Ex: Marketing content, News snippet ![](https://developer.android.com/static/images/guide/playcore/engage/article-entity-travel.png) **Figure 1:** UI showing a single ArticleEntity within Recommendations cluster. - - **EventEntity**: EventEntity represents an event happening in the - future. Event start time is a critical piece of information that - needs to be conveyed to the users. + - **EventEntity**: EventEntity represents an event happening in the future. Event start time is a critical piece of information that needs to be conveyed to the users. ![](https://developer.android.com/static/images/guide/playcore/engage/event-entity-travel.png) **Figure 2:** UI showing a single EventEntity within Recommendations cluster. - - **LodgingEntity**: LodgingEntity represents an accommodation, such - as a hotel, apartment, vacation home for short term and long term - rental. + - **LodgingEntity**: LodgingEntity represents an accommodation, such as a hotel, apartment, vacation home for short term and long term rental. ![](https://developer.android.com/static/images/guide/playcore/engage/lodging-entity-travel.png) **Figure 3:** UI showing a single LodgingEntity within Recommendations cluster. - - **StoreEntity**: StoreEntity represents a store, restaurant, cafe - etc. It highlights content where a dining venue or store is the - critical piece of information that needs to be conveyed to the - users. + - **StoreEntity**: StoreEntity represents a store, restaurant, cafe etc. It highlights content where a dining venue or store is the critical piece of information that needs to be conveyed to the users. ![](https://developer.android.com/static/images/guide/playcore/engage/store-entity-travel.png) **Figure 4:** UI showing a single StoreEntity within Recommendations cluster. - - **PointOfInterestEntity**: PointOfInterestEntity represents a - place of interest like, a gas station, event venue, theme park, - museum, tourist attraction, hiking trail etc. It highlights content - where location is a critical piece of information that needs to be - conveyed to the users. It shouldn't be used for lodging, a store or - a dining venue. + - **PointOfInterestEntity**: PointOfInterestEntity represents a place of interest like, a gas station, event venue, theme park, museum, tourist attraction, hiking trail etc. It highlights content where location is a critical piece of information that needs to be conveyed to the users. It shouldn't be used for lodging, a store or a dining venue. ![](https://developer.android.com/static/images/guide/playcore/engage/poi-entity-travel.png) **Figure 5:** UI showing a single PointOfInterestEntity within Recommendations cluster. - - **PersonEntity**: PersonEntity represents a person. The recommendations - could be to highlight a person in categories like health and fitness, - sports, dating, etc. + - **PersonEntity**: PersonEntity represents a person. The recommendations could be to highlight a person in categories like health and fitness, sports, dating, etc. ![](https://developer.android.com/static/images/guide/playcore/engage/person-entity-dating.png) **Figure 5:** UI showing a single PersonEntity within Recommendations cluster. -- The **Continuation** cluster shows content recently engaged by users from - multiple developer partners in a single UI grouping. Each developer partner - will be allowed to broadcast a maximum of 10 entities in the Continuation - cluster. +- The **Continuation** cluster shows content recently engaged by users from multiple developer partners in a single UI grouping. Each developer partner will be allowed to broadcast a maximum of 10 entities in the Continuation cluster. Your continuation content can take the following structure: - - **ArticleEntity**: ArticleEntity that represents a text-based - recommendation for content that is relevant to more than one category - of content. This entity can be used to represent unfinished news - articles or other content that the user would like to continue consuming - from where they left it. Ex: Marketing content, News snippet + - **ArticleEntity**: ArticleEntity that represents a text-based recommendation for content that is relevant to more than one category of content. This entity can be used to represent unfinished news articles or other content that the user would like to continue consuming from where they left it. Ex: Marketing content, News snippet ![](https://developer.android.com/static/images/guide/playcore/engage/article-entity-continuation-travel.png) **Figure 6.** UI showing a single ArticleEntity within a Continuation cluster. - - **RestaurantReservationEntity**: RestaurantReservationEntity represents - a reservation for a restaurant or cafe and helps users track upcoming or - ongoing restaurant reservations. + - **RestaurantReservationEntity**: RestaurantReservationEntity represents a reservation for a restaurant or cafe and helps users track upcoming or ongoing restaurant reservations. ![](https://developer.android.com/static/images/guide/playcore/engage/restaurant-reservation-entity-travel.png) **Figure 7.** UI showing a single RestaurantReservationEntity within a Continuation cluster. - - **EventReservationEntity**: EventReservationEntity represents a - reservation for an event and helps users track upcoming or ongoing - events reservations. Events could include, but not limited to the - following: + - **EventReservationEntity**: EventReservationEntity represents a reservation for an event and helps users track upcoming or ongoing events reservations. Events could include, but not limited to the following: - Sports events like reservation for a football match - Gaming events like reservation for eSports @@ -90,34 +47,18 @@ This integration includes the following three cluster types: **Recommendation** - Education / Training sessions reservations ![](https://developer.android.com/static/images/guide/playcore/engage/event-reservation-entity-travel.png) **Figure 8.** UI showing a single EventReservationEntity within a Continuation cluster. - - **LodgingReservationEntity**: LodgingEntityReservation represents a - reservation for a travel lodging and helps users track upcoming or - ongoing hotel or vacation rental reservations. + - **LodgingReservationEntity**: LodgingEntityReservation represents a reservation for a travel lodging and helps users track upcoming or ongoing hotel or vacation rental reservations. ![](https://developer.android.com/static/images/guide/playcore/engage/lodging-reservation-entity-travel.png) **Figure 9.** UI showing a single LodgingReservationEntity within a Continuation cluster. - - **TransportationReservationEntity**: TransportationReservationEntity - represents a reservation for transportation by any mode and helps users - track reservations for upcoming or ongoing flight, ferry, train, bus, - ride-hailing, or cruise. + - **TransportationReservationEntity**: TransportationReservationEntity represents a reservation for transportation by any mode and helps users track reservations for upcoming or ongoing flight, ferry, train, bus, ride-hailing, or cruise. ![](https://developer.android.com/static/images/guide/playcore/engage/transportation-reservation-entity-travel.png) **Figure 10.** UI showing a single TransportationReservationEntity within a Continuation cluster. - - **VehicleRentalReservationEntity**: VehicleRentalReservationEntity - represents a vehicle rental reservation and helps users track upcoming - or ongoing vehicle rental reservations. + - **VehicleRentalReservationEntity**: VehicleRentalReservationEntity represents a vehicle rental reservation and helps users track upcoming or ongoing vehicle rental reservations. ![](https://developer.android.com/static/images/guide/playcore/engage/vehicle-rental-reservation-entity-travel.png) **Figure 11.** UI showing a single VehicleRentalReservationEntity within a Continuation cluster. -- The **Featured** cluster is a UI view that showcases the chosen hero - `GenericFeaturedEntity` from many developer partners in one UI grouping. - There is a single Featured cluster, which is surfaced near the top of the - UI, with a priority placement above all Recommendation clusters. Each - developer partner is allowed to broadcast a single entity of a supported - type in Featured, with many entities (potentially of different types) from - multiple app developers in the Featured cluster. +- The **Featured** cluster is a UI view that showcases the chosen hero `GenericFeaturedEntity` from many developer partners in one UI grouping. There is a single Featured cluster, which is surfaced near the top of the UI, with a priority placement above all Recommendation clusters. Each developer partner is allowed to broadcast a single entity of a supported type in Featured, with many entities (potentially of different types) from multiple app developers in the Featured cluster. - - **GenericFeaturedEntity**: GenericFeaturedEntity differs from - Recommendation item in that Featured item should be used for a single - top content from developers and should represent the single most - important content that will be interesting and relevant to users. + - **GenericFeaturedEntity**: GenericFeaturedEntity differs from Recommendation item in that Featured item should be used for a single top content from developers and should represent the single most important content that will be interesting and relevant to users. ![](https://developer.android.com/static/images/guide/playcore/engage/featured-item-health-and-fitness.png) **Figure 12:** UI showing a single hero GenericFeaturedEntity card within a Featured cluster @@ -134,11 +75,9 @@ Add the `com.google.android.engage:engage-core` library to your app: ### Summary -The design is based on an implementation of a -[bound service](https://developer.android.com/guide/components/bound-services). +The design is based on an implementation of a [bound service](https://developer.android.com/guide/components/bound-services). -The data a client can publish is subject to the following limits for different -cluster types: +The data a client can publish is subject to the following limits for different cluster types: | Cluster type | Cluster limits | Minimum entity limits in a cluster | Maximum entity limits in a cluster | |---|---|---|---| @@ -148,8 +87,7 @@ cluster types: ### Step 1: Provide entity data -The SDK has defined different entities to represent each item type. We support -the following entities for the others category: +The SDK has defined different entities to represent each item type. We support the following entities for the others category: 1. `GenericFeaturedEntity` 2. `ArticleEntity` @@ -257,8 +195,7 @@ The charts below outline available attributes and requirements for each type. #### `StoreEntity` -The `StoreEntity` object represents an individual store that developer partners -want to publish, such as a restaurant or a grocery store. +The `StoreEntity` object represents an individual store that developer partners want to publish, such as a restaurant or a grocery store. | Attribute | Requirement | Description | Format | |---|---|---|---| @@ -493,8 +430,7 @@ Required specifications for image assets are listed in this table: | Landscape (1.91x1) | 600x314 | 1200x628 | | Portrait (4x5) | 480x600 | 960x1200 | -The images are required to be hosted on public CDNs so that Google can access -them. +The images are required to be hosted on public CDNs so that Google can access them. *File formats* @@ -511,8 +447,7 @@ PNG, JPG, static GIF, WebP #### Content Category -The content category allows apps to publish content belonging to multiple -categories. This maps the content with some of the predefined categories namely: +The content category allows apps to publish content belonging to multiple categories. This maps the content with some of the predefined categories namely: - `TYPE_EDUCATION` - `TYPE_SPORTS` @@ -532,33 +467,25 @@ categories. This maps the content with some of the predefined categories namely: - `TYPE_PARENTING` - `TYPE_DATING` -The images are required to be hosted on public CDNs so that Google can access -them. +The images are required to be hosted on public CDNs so that Google can access them. *Guidelines to use the content categories* 1. Some entities like **ArticleEntity** and **GenericFeaturedEntity** are eligible to use any of the content categories. For other entities like **EventEntity** , **EventReservationEntity** , **PointOfInterestEntity**, only a subset of these categories are eligible. Check the list of categories eligible for an entity type before populating the list. -2. Use the specific entity type for some content categories over a combination - of the Generic entities and the ContentCategory: +2. Use the specific entity type for some content categories over a combination of the Generic entities and the ContentCategory: - TYPE_MOVIES_AND_TV_SHOWS - Check out the entities from [Watch integration guide](https://developer.android.com/guide/playcore/engage/watch) before using the generic entities. - TYPE_BOOKS - Check out the [EbookEntity](https://developer.android.com/guide/playcore/engage/read#ebookentity) before using the generic entities. - TYPE_AUDIOBOOKS - Check out [AudiobookEntity](https://developer.android.com/guide/playcore/engage/read#audiobookentity) before using the generic entities. - TYPE_SHOPPING - Check out [ShoppingEntity](https://developer.android.com/guide/playcore/engage/shopping#shoppingEntity) before using the generic entities. - TYPE_FOOD_AND_DRINK - Check out entities from [Food Integration guide](https://developer.android.com/guide/playcore/engage/food) before using the generic entities. -3. The ContentCategory field is optional and should be left blank if the - content doesn't belong to any of the categories mentioned earlier. +3. The ContentCategory field is optional and should be left blank if the content doesn't belong to any of the categories mentioned earlier. -4. In case multiple content categories are provided, provide them in the order - of relevance to the content with the most relevant content category placed - first in the list. +4. In case multiple content categories are provided, provide them in the order of relevance to the content with the most relevant content category placed first in the list. ### Step 2: Provide Cluster data -It is recommended to have the content publish job executed in the background -(for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) -and scheduled on a regular basis or on an event basis (for example, every time -the user opens the app or when the user just added something to their cart). +It is recommended to have the content publish job executed in the background (for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) and scheduled on a regular basis or on an event basis (for example, every time the user opens the app or when the user just added something to their cart). `AppEngagePublishClient` is responsible for publishing clusters. @@ -578,16 +505,29 @@ There are following APIs to publish clusters in the client: #### `isServiceAvailable` -This API is used to check if the service is available for integration and -whether the content can be presented on the device. +This API is used to check if the service is available for integration and whether the content can be presented on the device. ##### For Engage SDK v1.6.0 and higher (Recommended) -You can check the service availability for every cluster type that you intend to -publish. The `isServiceAvailable` API accepts a request object, -`ServiceAvailabilityRequest`, which contains the cluster types for which service -availability needs to be checked. You can find the `ClusterType` enum values -required for `ServiceAvailabilityRequest` from the following table. +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/play/engage-sdk-integration) + +### Engage SDK integration + +To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill engage-sdk-integration + +If your team uses AI coding tools (such as Gemini in Android Studio), you can automate this migration by prompting your AI assistant: + + Use the engage-sdk-integration skill to use Engage SDK 1.6.0 and refactor isServiceAvailable to pass ServiceAvailabilityRequest for publishing all cluster types. + +
+ +You can check the service availability for every cluster type that you intend to publish. The `isServiceAvailable` API accepts a request object, `ServiceAvailabilityRequest`, which contains the cluster types for which service availability needs to be checked. You can find the `ClusterType` enum values required for `ServiceAvailabilityRequest` from the following table. | Cluster Type | Cluster Type Constant | Integer Value | |---|---|---| @@ -654,26 +594,11 @@ required for `ServiceAvailabilityRequest` from the following table. ###### Conditional Service Availability Feature -Some integrated apps request a special configuration that enables and disables -the Engage service intermittently in order to reduce their serving cost. This -intermittent content ingestion strategy, although possible, negatively affects -the user and the product -- stale content will not be presented and some surfaces -will not be served at all. +Some integrated apps request a special configuration that enables and disables the Engage service intermittently in order to reduce their serving cost. This intermittent content ingestion strategy, although possible, negatively affects the user and the product -- stale content will not be presented and some surfaces will not be served at all. -Starting with v1.6.0, the Engage SDK allows checking availability for specific -cluster types. This provides more flexibility so that if the intermittent -content strategy was adopted by a given application, some cluster types can -follow that intermittent strategy while other cluster types are always enabled -(i.e. continuation clusters). +Starting with v1.6.0, the Engage SDK allows checking availability for specific cluster types. This provides more flexibility so that if the intermittent content strategy was adopted by a given application, some cluster types can follow that intermittent strategy while other cluster types are always enabled (i.e. continuation clusters). -If the Engage service should not be 'continuously' enabled on all supported -devices for whatever reason, and is configured for intermittent ingestion for -any set of devices, all continuation cluster publications (e.g. Continue -Reading and Reservations) will be still enabled by default configuration, -and the rest of the cluster types will be enabled and disabled -intermittently. If intermittent ingestion applies to you but this default -configuration is not suitable for your needs, please contact -engage-developers@google.com. +If the Engage service should not be 'continuously' enabled on all supported devices for whatever reason, and is configured for intermittent ingestion for any set of devices, all continuation cluster publications (e.g. Continue Reading and Reservations) will be still enabled by default configuration, and the rest of the cluster types will be enabled and disabled intermittently. If intermittent ingestion applies to you but this default configuration is not suitable for your needs, please contact engage-developers@google.com. ##### For SDK versions prior to v1.6.0 (Deprecated) @@ -747,14 +672,12 @@ This API is used to publish a list of `RecommendationCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `RecommendationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Recommendation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFeaturedCluster` @@ -785,14 +708,12 @@ This API is used to publish a list of `FeaturedCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FeaturedCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Featured Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishContinuationCluster` @@ -823,20 +744,16 @@ This API is used to publish a `ContinuationCluster` object. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ContinuationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Continuation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishUserAccountManagementRequest` -This API is used to publish a Sign In card . The signin action directs users to -the app's sign in page so that the app can publish content (or provide more -personalized content) +This API is used to publish a Sign In card . The signin action directs users to the app's sign in page so that the app can publish content (or provide more personalized content) The following metadata is part of the Sign In Card - @@ -889,20 +806,16 @@ The following metadata is part of the Sign In Card - .setSignInCardEntity(SIGN_IN_CARD_ENTITY) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `UserAccountManagementCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated UserAccountManagementCluster Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `updatePublishStatus` -If for any internal business reason, none of the clusters is published, we -**strongly recommend** updating the publish status using the -**updatePublishStatus** API. This is important because : +If for any internal business reason, none of the clusters is published, we **strongly recommend** updating the publish status using the **updatePublishStatus** API. This is important because : - Providing the status in all scenarios, even when the content is published (STATUS == PUBLISHED), is critical to populate dashboards that use this explicit status to convey the health and other metrics of your integration. - If no content is published but the integration status isn't broken (STATUS == NOT_PUBLISHED), Google can avoid triggering alerts in the app health dashboards. It confirms that content is not published due to an **expected** situation from the provider's standpoint. @@ -942,11 +855,7 @@ The list of eligible publish status codes are : // Reach out to engage-developers@ before using this enum. AppEngagePublishStatusCode.NOT_PUBLISHED_OTHER -If the content is not published due to a user not logged in, Google would -recommend publishing the Sign In Card. If for any reason providers are not able -to publish the Sign In Card then we recommend calling the -**updatePublishStatus** API with the status code -**NOT_PUBLISHED_REQUIRES_SIGN_IN** +If the content is not published due to a user not logged in, Google would recommend publishing the Sign In Card. If for any reason providers are not able to publish the Sign In Card then we recommend calling the **updatePublishStatus** API with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** ### Kotlin @@ -977,9 +886,7 @@ This API is used to delete the content of Recommendation Clusters. client.deleteRecommendationClusters(); -When the service receives the request, it removes the existing data from the -Recommendation Clusters. In case of an error, the entire request is rejected and -the existing state is maintained. +When the service receives the request, it removes the existing data from the Recommendation Clusters. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -999,9 +906,7 @@ This API is used to delete the content of Featured Cluster. client.deleteFeaturedCluster(); -When the service receives the request, it removes the existing data from the -Featured Cluster. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from the Featured Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -1021,9 +926,7 @@ This API is used to delete the content of Continuation Cluster. client.deleteContinuationCluster(); -When the service receives the request, it removes the existing data from the -Continuation Cluster. In case of an error, the entire request is rejected and -the existing state is maintained. +When the service receives the request, it removes the existing data from the Continuation Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -1043,9 +946,7 @@ This API is used to delete the content of UserAccountManagement Cluster. client.deleteUserManagementCluster(); -When the service receives the request, it removes the existing data from the -UserAccountManagement Cluster. In case of an error, the entire request is -rejected and the existing state is maintained. +When the service receives the request, it removes the existing data from the UserAccountManagement Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -1075,15 +976,11 @@ This API is used to delete the content of a given cluster type. .addClusterType(ClusterType.TYPE_RECOMMENDATION) .build()); -When the service receives the request, it removes the existing data from all -clusters matching the specified cluster types. Clients can choose to pass one or -many cluster types. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from all clusters matching the specified cluster types. Clients can choose to pass one or many cluster types. In case of an error, the entire request is rejected and the existing state is maintained. #### Error handling -It is highly recommended to listen to the task result from the publish APIs such -that a follow-up action can be taken to recover and resubmit an successful task. +It is highly recommended to listen to the task result from the publish APIs such that a follow-up action can be taken to recover and resubmit an successful task. ### Kotlin @@ -1127,8 +1024,7 @@ that a follow-up action can be taken to recover and resubmit an successful task. } }); -The error is returned as an `AppEngageException` with the cause included as an -error code. +The error is returned as an `AppEngageException` with the cause included as an error code. | Error code | Error name | Note | |---|---|---| @@ -1142,23 +1038,13 @@ error code. ### Step 3: Handle broadcast intents -In addition to making publish content API calls through a job, it is also -required to set up a -[`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive -the request for a content publish. +In addition to making publish content API calls through a job, it is also required to set up a [`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive the request for a content publish. -The goal of broadcast intents is mainly for app reactivation and forcing data -sync. Broadcast intents are not designed to be sent very frequently. It is only -triggered when the Engage Service determines the content might be stale (for -example, a week old). That way, there is more confidence that the user can have -a fresh content experience, even if the application has not been executed for a -long period of time. +The goal of broadcast intents is mainly for app reactivation and forcing data sync. Broadcast intents are not designed to be sent very frequently. It is only triggered when the Engage Service determines the content might be stale (for example, a week old). That way, there is more confidence that the user can have a fresh content experience, even if the application has not been executed for a long period of time. The `BroadcastReceiver` must be set up in the following two ways: -- Dynamically register an instance of the `BroadcastReceiver` class using - `Context.registerReceiver()`. This enables communication from applications - that are still live in memory. +- Dynamically register an instance of the `BroadcastReceiver` class using `Context.registerReceiver()`. This enables communication from applications that are still live in memory. ### Kotlin @@ -1228,10 +1114,7 @@ The `BroadcastReceiver` must be set up in the following two ways: /*scheduler=*/null); } -- Statically declare an implementation with the `` tag in your - `AndroidManifest.xml` file. This allows the application to receive broadcast - intents when it is not running, and also allows the application to publish - the content. +- Statically declare an implementation with the `` tag in your `AndroidManifest.xml` file. This allows the application to receive broadcast intents when it is not running, and also allows the application to publish the content. -The following [intents](https://developer.android.com/reference/android/content/Intent) is sent by the -service: +The following [intents](https://developer.android.com/reference/android/content/Intent) is sent by the service: - `com.google.android.engage.action.PUBLISH_RECOMMENDATION` It is recommended to start a `publishRecommendationClusters` call when receiving this intent. - `com.google.android.engage.action.PUBLISH_FEATURED` It is recommended to start a `publishFeaturedCluster` call when receiving this intent. @@ -1260,19 +1142,15 @@ service: ## Integration workflow -For a step-by-step guide on verifying your integration after it is complete, see -[Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). +For a step-by-step guide on verifying your integration after it is complete, see [Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). ## FAQs -See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for -FAQs. +See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for FAQs. ## Contact -Contact -[`engage-developers@google.com`](mailto:engage-developers@google.com) if there are -any questions during the integration process. +Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during the integration process. ## Next steps diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/read.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/read.md index ccd4514..bb51a5f 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/read.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/read.md @@ -1,49 +1,29 @@ > [!IMPORTANT] > **Important:** Engage SDK has superseded Media Home, which is now deprecated. If you have an existing Media Home integration, follow the instructions in these guides to migrate your content to Engage SDK, which allows your content to be published to more devices and form factors. Please contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if you have any questions. -Boost app engagement by reaching your users where they are. Integrate Engage SDK -to deliver personalized recommendations and continuation content directly to -users across multiple on-device surfaces, like -**[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment -Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds -less than 50 KB (compressed) to the average APK and takes most apps about a -week of developer time. Learn more at our **[business -site](http://play.google.com/console/about/programs/EngageSDK)**. +Boost app engagement by reaching your users where they are. Integrate Engage SDK to deliver personalized recommendations and continuation content directly to users across multiple on-device surfaces, like **[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds less than 50 KB (compressed) to the average APK and takes most apps about a week of developer time. Learn more at our **[business site](http://play.google.com/console/about/programs/EngageSDK)**. -This guide contains instructions for developer partners to deliver reading -content (eBooks, Audiobooks, Comics/Manga) to Engage content surfaces. +This guide contains instructions for developer partners to deliver reading content (eBooks, Audiobooks, Comics/Manga) to Engage content surfaces. ## Integration detail ### Terminology -This integration includes the following three cluster types: **Recommendation** , -**Continuation** , and **Featured**. +This integration includes the following three cluster types: **Recommendation** , **Continuation** , and **Featured**. -- **Recommendation** clusters show personalized suggestions for content to read - from an individual developer partner. +- **Recommendation** clusters show personalized suggestions for content to read from an individual developer partner. Your recommendations take the following structure: - - **Recommendation Cluster:** A UI view that contains a group of - recommendations from a single developer partner. + - **Recommendation Cluster:** A UI view that contains a group of recommendations from a single developer partner. ![](https://developer.android.com/static/images/guide/playcore/engage/read-term-1.png) **Figure 1.** Entertainment Space UI showing a Recommendation Cluster from a single partner. - - **Entity:** An object representing a single item in a cluster. An entity - can be an ebook, an audio book, a book series, and more. See the [Provide - entity data](https://developer.android.com/guide/playcore/engage/read#provide-entity-data) section for a list of supported entity - types. + - **Entity:** An object representing a single item in a cluster. An entity can be an ebook, an audio book, a book series, and more. See the [Provide entity data](https://developer.android.com/guide/playcore/engage/read#provide-entity-data) section for a list of supported entity types. ![](https://developer.android.com/static/images/guide/playcore/engage/read-term-2.png) **Figure 2.** Entertainment Space UI showing a single Entity within a single partner's Recommendation Cluster. -- The **Continuation** cluster shows unfinished books from multiple developer - partners in a single UI grouping. Each developer partner will be allowed to - broadcast a maximum of 10 entities in the Continuation cluster. +- The **Continuation** cluster shows unfinished books from multiple developer partners in a single UI grouping. Each developer partner will be allowed to broadcast a maximum of 10 entities in the Continuation cluster. ![](https://developer.android.com/static/images/guide/playcore/engage/read-term-3.png) **Figure 3.** Entertainment Space UI showing a Continuation cluster with unfinished recommendations from multiple partners (only one recommendation is currently visible). -- The **Featured** cluster showcases a selection of items from multiple - developer partners in a single UI grouping. There will be a single Featured - cluster, which is surfaced near the top of the UI with a priority placement - above all Recommendation clusters. Each developer partner will be allowed to - broadcast up to 10 entities in the Featured cluster. +- The **Featured** cluster showcases a selection of items from multiple developer partners in a single UI grouping. There will be a single Featured cluster, which is surfaced near the top of the UI with a priority placement above all Recommendation clusters. Each developer partner will be allowed to broadcast up to 10 entities in the Featured cluster. ![](https://developer.android.com/static/images/guide/playcore/engage/read-term-4.png) **Figure 4.** Entertainment Space UI showing a Featured cluster with recommendations from multiple partners (only one recommendation is currently visible). @@ -60,11 +40,9 @@ Add the `com.google.android.engage:engage-core` library to your app: ### Summary -The design is based on an implementation of a [bound -service](https://developer.android.com/guide/components/bound-services). +The design is based on an implementation of a [bound service](https://developer.android.com/guide/components/bound-services). -The data a client can publish is subject to the following limits for different -cluster types: +The data a client can publish is subject to the following limits for different cluster types: | Cluster type | Cluster limits | Maximum entity limits in a cluster | |---|---|---| @@ -74,8 +52,7 @@ cluster types: ### Step 1: Provide entity data -The SDK has defined different entities to represent each item type. We support -the following entities for the Read category: +The SDK has defined different entities to represent each item type. We support the following entities for the Read category: 1. `EbookEntity` 2. `AudiobookEntity` @@ -85,8 +62,7 @@ The charts below outline available attributes and requirements for each type. #### `EbookEntity` -The `EbookEntity` object represents an ebook (for example, the ebook of -*Becoming* by Michelle Obama). +The `EbookEntity` object represents an ebook (for example, the ebook of *Becoming* by Michelle Obama). | Attribute | Requirement | Notes | |---|---|---| @@ -110,8 +86,7 @@ The `EbookEntity` object represents an ebook (for example, the ebook of #### `AudiobookEntity` -The `AudiobookEntity` object represents an audiobook (for example, the audiobook -of *Becoming* by Michelle Obama). +The `AudiobookEntity` object represents an audiobook (for example, the audiobook of *Becoming* by Michelle Obama). | Attribute | Requirement | Notes | |---|---|---| @@ -136,8 +111,7 @@ of *Becoming* by Michelle Obama). #### `BookSeriesEntity` -The `BookSeriesEntity` object represents a book series (for example, the *Harry -Potter* book series, which has 7 books). +The `BookSeriesEntity` object represents a book series (for example, the *Harry Potter* book series, which has 7 books). | Attribute | Requirement | Notes | |---|---|---| @@ -200,13 +174,9 @@ PNG, JPG, static GIF, WebP ### Step 2: Provide Cluster data -It's recommended to have the content publish job executed in the background -(for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) -and scheduled on a regular basis or on an event basis (for example, every time -the user opens the app or when the user just added something to their cart). +It's recommended to have the content publish job executed in the background (for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) and scheduled on a regular basis or on an event basis (for example, every time the user opens the app or when the user just added something to their cart). -`AppEngagePublishClient` is responsible for publishing clusters. Following -APIs are available in the client: +`AppEngagePublishClient` is responsible for publishing clusters. Following APIs are available in the client: - `isServiceAvailable` - `publishRecommendationClusters` @@ -222,16 +192,29 @@ APIs are available in the client: #### `isServiceAvailable` -This API is used to check if the service is available for integration and -whether the content can be presented on the device. +This API is used to check if the service is available for integration and whether the content can be presented on the device. ##### For Engage SDK v1.6.0 and higher (Recommended) -You can check the service availability for every cluster type that you intend to -publish. The `isServiceAvailable` API accepts a request object, -`ServiceAvailabilityRequest`, which contains the cluster types for which service -availability needs to be checked. You can find the `ClusterType` enum values -required for `ServiceAvailabilityRequest` from the following table. +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/play/engage-sdk-integration) + +### Engage SDK integration + +To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill engage-sdk-integration + +If your team uses AI coding tools (such as Gemini in Android Studio), you can automate this migration by prompting your AI assistant: + + Use the engage-sdk-integration skill to use Engage SDK 1.6.0 and refactor isServiceAvailable to pass ServiceAvailabilityRequest for publishing all cluster types. + +
+ +You can check the service availability for every cluster type that you intend to publish. The `isServiceAvailable` API accepts a request object, `ServiceAvailabilityRequest`, which contains the cluster types for which service availability needs to be checked. You can find the `ClusterType` enum values required for `ServiceAvailabilityRequest` from the following table. | Cluster Type | Cluster Type Constant | Integer Value | |---|---|---| @@ -288,26 +271,11 @@ required for `ServiceAvailabilityRequest` from the following table. ###### Conditional Service Availability Feature -Some integrated apps request a special configuration that enables and disables -the Engage service intermittently in order to reduce their serving cost. This -intermittent content ingestion strategy, although possible, negatively affects -the user and the product -- stale content will not be presented and some surfaces -will not be served at all. +Some integrated apps request a special configuration that enables and disables the Engage service intermittently in order to reduce their serving cost. This intermittent content ingestion strategy, although possible, negatively affects the user and the product -- stale content will not be presented and some surfaces will not be served at all. -Starting with v1.6.0, the Engage SDK allows checking availability for specific -cluster types. This provides more flexibility so that if the intermittent -content strategy was adopted by a given application, some cluster types can -follow that intermittent strategy while other cluster types are always enabled -(i.e. continuation clusters). +Starting with v1.6.0, the Engage SDK allows checking availability for specific cluster types. This provides more flexibility so that if the intermittent content strategy was adopted by a given application, some cluster types can follow that intermittent strategy while other cluster types are always enabled (i.e. continuation clusters). -If the Engage service should not be 'continuously' enabled on all supported -devices for whatever reason, and is configured for intermittent ingestion for -any set of devices, all continuation cluster publications (e.g. Continue -Reading) will be still enabled by default -configuration, and the rest of the cluster types will be enabled and disabled -intermittently. If intermittent ingestion applies to you but this default -configuration is not suitable for your needs, please contact -engage-developers@google.com. +If the Engage service should not be 'continuously' enabled on all supported devices for whatever reason, and is configured for intermittent ingestion for any set of devices, all continuation cluster publications (e.g. Continue Reading) will be still enabled by default configuration, and the rest of the cluster types will be enabled and disabled intermittently. If intermittent ingestion applies to you but this default configuration is not suitable for your needs, please contact engage-developers@google.com. ##### For SDK versions prior to v1.6.0 (Deprecated) @@ -379,14 +347,12 @@ This API is used to publish a list of `RecommendationCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `RecommendationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Recommendation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFeaturedCluster` @@ -415,14 +381,12 @@ This API is used to publish a list of `FeaturedCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FeaturedCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Featured Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishContinuationCluster` @@ -453,20 +417,16 @@ This API is used to publish a `ContinuationCluster` object. .build()) .build()) -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ContinuationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Continuation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishUserAccountManagementRequest` -This API is used to publish a Sign In card . The signin action directs users to -the app's sign in page so that the app can publish content (or provide more -personalized content) +This API is used to publish a Sign In card . The signin action directs users to the app's sign in page so that the app can publish content (or provide more personalized content) The following metadata is part of the Sign In Card - @@ -519,21 +479,16 @@ The following metadata is part of the Sign In Card - .setSignInCardEntity(SIGN_IN_CARD_ENTITY) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `UserAccountManagementCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated UserAccountManagementCluster Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `updatePublishStatus` -If for any internal business reason, none of the clusters is published, -we **strongly recommend** updating the publish status using the -**updatePublishStatus** API. -This is important because : +If for any internal business reason, none of the clusters is published, we **strongly recommend** updating the publish status using the **updatePublishStatus** API. This is important because : - Providing the status in all scenarios, even when the content is published (STATUS == PUBLISHED), is critical to populate dashboards that use this explicit status to convey the health and other metrics of your integration. - If no content is published but the integration status isn't broken (STATUS == NOT_PUBLISHED), Google can avoid triggering alerts in the app health dashboards. It confirms that content is not published due to an **expected** situation from the provider's standpoint. @@ -573,11 +528,7 @@ The list of eligible publish status codes are : // Reach out to engage-developers@ before using this enum. AppEngagePublishStatusCode.NOT_PUBLISHED_OTHER -If the content is not published due to a user not logged in, -Google would recommend publishing the Sign In Card. -If for any reason providers are not able to publish the Sign In Card -then we recommend calling the **updatePublishStatus** API -with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** +If the content is not published due to a user not logged in, Google would recommend publishing the Sign In Card. If for any reason providers are not able to publish the Sign In Card then we recommend calling the **updatePublishStatus** API with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** ### Kotlin @@ -608,9 +559,7 @@ This API is used to delete the content of Recommendation Clusters. client.deleteRecommendationClusters(); -When the service receives the request, it removes the existing data from the -Recommendation Clusters. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Recommendation Clusters. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -630,9 +579,7 @@ This API is used to delete the content of Featured Cluster. client.deleteFeaturedCluster(); -When the service receives the request, it removes the existing data from the -Featured Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Featured Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -652,9 +599,7 @@ This API is used to delete the content of Continuation Cluster. client.deleteContinuationCluster(); -When the service receives the request, it removes the existing data from the -Continuation Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Continuation Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -674,9 +619,7 @@ This API is used to delete the content of UserAccountManagement Cluster. client.deleteUserManagementCluster(); -When the service receives the request, it removes the existing data from the -UserAccountManagement Cluster. In case of an error, the entire request is -rejected and the existing state is maintained. +When the service receives the request, it removes the existing data from the UserAccountManagement Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -706,15 +649,11 @@ This API is used to delete the content of a given cluster type. ... .build()); -When the service receives the request, it removes the existing data from all -clusters matching the specified cluster types. Clients can choose to pass one or -many cluster types. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from all clusters matching the specified cluster types. Clients can choose to pass one or many cluster types. In case of an error, the entire request is rejected and the existing state is maintained. #### Error handling -It is highly recommended to listen to the task result from the publish APIs such -that a follow-up action can be taken to recover and resubmit an successful task. +It is highly recommended to listen to the task result from the publish APIs such that a follow-up action can be taken to recover and resubmit an successful task. client.publishRecommendationClusters( new PublishRecommendationClustersRequest.Builder() @@ -736,8 +675,7 @@ that a follow-up action can be taken to recover and resubmit an successful task. } }); -The error is returned as an `AppEngageException` with the cause included as an -error code. +The error is returned as an `AppEngageException` with the cause included as an error code. | Error code | Error name | Note | |---|---|---| @@ -751,23 +689,13 @@ error code. ### Step 3: Handle broadcast intents -In addition to making publish content API calls through a job, it is also -required to set up a -[`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive -the request for a content publish. +In addition to making publish content API calls through a job, it is also required to set up a [`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive the request for a content publish. -The goal of broadcast intents is mainly for app reactivation and forcing data -sync. Broadcast intents are not designed to be sent very frequently. It is only -triggered when the Engage Service determines the content might be stale (for -example, a week old). That way, there is more confidence that the user can have -a fresh content experience, even if the application has not been executed for a -long period of time. +The goal of broadcast intents is mainly for app reactivation and forcing data sync. Broadcast intents are not designed to be sent very frequently. It is only triggered when the Engage Service determines the content might be stale (for example, a week old). That way, there is more confidence that the user can have a fresh content experience, even if the application has not been executed for a long period of time. The `BroadcastReceiver` must be set up in the following two ways: -- Dynamically register an instance of the `BroadcastReceiver` class using - `Context.registerReceiver()`. This enables communication from applications - that are still live in memory. +- Dynamically register an instance of the `BroadcastReceiver` class using `Context.registerReceiver()`. This enables communication from applications that are still live in memory. ### Kotlin @@ -838,10 +766,7 @@ The `BroadcastReceiver` must be set up in the following two ways: } -- Statically declare an implementation with the `` tag in your - `AndroidManifest.xml` file. This allows the application to receive broadcast - intents when it is not running, and also allows the application to publish - the content. +- Statically declare an implementation with the `` tag in your `AndroidManifest.xml` file. This allows the application to receive broadcast intents when it is not running, and also allows the application to publish the content. -The following [intents](https://developer.android.com/reference/android/content/Intent) will be sent by the -service: +The following [intents](https://developer.android.com/reference/android/content/Intent) will be sent by the service: - `com.google.android.engage.action.PUBLISH_RECOMMENDATION` It is recommended to start a `publishRecommendationClusters` call when receiving this intent. - `com.google.android.engage.action.PUBLISH_FEATURED` It is recommended to start a `publishFeaturedCluster` call when receiving this intent. @@ -870,18 +794,15 @@ service: ## Integration workflow -For a step-by-step guide on verifying your integration after it is complete, see -[Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). +For a step-by-step guide on verifying your integration after it is complete, see [Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). ## FAQs -See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for -FAQs. +See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for FAQs. ## Contact -Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during -the integration process. Our team will reply as soon as possible. +Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during the integration process. Our team will reply as soon as possible. ## Next steps diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/shopping.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/shopping.md index 4e24895..efc4644 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/shopping.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/shopping.md @@ -1,78 +1,40 @@ -Boost app engagement by reaching your users where they are. Integrate Engage SDK -to deliver personalized recommendations and continuation content directly to -users across multiple on-device surfaces, like -**[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment -Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds -less than 50 KB (compressed) to the average APK and takes most apps about a -week of developer time. Learn more at our **[business -site](http://play.google.com/console/about/programs/EngageSDK)**. +Boost app engagement by reaching your users where they are. Integrate Engage SDK to deliver personalized recommendations and continuation content directly to users across multiple on-device surfaces, like **[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds less than 50 KB (compressed) to the average APK and takes most apps about a week of developer time. Learn more at our **[business site](http://play.google.com/console/about/programs/EngageSDK)**. -This guide contains instructions for developer partners to deliver shopping -content to Engage content surfaces. +This guide contains instructions for developer partners to deliver shopping content to Engage content surfaces. ## Integration detail ### Terminology -This integration includes the following five cluster types: **Recommendation** , -**Featured** , **Shopping Cart** , **Shopping List** , **Reorder** and -**Shopping Order Tracking**. +This integration includes the following five cluster types: **Recommendation** , **Featured** , **Shopping Cart** , **Shopping List** , **Reorder** and **Shopping Order Tracking**. -- **Recommendation** clusters show personalized shopping suggestions from an - individual developer partner. These recommendations can be personalized to the - user or generalized (for example, trending items). Use these to surface - products, events, sales, promos, subscriptions as you see fit. +- **Recommendation** clusters show personalized shopping suggestions from an individual developer partner. These recommendations can be personalized to the user or generalized (for example, trending items). Use these to surface products, events, sales, promos, subscriptions as you see fit. Your recommendations take the following structure: - - **Recommendation Cluster:** A UI view that contains a group of - recommendations from the same developer partner. + - **Recommendation Cluster:** A UI view that contains a group of recommendations from the same developer partner. - **ShoppingEntity:** An object representing a single item in a cluster. -- The **Featured** cluster showcases a selection of entities from multiple - developer partners in one UI grouping. There will be a single Featured - cluster, which is surfaced near the top of the UI with a priority placement - above all Recommendation clusters. Each developer partner will be allowed to - broadcast up to 10 entities in the Featured cluster. +- The **Featured** cluster showcases a selection of entities from multiple developer partners in one UI grouping. There will be a single Featured cluster, which is surfaced near the top of the UI with a priority placement above all Recommendation clusters. Each developer partner will be allowed to broadcast up to 10 entities in the Featured cluster. -- The **Shopping Cart** cluster shows a sneak peek of shopping carts from many - developer partners in one UI grouping, nudging users to complete their - outstanding carts. There is a single Shopping Cart cluster, which is - surfaced near the top of the UI, with a priority placement above all - Recommendation clusters. Each developer partner is allowed to broadcast up to - 3 `ShoppingCart` instances in the Shopping Cart cluster. +- The **Shopping Cart** cluster shows a sneak peek of shopping carts from many developer partners in one UI grouping, nudging users to complete their outstanding carts. There is a single Shopping Cart cluster, which is surfaced near the top of the UI, with a priority placement above all Recommendation clusters. Each developer partner is allowed to broadcast up to 3 `ShoppingCart` instances in the Shopping Cart cluster. Your Shopping Cart takes the following structure: - - **Shopping Cart Cluster:** A UI view that contains a group of shopping - cart previews from many developer partners. + - **Shopping Cart Cluster:** A UI view that contains a group of shopping cart previews from many developer partners. - - **ShoppingCart:** An object representing the shopping cart preview - for a single developer partner, to be displayed in the Shopping Cart - cluster. The `ShoppingCart` must show the total count of items in the - cart and may also include images for some items in the user's cart. + - **ShoppingCart:** An object representing the shopping cart preview for a single developer partner, to be displayed in the Shopping Cart cluster. The `ShoppingCart` must show the total count of items in the cart and may also include images for some items in the user's cart. -- The **Shopping List** cluster shows a sneak peek of the shopping - lists from multiple developer partners in one UI grouping, prompting users to - return to the corresponding app to update and complete their lists. There is a - single Shopping List cluster. +- The **Shopping List** cluster shows a sneak peek of the shopping lists from multiple developer partners in one UI grouping, prompting users to return to the corresponding app to update and complete their lists. There is a single Shopping List cluster. -- The **Reorder** cluster shows a sneak peek of the previous orders from - multiple developer partners in one UI grouping, prompting users to reorder. - There is a single Reorder cluster. +- The **Reorder** cluster shows a sneak peek of the previous orders from multiple developer partners in one UI grouping, prompting users to reorder. There is a single Reorder cluster. - - Reorder cluster must show the total count of items in the - user's previous order and must also include one of the following: + - Reorder cluster must show the total count of items in the user's previous order and must also include one of the following: - Images for X items in the user's previous order. - Labels for X items in the user's previous order. -- The **Shopping Order Tracking** cluster shows a sneak peek of pending - or recently completed shopping orders from many developer partners in one UI - grouping, allowing users to track their orders. +- The **Shopping Order Tracking** cluster shows a sneak peek of pending or recently completed shopping orders from many developer partners in one UI grouping, allowing users to track their orders. - There is a single ShoppingOrderTracking cluster that is surfaced - near the top of the UI, with a priority placement above all Recommendation - clusters. Each developer partner is allowed to broadcast multiple - ShoppingOrderTrackingEntity items in the Shopping Order Tracking cluster. + There is a single ShoppingOrderTracking cluster that is surfaced near the top of the UI, with a priority placement above all Recommendation clusters. Each developer partner is allowed to broadcast multiple ShoppingOrderTrackingEntity items in the Shopping Order Tracking cluster. - Your ShoppingOrderTrackingCluster takes the following structure: - **ShoppingOrderTracking Cluster**: A UI view that contains a group of order tracking previews from many developer partners @@ -92,16 +54,13 @@ Add the `com.google.android.engage:engage-core` library to your app: implementation 'com.google.android.engage:engage-core:1.6.0' } -For more information, see [Package visibility in Android -11](https://developer.android.com/about/versions/11/privacy/package-visibility). +For more information, see [Package visibility in Android 11](https://developer.android.com/about/versions/11/privacy/package-visibility). ### Summary -The design is based on an implementation of a [bound -service](https://developer.android.com/guide/components/bound-services). +The design is based on an implementation of a [bound service](https://developer.android.com/guide/components/bound-services). -The data a client can publish is subject to the following limits for different -cluster types: +The data a client can publish is subject to the following limits for different cluster types: | Cluster type | Cluster limits | Maximum entity limits in a cluster | |---|---|---| @@ -114,8 +73,7 @@ cluster types: ### Step 1: Provide entity data -The SDK has defined different entities to represent each item type. The -following entities are supported for the Shopping category: +The SDK has defined different entities to represent each item type. The following entities are supported for the Shopping category: 1. `ShoppingEntity` 2. `ShoppingCart` @@ -127,8 +85,7 @@ The charts below outline available attributes and requirements for each type. #### `ShoppingEntity` -The `ShoppingEntity` object represents a product, promotion, deal, subscription, -or event that developer partners want to publish. +The `ShoppingEntity` object represents a product, promotion, deal, subscription, or event that developer partners want to publish. ##### `ShoppingEntity` @@ -231,10 +188,7 @@ PNG, JPG, static GIF, WebP ### Step 2: Provide Cluster data -It is recommended to have the content publish job executed in the background -(for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) -and scheduled on a regular basis or on an event basis (for example, every time -the user opens the app or when the user just added something to their cart). +It is recommended to have the content publish job executed in the background (for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) and scheduled on a regular basis or on an event basis (for example, every time the user opens the app or when the user just added something to their cart). `AppEngageShoppingClient` is responsible for publishing shopping clusters. @@ -260,16 +214,29 @@ Following APIs are exposed to publish clusters in the client: #### `isServiceAvailable` -This API is used to check if the service is available for integration and -whether the content can be presented on the device. +This API is used to check if the service is available for integration and whether the content can be presented on the device. ##### For Engage SDK v1.6.0 and higher (Recommended) -You can check the service availability for every cluster type that you intend to -publish. The `isServiceAvailable` API accepts a request object, -`ServiceAvailabilityRequest`, which contains the cluster types for which service -availability needs to be checked. You can find the `ClusterType` enum values -required for `ServiceAvailabilityRequest` from the following table. +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/play/engage-sdk-integration) + +### Engage SDK integration + +To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill engage-sdk-integration + +If your team uses AI coding tools (such as Gemini in Android Studio), you can automate this migration by prompting your AI assistant: + + Use the engage-sdk-integration skill to use Engage SDK 1.6.0 and refactor isServiceAvailable to pass ServiceAvailabilityRequest for publishing all cluster types. + +
+ +You can check the service availability for every cluster type that you intend to publish. The `isServiceAvailable` API accepts a request object, `ServiceAvailabilityRequest`, which contains the cluster types for which service availability needs to be checked. You can find the `ClusterType` enum values required for `ServiceAvailabilityRequest` from the following table. | Cluster Type | Cluster Type Constant | Integer Value | |---|---|---| @@ -331,26 +298,11 @@ required for `ServiceAvailabilityRequest` from the following table. ###### Conditional Service Availability Feature -Some integrated apps request a special configuration that enables and disables -the Engage service intermittently in order to reduce their serving cost. This -intermittent content ingestion strategy, although possible, negatively affects -the user and the product -- stale content will not be presented and some surfaces -will not be served at all. +Some integrated apps request a special configuration that enables and disables the Engage service intermittently in order to reduce their serving cost. This intermittent content ingestion strategy, although possible, negatively affects the user and the product -- stale content will not be presented and some surfaces will not be served at all. -Starting with v1.6.0, the Engage SDK allows checking availability for specific -cluster types. This provides more flexibility so that if the intermittent -content strategy was adopted by a given application, some cluster types can -follow that intermittent strategy while other cluster types are always enabled -(i.e. continuation clusters). +Starting with v1.6.0, the Engage SDK allows checking availability for specific cluster types. This provides more flexibility so that if the intermittent content strategy was adopted by a given application, some cluster types can follow that intermittent strategy while other cluster types are always enabled (i.e. continuation clusters). -If the Engage service should not be 'continuously' enabled on all supported -devices for whatever reason, and is configured for intermittent ingestion for -any set of devices, all continuation cluster publications (e.g. Shopping -Cart, Shopping List, Reorder, and Shopping Order Tracking) will be still -enabled by default configuration, and the rest of the cluster types will be -enabled and disabled intermittently. If intermittent ingestion applies to -you but this default configuration is not suitable for your needs, please -contact engage-developers@google.com. +If the Engage service should not be 'continuously' enabled on all supported devices for whatever reason, and is configured for intermittent ingestion for any set of devices, all continuation cluster publications (e.g. Shopping Cart, Shopping List, Reorder, and Shopping Order Tracking) will be still enabled by default configuration, and the rest of the cluster types will be enabled and disabled intermittently. If intermittent ingestion applies to you but this default configuration is not suitable for your needs, please contact engage-developers@google.com. ##### For SDK versions prior to v1.6.0 (Deprecated) @@ -431,14 +383,12 @@ A `RecommendationCluster` object can have the following attributes: .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - All existing Recommendation Cluster data is removed. - Data from the request is parsed and stored in new Recommendation Clusters. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFeaturedCluster` @@ -467,20 +417,16 @@ This API is used to publish a `FeaturedCluster` object. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FeaturedCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Featured Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishShoppingCarts` -This API is used to publish a list of `ShoppingCart` objects. This is -applicable to developer partner publishing separate carts per merchant. Include -merchant name in the title when using this API. +This API is used to publish a list of `ShoppingCart` objects. This is applicable to developer partner publishing separate carts per merchant. Include merchant name in the title when using this API. > [!IMPORTANT] > **Important:** The publish APIs are upsert APIs; it replaces the existing content. **Don't** call delete and publish APIs subsequently to replace the content as the publish APIs do that inherently. @@ -505,14 +451,12 @@ merchant name in the title when using this API. .build()) .build()) -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ShoppingCart` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Shopping Cart Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishShoppingLists` @@ -541,14 +485,12 @@ This API is used to publish a list of `ShoppingList` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ShoppingList` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Shopping List Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishShoppingReorderCluster` @@ -577,14 +519,12 @@ This API is used to publish a `ShoppingReorderCluster` object. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ShoppingReorderCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Reorder Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishShoppingOrderTrackingCluster` @@ -613,20 +553,16 @@ This API is used to publish a `ShoppingOrderTrackingCluster` object. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ShoppingOrderTrackingCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Shopping Order Tracking Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishUserAccountManagementRequest` -This API is used to publish a Sign In card . The signin action directs users to -the app's sign in page so that the app can publish content (or provide more -personalized content) +This API is used to publish a Sign In card . The signin action directs users to the app's sign in page so that the app can publish content (or provide more personalized content) The following metadata is part of the Sign In Card - @@ -679,21 +615,16 @@ The following metadata is part of the Sign In Card - .setSignInCardEntity(SIGN_IN_CARD_ENTITY) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `UserAccountManagementCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated UserAccountManagementCluster Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `updatePublishStatus` -If for any internal business reason, none of the clusters is published, -we **strongly recommend** updating the publish status using the -**updatePublishStatus** API. -This is important because : +If for any internal business reason, none of the clusters is published, we **strongly recommend** updating the publish status using the **updatePublishStatus** API. This is important because : - Providing the status in all scenarios, even when the content is published (STATUS == PUBLISHED), is critical to populate dashboards that use this explicit status to convey the health and other metrics of your integration. - If no content is published but the integration status isn't broken (STATUS == NOT_PUBLISHED), Google can avoid triggering alerts in the app health dashboards. It confirms that content is not published due to an **expected** situation from the provider's standpoint. @@ -733,11 +664,7 @@ The list of eligible publish status codes are : // Reach out to engage-developers@ before using this enum. AppEngagePublishStatusCode.NOT_PUBLISHED_OTHER -If the content is not published due to a user not logged in, -Google would recommend publishing the Sign In Card. -If for any reason providers are not able to publish the Sign In Card -then we recommend calling the **updatePublishStatus** API -with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** +If the content is not published due to a user not logged in, Google would recommend publishing the Sign In Card. If for any reason providers are not able to publish the Sign In Card then we recommend calling the **updatePublishStatus** API with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** ### Kotlin @@ -768,9 +695,7 @@ This API is used to delete the content of Recommendation Clusters. client.deleteRecommendationClusters(); -When the service receives the request, it removes the existing data from the -Recommendation Clusters. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Recommendation Clusters. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -790,9 +715,7 @@ This API is used to delete the content of Featured Cluster. client.deleteFeaturedCluster(); -When the service receives the request, it removes the existing data from the -Featured Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Featured Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -812,9 +735,7 @@ This API is used to delete the content of Shopping Cart Cluster. client.deleteShoppingCartCluster(); -When the service receives the request, it removes the existing data from the -Shopping Cart Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Shopping Cart Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -834,9 +755,7 @@ This API is used to delete the content of Shopping List Cluster. client.deleteShoppingListCluster(); -When the service receives the request, it removes the existing data from the -Shopping List Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Shopping List Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -856,9 +775,7 @@ This API is used to delete the content of Shopping Reorder Cluster. client.deleteShoppingReorderCluster(); -When the service receives the request, it removes the existing data from the -Shopping Reorder Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Shopping Reorder Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -878,9 +795,7 @@ This API is used to delete the content of Shopping Order Tracking Cluster. client.deleteShoppingOrderTrackingCluster(); -When the service receives the request, it removes the existing data from the -Shopping Order Tracking Cluster. In case of an error, the entire request is -rejected and the existing state is maintained. +When the service receives the request, it removes the existing data from the Shopping Order Tracking Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This API is available in versions 1.4.0 and higher. @@ -900,9 +815,7 @@ This API is used to delete the content of UserAccountManagement Cluster. client.deleteUserManagementCluster(); -When the service receives the request, it removes the existing data from the -UserAccountManagement Cluster. In case of an error, the entire request is -rejected and the existing state is maintained. +When the service receives the request, it removes the existing data from the UserAccountManagement Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -932,15 +845,11 @@ This API is used to delete the content of a given cluster type. ... .build()); -When the service receives the request, it removes the existing data from all -clusters matching the specified cluster types. Clients can choose to pass one or -many cluster types. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from all clusters matching the specified cluster types. Clients can choose to pass one or many cluster types. In case of an error, the entire request is rejected and the existing state is maintained. #### Error handling -It is highly recommended to listen to the task result from the publish APIs such -that a follow-up action can be taken to recover and resubmit an successful task. +It is highly recommended to listen to the task result from the publish APIs such that a follow-up action can be taken to recover and resubmit an successful task. ### Kotlin @@ -984,8 +893,7 @@ that a follow-up action can be taken to recover and resubmit an successful task. } }); -The error is returned as an `AppEngageException` with the cause included as an -error code. +The error is returned as an `AppEngageException` with the cause included as an error code. | Error code | Error name | Note | |---|---|---| @@ -999,23 +907,13 @@ error code. ### Step 3: Handle broadcast intents -In addition to making publish content API calls through a job, it is also -required to set up a -[`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive -the request for a content publish. +In addition to making publish content API calls through a job, it is also required to set up a [`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive the request for a content publish. -The goal of broadcast intents is mainly for app reactivation and forcing data -sync. Broadcast intents are not designed to be sent very frequently. It is only -triggered when the Engage Service determines the content might be stale (for -example, a week old). That way, there is more confidence that the user can have -a fresh content experience, even if the application has not been executed for a -long period of time. +The goal of broadcast intents is mainly for app reactivation and forcing data sync. Broadcast intents are not designed to be sent very frequently. It is only triggered when the Engage Service determines the content might be stale (for example, a week old). That way, there is more confidence that the user can have a fresh content experience, even if the application has not been executed for a long period of time. The `BroadcastReceiver` must be set up in the following two ways: -- Dynamically register an instance of the `BroadcastReceiver` class using - `Context.registerReceiver()`. This enables communication from applications - that are still live in memory. +- Dynamically register an instance of the `BroadcastReceiver` class using `Context.registerReceiver()`. This enables communication from applications that are still live in memory. ### Kotlin @@ -1138,10 +1036,7 @@ The `BroadcastReceiver` must be set up in the following two ways: } -- Statically declare an implementation with the `` tag in your - `AndroidManifest.xml` file. This allows the application to receive broadcast - intents when it is not running, and also allows the application to publish - the content. +- Statically declare an implementation with the `` tag in your `AndroidManifest.xml` file. This allows the application to receive broadcast intents when it is not running, and also allows the application to publish the content. -The following [intents](https://developer.android.com/reference/android/content/Intent) are sent by the -service: +The following [intents](https://developer.android.com/reference/android/content/Intent) are sent by the service: - `com.google.android.engage.action.PUBLISH_RECOMMENDATION` It is recommended to start a `publishRecommendationClusters` call when this intent is received. - `com.google.android.engage.action.PUBLISH_FEATURED` It is recommended to start a `publishFeaturedCluster` call when this intent is received. @@ -1182,20 +1076,15 @@ service: ## Integration workflow -For a step-by-step guide on verifying your integration after it is complete, see -[Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). +For a step-by-step guide on verifying your integration after it is complete, see [Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). ## FAQs -See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for -FAQs. +See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for FAQs. ## Contact -Contact -[`engage-developers@google.com`](mailto:engage-developers@google.com) if there are -any questions during the integration process. Our team replies as soon as -possible. +Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during the integration process. Our team replies as soon as possible. ## Next steps diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/social.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/social.md new file mode 100644 index 0000000..32e630b --- /dev/null +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/social.md @@ -0,0 +1,649 @@ +Boost app engagement by reaching your users where they are. Integrate Engage SDK to deliver personalized recommendations and continuation content directly to users across multiple on-device surfaces, like **[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds less than 50 KB (compressed) to the average APK and takes most apps about a week of developer time. Learn more at our **[business site](http://play.google.com/console/about/programs/EngageSDK)**. + +This guide contains instructions for developer partners to deliver social media content to Engage content surfaces. + +## Integration detail + +The following section captures the integration detail. + +### Terminology + +***Recommendation*** clusters show personalized suggestions from an individual developer partner. + +Your recommendations take the following structure: + +**Recommendation Cluster**: UI view that contains a group of recommendations from the same developer partner. + +Each Recommendation Cluster consists of one of the following two types of entities : + +- PortraitMediaEntity +- SocialPostEntity + +**PortraitMediaEntity** must contain 1 portrait image for the post. Profile and Interaction related metadata are optional. + +- Post + + - Image in portrait mode and Timestamp, or + - Image in portrait mode + text content and Timestamp +- Profile + + - Avatar, Name or Handle, Additional image +- Interactions + + - Count and label only, or + - Count and visual (icon) + +**SocialPostEntity** contains profile, post and interaction related metadata. + +- Profile + + - Avatar, Name or Handle, additional text, additional image +- Post + + - Text and Timestamp, or + - Rich media (image or rich URL) and Timestamp, or + - Text and rich media (image or rich URL) and Timestamp, or + - Video preview (thumbnail and duration) and Timestamp +- Interactions + + - Count \& label only, or + - Count \& visual (icon) + +### Pre-work + +Minimum API level: 19 + +Add the `com.google.android.engage:engage-core` library to your app: + + dependencies { + // Make sure you also include that repository in your project's build.gradle file. + implementation 'com.google.android.engage:engage-core:1.6.0' + } + +### Summary + +The design is based on an implementation of a [bound service](https://developer.android.com/guide/components/bound-services). + +The data a client can publish is subject to the following limits for different cluster types: + +| Cluster type | Cluster limits | Minimum entity limits in a cluster | Maximum entity limits in a cluster | +|---|---|---|---| +| Recommendation Cluster(s) | At most 7 | At least 1 (`PortraitMediaEntity`, or `SocialPostEntity`) | At most 50 (`PortraitMediaEntity`, or `SocialPostEntity`) | + +### Step 1: Provide entity data + +The SDK has defined different entities to represent each item type. The SDK supports the following entities for the Social category: + +1. `PortraitMediaEntity` +2. `SocialPostEntity` + +The charts below outline available attributes and requirements for each type. + +#### `PortraitMediaEntity` + +| Attribute | Requirement | Description | Format | +|---|---|---|---| +| Action URI | **Required** for all surfaces other than Google TV | Deep Link to the entity in the provider app. Note: You can use deep links for attribution. [Refer to this FAQ](https://developer.android.com/guide/playcore/engage/faq#deeplinks-attribution) | URI | +| PlatformSpecificPlayback | **Required** for Google TV surface | Deep Link to the entity in the provider app for platforms like Google TV and Mobile. | List of PlatformSpecificPlayback objects | +| Recommendation Reason | Optional | The justification for recommending the content to the user. | RecommendationReason object | +| Comments Summary | Optional | Summary of comments for the post. | String | +| **Post related metadata (Required)** |||| +| Image(s) | Required | Image(s) should be in **portrait aspect ratio.** The UI may show only 1 image when multiple images are provided. However, the UI may provide visual indication that there are more images in the app. *If the post is a video, the provider should provide a thumbnail of the video to be shown as an image.* | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| Text content | Optional | The main text of a post, update, etc. | String (recommended max 140 chars) | +| Timestamp | Optional | Time when the post was published. | Epoch timestamp in milliseconds | +| Is video content | Optional | Is the post a video? | boolean | +| Video duration | Optional | The duration of the video in milliseconds. | Long | +| **Profile related metadata (Optional)** |||| +| Name | Required | Profile name or id or handle, eg "John Doe", "@TeamPixel" | String(recommended max 25 chars) | +| Avatar | Required | Profile picture or avatar image of the user. **Square 1:1 image** | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| Additional Image | Optional | Profile badge. for example - verified badge **Square 1:1 image** | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| **Interactions related metadata (Optional)** |||| +| Count | Optional | Indicate the number of interactions, for example - "3.7 M.". **Note:** If both Count and Count Value are provided, Count will be used. **Note:** Partners should use either **Count** or **CountWithOptionalLabel**. | String | +| CountWithOptionalLabel | Optional | Indicate the number of interactions with an optional label, for example - "3.7 M Likes.". **Note:** If both CountWithOptionalLabel and Count Value are provided, one of them will be used. **Note:** Partners should use either **Count** or **CountWithOptionalLabel**. | String | +| Count Value | Optional | The number of interactions as a value. **Note:** Provide Count Value instead of Count if your app doesn't handle logic on how a large number should be optimized for different display sizes. If both Count and Count Value are provided, Count is used. | Long | +| Label | Optional | Indicate what the interaction label is for. For example - "Likes". | String | +| Visual | Optional | Indicate what the interaction is for. For example - Image showing Likes icon, emoji. Can provide more than 1 image, though not all may not be shown on all form factors. **Note:** Must be Square 1:1 image | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| **DisplayTimeWindow (Optional) - Set a time window for a content to be shown on the surface** |||| +| Start Timestamp | Optional | The epoch timestamp after which the content should be shown on the surface. If not set, content is eligible to be shown on the surface. | Epoch timestamp in milliseconds | +| End Timestamp | Optional | The epoch timestamp after which the content is no longer shown on the surface. If not set, content is eligible to be shown on the surface. | Epoch timestamp in milliseconds | + +#### `SocialPostEntity` + +| Attribute | Requirement | Description | Format | +|---|---|---|---| +| Action URI | **Required** | Deep Link to the entity in the provider app. Note: You can use deep links for attribution. [Refer to this FAQ](https://developer.android.com/guide/playcore/engage/faq#deeplinks-attribution) | URI | +| PlatformSpecificPlayback URIs | **Required** for Google TV surface | Deep Link to the entity in the provider app for platforms like Google TV and Mobile. | List of PlatformSpecificPlayback objects | +| Recommendation Reason | Optional | The justification for recommending the content to the user. | RecommendationReason object | +| Comments Summary | Optional | Summary of comments for the post. | String | +| **Post related metadata (Required)** At least one of TextContent, Image or WebContent is required |||| +| Image(s) | Optional | Image(s) should be in **portrait aspect ratio.** The UI may show only 1 image when multiple images are provided. However, the UI may provide visual indication that there are more images in the app. *If the post is a video, the provider should provide a thumbnail of the video to be shown as an image.* | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| Text content | Optional | The main text of a post, update, etc. | String (recommended max 140 chars) | +| **Video Content (Optional)** |||| +| Duration | Required | The duration of the video in milliseconds. | Long | +| Image | Required | Preview image of the video content. | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| **Link Preview (Optional)** |||| +| Link Preview - Title | Required | Text to indicate the title of the web page content | String | +| Link Preview - Hostname | Required | Text to indicate the web page owner, eg "INSIDER" | String | +| Link Preview - Image | Optional | Hero image for the web content | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| Timestamp | Optional | Time when the post was published. | Epoch timestamp in milliseconds | +| **Profile related metadata (Optional)** |||| +| Name | Required | Profile name or id or handle, eg "John Doe", "@TeamPixel." | String(recommended max 25 chars) | +| Additional Text | Optional | Could be used as profile id or handle or additional metadata For example "@John-Doe", "5M followers", "You might like", "Trending", "5 new posts" | String(recommended max 40 chars) | +| Avatar | Required | Profile picture or avatar image of the user. **Square 1:1 image** | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| Additional Image | Optional | Profile badge, for example - verified badge **Square 1:1 image** | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| **Interactions related metadata (Optional)** |||| +| Count | Required | Indicate the number of interactions, for example - "3.7 M." **Note:** Partners should use either **Count** or **CountWithOptionalLabel**. | String | +| CountWithOptionalLabel | Required | Indicate the number of interactions with an optional label, for example - "3.7 M Likes." **Note:** Partners should use either **Count** or **CountWithOptionalLabel**. | String | +| Label | Optional If not provided, **Visual** must be provided. | Indicate what the interaction is for. For example - "Likes." | String (recommended max 20 chars for count + label combined) | +| Visual | Optional If not provided, **Label** must be provided. | Indicate what the interaction is for. For example - Image showing Likes icon, emoji. Can provide more than 1 image, though not all may not be shown on all form factors. **Square 1:1 image** | See [Image Specifications](https://developer.android.com/guide/playcore/engage/social#image-specs) for guidance. | +| **DisplayTimeWindow (Optional) - Set a time window for a content to be shown on the surface** |||| +| Start Timestamp | Optional | The epoch timestamp after which the content should be shown on the surface. If not set, content is eligible to be shown on the surface. | Epoch timestamp in milliseconds | +| End Timestamp | Optional | The epoch timestamp after which the content is no longer shown on the surface. If not set, content is eligible to be shown on the surface. | Epoch timestamp in milliseconds | + +#### Image specifications + +The images are required to be hosted on public CDNs so that Google can access them. + +*File formats* + +PNG, JPG, static GIF, WebP + +*Maximum file size* + +5120 KB + +*Additional recommendations* + +- **Image safe area:** Put your important content in the center 80% of the image. +- Use a transparent background so that the image can be properly displayed in Dark and Light theme settings. + +### Step 2: Provide Cluster data + +It is recommended to have the content publish job executed in the background (for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) and scheduled on a regular basis or on an event basis (for example, every time the user opens the app or when the user just followed a new account) + +`AppEngageSocialClient` is responsible for publishing social clusters. + +There are following APIs to publish clusters in the client: + +- `isServiceAvailable` +- `publishRecommendationClusters` +- `publishUserAccountManagementRequest` +- `updatePublishStatus` +- `deleteRecommendationsClusters` +- `deleteUserManagementCluster` +- `deleteClusters` + +#### `isServiceAvailable` + +This API is used to check if the service is available for integration and whether the content can be presented on the device. + +##### For Engage SDK v1.6.0 and higher (Recommended) + +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/play/engage-sdk-integration) + +### Engage SDK integration + +To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill engage-sdk-integration + +If your team uses AI coding tools (such as Gemini in Android Studio), you can automate this migration by prompting your AI assistant: + + Use the engage-sdk-integration skill to use Engage SDK 1.6.0 and refactor isServiceAvailable to pass ServiceAvailabilityRequest for publishing all cluster types. + +
+ +You can check the service availability for every cluster type that you intend to publish. The `isServiceAvailable` API accepts a request object, `ServiceAvailabilityRequest`, which contains the cluster types for which service availability needs to be checked. You can find the `ClusterType` enum values required for `ServiceAvailabilityRequest` from the following table. + +| Cluster Type | Cluster Type Constant | Integer Value | +|---|---|---| +| Unknown | `TYPE_UNKNOWN` | 0 | +| Recommendation Cluster | `TYPE_RECOMMENDATION` | 1 | +| Featured Cluster | `TYPE_FEATURED` | 2 | +| Continuation Cluster | `TYPE_CONTINUATION` | 3 | +| User Management Cluster | `TYPE_ENGAGEMENT` | 8 | +| Subscription Cluster | `TYPE_SUBSCRIPTION` | 12 | + +### Kotlin + + val request = ServiceAvailabilityRequest.Builder() + .addIntendedClusterType(ClusterType.TYPE_CONTINUATION) + .addIntendedClusterType(ClusterType.TYPE_RECOMMENDATION) + .build() + + client.isServiceAvailable(request).addOnCompleteListener { task -> + if (task.isSuccessful) { + val availabilityMap = task.result + if (availabilityMap[ClusterType.TYPE_CONTINUATION] == true) { + // Proceed with publishing continuation content + } + if (availabilityMap[ClusterType.TYPE_RECOMMENDATION] == true) { + // Proceed with publishing recommendation content + } + } else { + // The IPC call itself fails, proceed with error handling logic here, + // such as retry. + } + } + +### Java + + ServiceAvailabilityRequest request = + new ServiceAvailabilityRequest.Builder() + .addIntendedClusterType(ClusterType.TYPE_CONTINUATION) + .addIntendedClusterType(ClusterType.TYPE_RECOMMENDATION) + .build(); + + client.isServiceAvailable(request).addOnCompleteListener(task -> { + if (task.isSuccessful()) { + Map availabilityMap = task.getResult(); + if (Boolean.TRUE.equals(availabilityMap.get(ClusterType.TYPE_CONTINUATION))) { + // Proceed with publishing continuation content + } + if (Boolean.TRUE.equals(availabilityMap.get(ClusterType.TYPE_RECOMMENDATION))) { + // Proceed with publishing recommendation content + } + } else { + // The IPC call itself fails, proceed with error handling logic here, + // such as retry. + } + }); + +###### Conditional Service Availability Feature + +Some integrated apps request a special configuration that enables and disables the Engage service intermittently in order to reduce their serving cost. This intermittent content ingestion strategy, although possible, negatively affects the user and the product -- stale content will not be presented and some surfaces will not be served at all. + +Starting with v1.6.0, the Engage SDK allows checking availability for specific cluster types. If you are interested in opting into this feature for any cluster type, please contact engage-developers@google.com. + +##### For SDK versions prior to v1.6.0 (Deprecated) + +### Kotlin + + client.isServiceAvailable.addOnCompleteListener { task -> + if (task.isSuccessful) { + // Handle IPC call success + if(task.result) { + // Service is available on the device, proceed with content publish + // calls. + } else { + // Service is not available, no further action is needed. + } + } else { + // The IPC call itself fails, proceed with error handling logic here, + // such as retry. + } + } + +### Java + + client.isServiceAvailable().addOnCompleteListener(task - > { + if (task.isSuccessful()) { + // Handle success + if(task.getResult()) { + // Service is available on the device, proceed with content publish + // calls. + } else { + // Service is not available, no further action is needed. + } + } else { + // The IPC call itself fails, proceed with error handling logic here, + // such as retry. + } + }); + +> [!NOTE] +> **Note:** We highly recommend keeping a periodic job running to check if the service becomes available at a later point in time. The availability of the service may change with Android version upgrades, app upgrades, installs, and uninstalls. By ensuring periodic job checks at a certain time interval, data can be published once the service becomes available. + +#### `publishRecommendationClusters` + +This API is used to publish a list `RecommendationCluster` objects. + +A `RecommendationCluster` object can have the following attributes: + +| Attribute | Requirement | Description | +|---|---|---| +| List of SocialPostEntity, or PortraitMediaEntity | **Required** | A list of entities that make up the recommendations for this Recommendation Cluster. Entities in a single cluster must be of the same type. | +| Title | **Required** | The title for the Recommendation Cluster (for example, *Latest from your friends*). **Recommended text size: under 25 chars** (Text that is too long may show ellipses) | +| Subtitle | Optional | The subtitle for the Recommendation Cluster. | +| Action Uri | Optional | The deep link to the page in the partner app where users can see the complete list of recommendations. Note: You can use deep links for attribution. [Refer to this FAQ](https://developer.android.com/guide/playcore/engage/faq#deeplinks-attribution) | + +> [!IMPORTANT] +> **Important:** The publish APIs are upsert APIs; it replaces the existing content. **Don't** call delete and publish APIs subsequently to replace the content as the publish APIs do that inherently. + +> [!IMPORTANT] +> **Important:** For social apps, it's critical to update recommendations after each app usage. Social app users are more interested in the most recent recommendations and ideally would like to see a post at most once. + +### Kotlin + + client.publishRecommendationClusters( + PublishRecommendationClustersRequest.Builder() + .addRecommendationCluster( + RecommendationCluster.Builder() + .addEntity(entity1) + .addEntity(entity2) + .setTitle("Latest from your friends") + .build()) + .build()) + +### Java + + client.publishRecommendationClusters( + new PublishRecommendationClustersRequest.Builder() + .addRecommendationCluster( + new RecommendationCluster.Builder() + .addEntity(entity1) + .addEntity(entity2) + .setTitle("Latest from your friends") + .build()) + .build()); + +When the service receives the request, the following actions take place within one transaction: + +- All existing Recommendation Cluster data is removed. +- Data from the request is parsed and stored in new Recommendation Clusters. + +In case of an error, the entire request is rejected and the existing state is maintained. + +#### `publishUserAccountManagementRequest` + +This API is used to publish a Sign In card . The signin action directs users to the app's sign in page so that the app can publish content (or provide more personalized content) + +The following metadata is part of the Sign In Card - + +| Attribute | Requirement | Description | +|---|---|---| +| Action Uri | Required | Deeplink to Action (i.e. navigates to app sign in page) | +| Image | Optional - If not provided, Title must be provided | Image Shown on the Card 16x9 aspect ratio images with a resolution of 1264x712 | +| Title | Optional - If not provided, Image must be provided | Title on the Card | +| Action Text | Optional | Text Shown on the CTA (i.e. Sign in) | +| Subtitle | Optional | Optional Subtitle on the Card | + +> [!IMPORTANT] +> **Important:** The publish APIs are upsert APIs; it replaces the existing content. **Don't** call delete and publish APIs subsequently to replace the content as the publish APIs do that inherently. + +### Kotlin + + var SIGN_IN_CARD_ENTITY = + SignInCardEntity.Builder() + .addPosterImage( + Image.Builder() + .setImageUri(Uri.parse("http://www.x.com/image.png")) + .setImageHeightInPixel(500) + .setImageWidthInPixel(500) + .build()) + .setActionText("Sign In") + .setActionUri(Uri.parse("http://xx.com/signin")) + .build() + + client.publishUserAccountManagementRequest( + PublishUserAccountManagementRequest.Builder() + .setSignInCardEntity(SIGN_IN_CARD_ENTITY) + .build()); + +### Java + + SignInCardEntity SIGN_IN_CARD_ENTITY = + new SignInCardEntity.Builder() + .addPosterImage( + new Image.Builder() + .setImageUri(Uri.parse("http://www.x.com/image.png")) + .setImageHeightInPixel(500) + .setImageWidthInPixel(500) + .build()) + .setActionText("Sign In") + .setActionUri(Uri.parse("http://xx.com/signin")) + .build(); + + client.publishUserAccountManagementRequest( + new PublishUserAccountManagementRequest.Builder() + .setSignInCardEntity(SIGN_IN_CARD_ENTITY) + .build()); + +When the service receives the request, the following actions take place within one transaction: + +- Existing `UserAccountManagementCluster` data from the developer partner is removed. +- Data from the request is parsed and stored in the updated UserAccountManagementCluster Cluster. + +In case of an error, the entire request is rejected and the existing state is maintained. + +#### `updatePublishStatus` + +If for any internal business reason, none of the clusters is published, we **strongly recommend** updating the publish status using the **updatePublishStatus** API. This is important because : + +- Providing the status in all scenarios, even when the content is published (STATUS == PUBLISHED), is critical to populate dashboards that use this explicit status to convey the health and other metrics of your integration. +- If no content is published but the integration status isn't broken (STATUS == NOT_PUBLISHED), Google can avoid triggering alerts in the app health dashboards. It confirms that content is not published due to an **expected** situation from the provider's standpoint. +- It helps developers provide insights into when the data is published versus not. +- Google may use the status codes to nudge the user to do certain actions in the app so they can see the app content or overcome it. + +The list of eligible publish status codes are : + + // Content is published + AppEngagePublishStatusCode.PUBLISHED, + + // Content is not published as user is not signed in + AppEngagePublishStatusCode.NOT_PUBLISHED_REQUIRES_SIGN_IN, + + // Content is not published as user is not subscribed + AppEngagePublishStatusCode.NOT_PUBLISHED_REQUIRES_SUBSCRIPTION, + + // Content is not published as user location is ineligible + AppEngagePublishStatusCode.NOT_PUBLISHED_INELIGIBLE_LOCATION, + + // Content is not published as there is no eligible content + AppEngagePublishStatusCode.NOT_PUBLISHED_NO_ELIGIBLE_CONTENT, + + // Content is not published as the feature is disabled by the client + // Available in v1.3.1 + AppEngagePublishStatusCode.NOT_PUBLISHED_FEATURE_DISABLED_BY_CLIENT, + + // Content is not published as the feature due to a client error + // Available in v1.3.1 + AppEngagePublishStatusCode.NOT_PUBLISHED_CLIENT_ERROR, + + // Content is not published as the feature due to a service error + // Available in v1.3.1 + AppEngagePublishStatusCode.NOT_PUBLISHED_SERVICE_ERROR, + + // Content is not published due to some other reason + // Reach out to engage-developers@ before using this enum. + AppEngagePublishStatusCode.NOT_PUBLISHED_OTHER + +If the content is not published due to a user not logged in, Google would recommend publishing the Sign In Card. If for any reason providers are not able to publish the Sign In Card then we recommend calling the **updatePublishStatus** API with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** + +### Kotlin + + client.updatePublishStatus( + PublishStatusRequest.Builder() + .setStatusCode(AppEngagePublishStatusCode.NOT_PUBLISHED_REQUIRES_SIGN_IN) + .build()) + +### Java + + client.updatePublishStatus( + new PublishStatusRequest.Builder() + .setStatusCode(AppEngagePublishStatusCode.NOT_PUBLISHED_REQUIRES_SIGN_IN) + .build()); + +#### `deleteRecommendationClusters` + +This API is used to delete the content of Recommendation Clusters. + +> [!IMPORTANT] +> **Important:** Delete APIs should only be called when there is no content to publish. **Don't** call delete and publish APIs subsequently to replace the content as the publish APIs do that inherently. Reach out to [`engage-developers@google.com`](mailto:engage-developers@google.com) before using delete APIs. + +### Kotlin + + client.deleteRecommendationClusters() + +### Java + + client.deleteRecommendationClusters(); + +When the service receives the request, it removes the existing data from the Recommendation Clusters. In case of an error, the entire request is rejected and the existing state is maintained. + +#### `deleteUserManagementCluster` + +This API is used to delete the content of UserAccountManagement Cluster. + +> [!IMPORTANT] +> **Important:** Delete APIs should only be called when there is no content to publish. **Don't** call delete and publish APIs subsequently to replace the content as the publish APIs do that inherently. Reach out to [`engage-developers@google.com`](mailto:engage-developers@google.com) before using delete APIs. + +### Kotlin + + client.deleteUserManagementCluster() + +### Java + + client.deleteUserManagementCluster(); + +When the service receives the request, it removes the existing data from the UserAccountManagement Cluster. In case of an error, the entire request is rejected and the existing state is maintained. + +#### `deleteClusters` + +This API is used to delete the content of a given cluster type. + +> [!IMPORTANT] +> **Important:** Delete APIs should only be called when there is no content to publish. **Don't** call delete and publish APIs subsequently to replace the content as the publish APIs do that inherently. Reach out to [`engage-developers@google.com`](mailto:engage-developers@google.com) before using delete APIs. + +### Kotlin + + client.deleteClusters( + DeleteClustersRequest.Builder() + .addClusterType(ClusterType.TYPE_RECOMMENDATION) + ... + .build()) + +### Java + + client.deleteClusters( + new DeleteClustersRequest.Builder() + .addClusterType(ClusterType.TYPE_RECOMMENDATION) + ... + .build()); + +When the service receives the request, it removes the existing data from all clusters matching the specified cluster types. Clients can choose to pass one or many cluster types. In case of an error, the entire request is rejected and the existing state is maintained. + +#### Error handling + +It is highly recommended to listen to the task result from the publish APIs such that a follow-up action can be taken to recover and resubmit an successful task. + + client.publishRecommendationClusters( + new PublishRecommendationClustersRequest.Builder() + .addRecommendationCluster(...) + .build()) + .addOnCompleteListener( + task -> { + if (task.isSuccessful()) { + // do something + } else { + Exception exception = task.getException(); + if (exception instanceof AppEngageException) { + @AppEngageErrorCode + int errorCode = ((AppEngageException) exception).getErrorCode(); + if (errorCode == AppEngageErrorCode.SERVICE_NOT_FOUND) { + // do something + } + } + } + }); + +The error is returned as an `AppEngageException` with the cause included as an error code. + +| Error code | Error name | Note | +|---|---|---| +| `1` | `SERVICE_NOT_FOUND` | The service is not available on the given device. | +| `2` | `SERVICE_NOT_AVAILABLE` | The service is available on the given device, but it is not available at the time of the call (for example, it is explicitly disabled). | +| `3` | `SERVICE_CALL_EXECUTION_FAILURE` | The task execution failed due to threading issues. In this case, it can be retried. | +| `4` | `SERVICE_CALL_PERMISSION_DENIED` | The caller is not allowed to make the service call. | +| `5` | `SERVICE_CALL_INVALID_ARGUMENT` | The request contains invalid data (for example, more than the allowed number of clusters). | +| `6` | `SERVICE_CALL_INTERNAL` | There is an error on the service side. | +| `7` | `SERVICE_CALL_RESOURCE_EXHAUSTED` | The service call is made too frequently. | + +### Step 3: Handle broadcast intents + +In addition to making publish content API calls through a job, it is also required to set up a [`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive the request for a content publish. + +The goal of broadcast intents is mainly for app reactivation and forcing data sync. Broadcast intents are not designed to be sent very frequently. It is only triggered when the Engage Service determines the content might be stale (for example, a week old). That way, there is more confidence that the user can have a fresh content experience, even if the application has not been executed for a long period of time. + +The `BroadcastReceiver` must be set up in the following two ways: + +- Dynamically register an instance of the `BroadcastReceiver` class using `Context.registerReceiver()`. This enables communication from applications that are still live in memory. + +### Kotlin + + class AppEngageBroadcastReceiver : BroadcastReceiver(){ + // Trigger recommendation cluster publish when PUBLISH_RECOMMENDATION + // broadcast is received + } + + fun registerBroadcastReceivers(context: Context){ + var context = context + context = context.applicationContext + + // Register Recommendation Cluster Publish Intent + context.registerReceiver(AppEngageBroadcastReceiver(), + IntentFilter(Intents.ACTION_PUBLISH_RECOMMENDATION), + com.google.android.engage.service.BroadcastReceiverPermissions.BROADCAST_REQUEST_DATA_PUBLISH_PERMISSION, + /*scheduler=*/null) + } + +### Java + + class AppEngageBroadcastReceiver extends BroadcastReceiver { + // Trigger recommendation cluster publish when PUBLISH_RECOMMENDATION broadcast + // is received + } + + public static void registerBroadcastReceivers(Context context) { + + context = context.getApplicationContext(); + + // Register Recommendation Cluster Publish Intent + context.registerReceiver(new AppEngageBroadcastReceiver(), + new IntentFilter(com.google.android.engage.service.Intents.ACTION_PUBLISH_RECOMMENDATION), + com.google.android.engage.service.BroadcastReceiverPermissions.BROADCAST_REQUEST_DATA_PUBLISH_PERMISSION, + /*scheduler=*/null); + } + +- Statically declare an implementation with the `` tag in your `AndroidManifest.xml` file. This allows the application to receive broadcast intents when it is not running, and also allows the application to publish the content. + + + + + + + + + +The following [intents](https://developer.android.com/reference/android/content/Intent) will be sent by the service: + +- `com.google.android.engage.action.PUBLISH_RECOMMENDATION` It is recommended to start a `publishRecommendationClusters` call when receiving this intent. + +## Integration workflow + +For a step-by-step guide on verifying your integration after it is complete, see [Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). + +## FAQs + +See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for FAQs. + +## Contact + +Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during the integration process. Our team will reply as soon as possible. + +## Next steps + +After completing this integration, your next steps are as follows: + +- Send an email to [`engage-developers@google.com`](mailto:engage-developers@google.com) and attach your integrated APK that is ready for testing by Google. +- Google performs a verification and reviews internally to make sure the integration works as expected. If changes are needed, Google contacts you with any necessary details. +- When testing is complete and no changes are needed, Google contacts you to notify you that you can start publishing the updated and integrated APK to the Play Store. +- After Google has confirmed that your updated APK has been published to the Play Store, your **Recommendation**, clusters will be published and visible to users. \ No newline at end of file diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/travel.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/travel.md index d9a3507..aab021e 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/travel.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/travel.md @@ -1,82 +1,44 @@ -Boost app engagement by reaching your users where they are. Integrate Engage SDK -to deliver personalized recommendations and continuation content directly to -users across multiple on-device surfaces, like -**[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment -Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds -less than 50 KB (compressed) to the average APK and takes most apps about a -week of developer time. Learn more at our **[business -site](http://play.google.com/console/about/programs/EngageSDK)**. +Boost app engagement by reaching your users where they are. Integrate Engage SDK to deliver personalized recommendations and continuation content directly to users across multiple on-device surfaces, like **[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds less than 50 KB (compressed) to the average APK and takes most apps about a week of developer time. Learn more at our **[business site](http://play.google.com/console/about/programs/EngageSDK)**. -This guide contains instructions for developer partners to deliver travel and -events content to Engage content surfaces. +This guide contains instructions for developer partners to deliver travel and events content to Engage content surfaces. ## Integration detail ### Terminology -This integration includes the following cluster types: **Recommendation** , -**Featured** , **Reservation** and **Continue Search**. +This integration includes the following cluster types: **Recommendation** , **Featured** , **Reservation** and **Continue Search**. -- **Recommendation** clusters show personalized travel \& event suggestions - from an individual developer partner. These recommendations can be - personalized to the user or generalized (for example, trending items). Use - these to surface articles, events, lodging, or places of interest - recommendations. +- **Recommendation** clusters show personalized travel \& event suggestions from an individual developer partner. These recommendations can be personalized to the user or generalized (for example, trending items). Use these to surface articles, events, lodging, or places of interest recommendations. - A Recommendation cluster can be made of `ArticleEntity`, `EventEntity`, `LodgingEntity`, `PointOfInterestEntity`, or `StoreEntity` listings, but not a mix of different entity types. Your recommendations take the following structure: - - **Recommendation Cluster:** A UI view that contains a group of - recommendations from the same developer partner. + - **Recommendation Cluster:** A UI view that contains a group of recommendations from the same developer partner. - - **Entity:** An object representing a single item in a cluster. This - integration offers some entities that would be surfaced using the - Recommendation Cluster: + - **Entity:** An object representing a single item in a cluster. This integration offers some entities that would be surfaced using the Recommendation Cluster: - - **ArticleEntity**: ArticleEntity represents a recommendation for - text-based content related to travel \& events. It can be used for - articles, blogposts, marketing content, news snippets, etc. + - **ArticleEntity**: ArticleEntity represents a recommendation for text-based content related to travel \& events. It can be used for articles, blogposts, marketing content, news snippets, etc. ![](https://developer.android.com/static/images/guide/playcore/engage/article-entity-travel.png) **Figure 1:** UI showing a single ArticleEntity within Recommendations cluster. - - **EventEntity**: EventEntity represents an event happening in the - future. Event start time is a critical piece of information that - needs to be conveyed to the users. + - **EventEntity**: EventEntity represents an event happening in the future. Event start time is a critical piece of information that needs to be conveyed to the users. ![](https://developer.android.com/static/images/guide/playcore/engage/event-entity-travel.png) **Figure 2:** UI showing a single EventEntity within Recommendations cluster. - - **LodgingEntity**: LodgingEntity represents an accommodation, such - as a hotel, apartment, vacation home for short term and long term - rental. + - **LodgingEntity**: LodgingEntity represents an accommodation, such as a hotel, apartment, vacation home for short term and long term rental. ![](https://developer.android.com/static/images/guide/playcore/engage/lodging-entity-travel.png) **Figure 3:** UI showing a single LodgingEntity within Recommendations cluster. - - **StoreEntity**: StoreEntity represents a store, restaurant, cafe - etc. It highlights content where a dining venue or store is the - critical piece of information that needs to be conveyed to the - users. + - **StoreEntity**: StoreEntity represents a store, restaurant, cafe etc. It highlights content where a dining venue or store is the critical piece of information that needs to be conveyed to the users. ![](https://developer.android.com/static/images/guide/playcore/engage/store-entity-travel.png) **Figure 4:** UI showing a single StoreEntity within Recommendations cluster. - - **PointOfInterestEntity**: PointOfInterestEntity represents a - place of interest like, a gas station, event venue, theme park, - museum, tourist attraction, hiking trail etc. It highlights content - where location is a critical piece of information that needs to be - conveyed to the users. It shouldn't be used for lodging, a store or - a dining venue. + - **PointOfInterestEntity**: PointOfInterestEntity represents a place of interest like, a gas station, event venue, theme park, museum, tourist attraction, hiking trail etc. It highlights content where location is a critical piece of information that needs to be conveyed to the users. It shouldn't be used for lodging, a store or a dining venue. ![](https://developer.android.com/static/images/guide/playcore/engage/poi-entity-travel.png) **Figure 5:** UI showing a single PointOfInterestEntity within Recommendations cluster. -- The **Reservation** cluster shows content recently engaged by users from - multiple developer partners in a single UI grouping. Each developer partner - will be allowed to broadcast a maximum of 10 entities in the Reservation - cluster. +- The **Reservation** cluster shows content recently engaged by users from multiple developer partners in a single UI grouping. Each developer partner will be allowed to broadcast a maximum of 10 entities in the Reservation cluster. Your reservation content can take the following structure: - - **RestaurantReservationEntity**: RestaurantReservationEntity represents - a reservation for a restaurant or cafe and helps users track upcoming or - ongoing restaurant reservations. + - **RestaurantReservationEntity**: RestaurantReservationEntity represents a reservation for a restaurant or cafe and helps users track upcoming or ongoing restaurant reservations. ![](https://developer.android.com/static/images/guide/playcore/engage/restaurant-reservation-entity-travel.png) **Figure 6.** UI showing a single RestaurantReservationEntity within a Reservation cluster. - - **EventReservationEntity**: EventReservationEntity represents a - reservation for an event and helps users track upcoming or ongoing - events reservations. Events could include, but not limited to the - following: + - **EventReservationEntity**: EventReservationEntity represents a reservation for an event and helps users track upcoming or ongoing events reservations. Events could include, but not limited to the following: - Sports events like reservation for a football match - Gaming events like reservation for eSports @@ -86,40 +48,21 @@ This integration includes the following cluster types: **Recommendation** , - Education / Training sessions reservations ![](https://developer.android.com/static/images/guide/playcore/engage/event-reservation-entity-travel.png) **Figure 7.** UI showing a single EventReservationEntity within a Reservation cluster. - - **LodgingReservationEntity**: LodgingEntityReservation represents a - reservation for travel lodging and helps users track upcoming or - ongoing hotel or vacation rental reservations. + - **LodgingReservationEntity**: LodgingEntityReservation represents a reservation for travel lodging and helps users track upcoming or ongoing hotel or vacation rental reservations. ![](https://developer.android.com/static/images/guide/playcore/engage/lodging-reservation-entity-travel.png) **Figure 8.** UI showing a single LodgingReservationEntity within a Reservation cluster. - - **TransportationReservationEntity**: TransportationReservationEntity - represents reservation for transportation by any mode and helps users - track reservations for upcoming or ongoing flight, ferry, train, bus, - ride-hailing, or cruise. + - **TransportationReservationEntity**: TransportationReservationEntity represents reservation for transportation by any mode and helps users track reservations for upcoming or ongoing flight, ferry, train, bus, ride-hailing, or cruise. ![](https://developer.android.com/static/images/guide/playcore/engage/transportation-reservation-entity-travel.png) **Figure 9.** UI showing a single TransportationReservationEntity within a Reservation cluster. - - **VehicleRentalReservationEntity**: VehicleRentalReservationEntity - represents vehicle rental reservation and helps users track upcoming - or ongoing vehicle rental reservations. + - **VehicleRentalReservationEntity**: VehicleRentalReservationEntity represents vehicle rental reservation and helps users track upcoming or ongoing vehicle rental reservations. ![](https://developer.android.com/static/images/guide/playcore/engage/vehicle-rental-reservation-entity-travel.png) **Figure 10.** UI showing a single VehicleRentalReservationEntity within a Reservation cluster. -- The **Featured** cluster showcases a selection of entities from multiple - developer partners in one UI grouping. There will be a single Featured - cluster, which is surfaced near the top of the UI with a priority placement - above all Recommendation clusters. Each developer partner will be allowed to - broadcast up to 10 entities in the Featured cluster. +- The **Featured** cluster showcases a selection of entities from multiple developer partners in one UI grouping. There will be a single Featured cluster, which is surfaced near the top of the UI with a priority placement above all Recommendation clusters. Each developer partner will be allowed to broadcast up to 10 entities in the Featured cluster. - - **GenericFeaturedEntity**: GenericFeaturedEntity differs from - Recommendation item in that Featured item should be used for a single - top content from developers and should represent the single most - important content that will be interesting and relevant to users. + - **GenericFeaturedEntity**: GenericFeaturedEntity differs from Recommendation item in that Featured item should be used for a single top content from developers and should represent the single most important content that will be interesting and relevant to users. ![](https://developer.android.com/static/images/guide/playcore/engage/featured-cluster-travel.png) **Figure 11:** UI showing a FeaturedCluster with a list of GenericFeaturedEntity -- The **Continue Search** cluster helps users resume their previous travel - search journey by showcasing a list of search queries that the user has - recently searched for across all their travel apps. The cluster will be - pinned in second position, after reservations and before featured and - recommendation clusters. Each developer partner will be allowed to broadcast - up to 3 entities in the Continue Search cluster. +- The **Continue Search** cluster helps users resume their previous travel search journey by showcasing a list of search queries that the user has recently searched for across all their travel apps. The cluster will be pinned in second position, after reservations and before featured and recommendation clusters. Each developer partner will be allowed to broadcast up to 3 entities in the Continue Search cluster. - **PointOfInterestEntity:** PointOfInterestEntity represents a place of interest like, a gas station, event venue, theme park, museum, tourist attraction, hiking trail etc. It highlights content the user has previously searched for. @@ -136,11 +79,9 @@ Add the `com.google.android.engage:engage-core` library to your app: ### Summary -The design is based on an implementation of a -[bound service](https://developer.android.com/guide/components/bound-services). +The design is based on an implementation of a [bound service](https://developer.android.com/guide/components/bound-services). -The data a client can publish is subject to the following limits for different -cluster types: +The data a client can publish is subject to the following limits for different cluster types: | Cluster type | Cluster limits | Minimum entity limits in a cluster | Maximum entity limits in a cluster | |---|---|---|---| @@ -151,8 +92,7 @@ cluster types: ### Step 1: Provide entity data -The SDK has defined different entities to represent each item type. We support -the following entities for the Travel \& Events category: +The SDK has defined different entities to represent each item type. We support the following entities for the Travel \& Events category: 1. `GenericFeaturedEntity` 2. `ArticleEntity` @@ -274,9 +214,7 @@ The charts below outline available attributes and requirements for each type. #### `StoreEntity` -The `StoreEntity` object represents an individual store that developer partners -want to publish, such as a popular dining place or eatery that are relevant to -one's travel experience. +The `StoreEntity` object represents an individual store that developer partners want to publish, such as a popular dining place or eatery that are relevant to one's travel experience. | Attribute | Requirement | Description | Format | |---|---|---|---| @@ -514,8 +452,7 @@ Required specifications for image assets are listed in this table: | Landscape (1.91x1) | 600x314 | 1200x628 | | Portrait (4x5) | 480x600 | 960x1200 | -The images are required to be hosted on public CDNs so that Google can access -them. +The images are required to be hosted on public CDNs so that Google can access them. *File formats* @@ -532,15 +469,13 @@ PNG, JPG, static GIF, WebP #### Timezone specifications -Prefer ID (for example, "America/Los_Angeles") over offset (for example, -"-07:00"). +Prefer ID (for example, "America/Los_Angeles") over offset (for example, "-07:00"). Sample usage: `DateTimeZone.forID("America/Los_Angeles")` #### Content Category -The content category allows apps to publish content belonging to multiple -categories. This maps the content with some of the predefined categories namely: +The content category allows apps to publish content belonging to multiple categories. This maps the content with some of the predefined categories namely: - `TYPE_EDUCATION` - `TYPE_SPORTS` @@ -560,33 +495,25 @@ categories. This maps the content with some of the predefined categories namely: - `TYPE_PARENTING` - `TYPE_DATING` -The images are required to be hosted on public CDNs so that Google can access -them. +The images are required to be hosted on public CDNs so that Google can access them. *Guidelines to use the content categories* 1. Some entities like **ArticleEntity** and **GenericFeaturedEntity** are eligible to use any of the content categories. For other entities like **EventEntity** , **EventReservationEntity** , **PointOfInterestEntity**, only a subset of these categories are eligible. Check the list of categories eligible for an entity type before populating the list. -2. Use the specific entity type for some content categories over a combination - of the Generic entities and the ContentCategory: +2. Use the specific entity type for some content categories over a combination of the Generic entities and the ContentCategory: - TYPE_MOVIES_AND_TV_SHOWS - Check out the entities from [Watch integration guide](https://developer.android.com/guide/playcore/engage/watch) before using the generic entities. - TYPE_BOOKS - Check out the [EbookEntity](https://developer.android.com/guide/playcore/engage/read#ebookentity) before using the generic entities. - TYPE_AUDIOBOOKS - Check out [AudiobookEntity](https://developer.android.com/guide/playcore/engage/read#audiobookentity) before using the generic entities. - TYPE_SHOPPING - Check out [ShoppingEntity](https://developer.android.com/guide/playcore/engage/shopping#shoppingEntity) before using the generic entities. - TYPE_FOOD_AND_DRINK - Check out entities from [Food Integration guide](https://developer.android.com/guide/playcore/engage/food) before using the generic entities. -3. The ContentCategory field is optional and should be left blank if the - content doesn't belong to any of the categories mentioned earlier. +3. The ContentCategory field is optional and should be left blank if the content doesn't belong to any of the categories mentioned earlier. -4. In case multiple content categories are provided, provide them in the order - of relevance to the content with the most relevant content category placed - first in the list. +4. In case multiple content categories are provided, provide them in the order of relevance to the content with the most relevant content category placed first in the list. ### Step 2: Provide Cluster data -It is recommended to have the content publish job executed in the background -(for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) -and scheduled on a regular basis or on an event basis (for example, every time -the user opens the app or when the user just added something to their cart). +It is recommended to have the content publish job executed in the background (for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) and scheduled on a regular basis or on an event basis (for example, every time the user opens the app or when the user just added something to their cart). `AppEngageTravelClient` is responsible for publishing clusters. @@ -608,16 +535,29 @@ There are following APIs to publish clusters in the client: #### `isServiceAvailable` -This API is used to check if the service is available for integration and -whether the content can be presented on the device. +This API is used to check if the service is available for integration and whether the content can be presented on the device. ##### For Engage SDK v1.6.0 and higher (Recommended) -You can check the service availability for every cluster type that you intend to -publish. The `isServiceAvailable` API accepts a request object, -`ServiceAvailabilityRequest`, which contains the cluster types for which service -availability needs to be checked. You can find the `ClusterType` enum values -required for `ServiceAvailabilityRequest` from the following table. +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/play/engage-sdk-integration) + +### Engage SDK integration + +To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill engage-sdk-integration + +If your team uses AI coding tools (such as Gemini in Android Studio), you can automate this migration by prompting your AI assistant: + + Use the engage-sdk-integration skill to use Engage SDK 1.6.0 and refactor isServiceAvailable to pass ServiceAvailabilityRequest for publishing all cluster types. + +
+ +You can check the service availability for every cluster type that you intend to publish. The `isServiceAvailable` API accepts a request object, `ServiceAvailabilityRequest`, which contains the cluster types for which service availability needs to be checked. You can find the `ClusterType` enum values required for `ServiceAvailabilityRequest` from the following table. | Cluster Type | Cluster Type Constant | Integer Value | |---|---|---| @@ -677,25 +617,11 @@ required for `ServiceAvailabilityRequest` from the following table. ###### Conditional Service Availability Feature -Some integrated apps request a special configuration that enables and disables -the Engage service intermittently in order to reduce their serving cost. This -intermittent content ingestion strategy, although possible, negatively affects -the user and the product -- stale content will not be presented and some surfaces -will not be served at all. +Some integrated apps request a special configuration that enables and disables the Engage service intermittently in order to reduce their serving cost. This intermittent content ingestion strategy, although possible, negatively affects the user and the product -- stale content will not be presented and some surfaces will not be served at all. -Starting with v1.6.0, the Engage SDK allows checking availability for specific -cluster types. This provides more flexibility so that if the intermittent -content strategy was adopted by a given application, some cluster types can -follow that intermittent strategy while other cluster types are always enabled -(i.e. continuation clusters). +Starting with v1.6.0, the Engage SDK allows checking availability for specific cluster types. This provides more flexibility so that if the intermittent content strategy was adopted by a given application, some cluster types can follow that intermittent strategy while other cluster types are always enabled (i.e. continuation clusters). -If the Engage service should not be 'continuously' enabled on all supported -devices for whatever reason, and is configured for intermittent ingestion for -any set of devices, all continuation cluster publications (e.g. Reservation -and Continue Search) will be still enabled by default configuration, and the -rest of the cluster types will be enabled and disabled intermittently. If -intermittent ingestion applies to you but this default configuration is not -suitable for your needs, please contact engage-developers@google.com. +If the Engage service should not be 'continuously' enabled on all supported devices for whatever reason, and is configured for intermittent ingestion for any set of devices, all continuation cluster publications (e.g. Reservation and Continue Search) will be still enabled by default configuration, and the rest of the cluster types will be enabled and disabled intermittently. If intermittent ingestion applies to you but this default configuration is not suitable for your needs, please contact engage-developers@google.com. ##### For SDK versions prior to v1.6.0 (Deprecated) @@ -769,14 +695,12 @@ This API is used to publish a list of `RecommendationCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `RecommendationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Recommendation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFeaturedCluster` @@ -807,14 +731,12 @@ This API is used to publish a list of `FeaturedCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FeaturedCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Featured Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishReservationCluster` @@ -851,14 +773,12 @@ This API is used to publish a `ReservationCluster` object. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ReservationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Reservation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishContinueSearchCluster` @@ -889,20 +809,16 @@ This API is used to publish a list of `ContinueSearchCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ContinueSearchCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Continue Search Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishUserAccountManagementRequest` -This API is used to publish a Sign In card . The signin action directs users to -the app's sign in page so that the app can publish content (or provide more -personalized content) +This API is used to publish a Sign In card . The signin action directs users to the app's sign in page so that the app can publish content (or provide more personalized content) The following metadata is part of the Sign In Card - @@ -955,20 +871,16 @@ The following metadata is part of the Sign In Card - .setSignInCardEntity(SIGN_IN_CARD_ENTITY) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `UserAccountManagementCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated UserAccountManagementCluster Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `updatePublishStatus` -If for any internal business reason, none of the clusters is published, we -**strongly recommend** updating the publish status using the -**updatePublishStatus** API. This is important because : +If for any internal business reason, none of the clusters is published, we **strongly recommend** updating the publish status using the **updatePublishStatus** API. This is important because : - Providing the status in all scenarios, even when the content is published (STATUS == PUBLISHED), is critical to populate dashboards that use this explicit status to convey the health and other metrics of your integration. - If no content is published but the integration status isn't broken (STATUS == NOT_PUBLISHED), Google can avoid triggering alerts in the app health dashboards. It confirms that content is not published due to an **expected** situation from the provider's standpoint. @@ -1008,11 +920,7 @@ The list of eligible publish status codes are : // Reach out to engage-developers@ before using this enum. AppEngagePublishStatusCode.NOT_PUBLISHED_OTHER -If the content is not published due to a user not logged in, Google would -recommend publishing the Sign In Card. If for any reason providers are not able -to publish the Sign In Card then we recommend calling the -**updatePublishStatus** API with the status code -**NOT_PUBLISHED_REQUIRES_SIGN_IN** +If the content is not published due to a user not logged in, Google would recommend publishing the Sign In Card. If for any reason providers are not able to publish the Sign In Card then we recommend calling the **updatePublishStatus** API with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** ### Kotlin @@ -1043,9 +951,7 @@ This API is used to delete the content of Recommendation Clusters. client.deleteRecommendationClusters(); -When the service receives the request, it removes the existing data from the -Recommendation Clusters. In case of an error, the entire request is rejected and -the existing state is maintained. +When the service receives the request, it removes the existing data from the Recommendation Clusters. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -1065,9 +971,7 @@ This API is used to delete the content of Featured Cluster. client.deleteFeaturedCluster(); -When the service receives the request, it removes the existing data from the -Featured Cluster. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from the Featured Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -1087,9 +991,7 @@ This API is used to delete the content of Reservation Cluster. client.deleteReservationCluster(); -When the service receives the request, it removes the existing data from the -Reservation Cluster. In case of an error, the entire request is rejected and -the existing state is maintained. +When the service receives the request, it removes the existing data from the Reservation Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -1109,9 +1011,7 @@ This API is used to delete the content of UserAccountManagement Cluster. client.deleteUserManagementCluster(); -When the service receives the request, it removes the existing data from the -UserAccountManagement Cluster. In case of an error, the entire request is -rejected and the existing state is maintained. +When the service receives the request, it removes the existing data from the UserAccountManagement Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -1131,9 +1031,7 @@ This API is used to delete the content of Continue Search Cluster. client.deleteContinueSearchCluster(); -When the service receives the request, it removes the existing data from the -Continue Search Cluster. In case of an error, the entire request is -rejected, and the existing state is maintained. +When the service receives the request, it removes the existing data from the Continue Search Cluster. In case of an error, the entire request is rejected, and the existing state is maintained. > [!NOTE] > **Note:** This API is available from version 1.5.6 onwards. @@ -1165,15 +1063,11 @@ This API is used to delete the content of a given cluster type. .addClusterType(ClusterType.TYPE_CONTINUE_SEARCH) .build()); -When the service receives the request, it removes the existing data from all -clusters matching the specified cluster types. Clients can choose to pass one or -many cluster types. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from all clusters matching the specified cluster types. Clients can choose to pass one or many cluster types. In case of an error, the entire request is rejected and the existing state is maintained. #### Error handling -It is highly recommended to listen to the task result from the publish APIs such -that a follow-up action can be taken to recover and resubmit an successful task. +It is highly recommended to listen to the task result from the publish APIs such that a follow-up action can be taken to recover and resubmit an successful task. ### Kotlin @@ -1217,8 +1111,7 @@ that a follow-up action can be taken to recover and resubmit an successful task. } }); -The error is returned as an `AppEngageException` with the cause included as an -error code. +The error is returned as an `AppEngageException` with the cause included as an error code. | Error code | Error name | Note | |---|---|---| @@ -1232,23 +1125,13 @@ error code. ### Step 3: Handle broadcast intents -In addition to making publish content API calls through a job, it is also -required to set up a -[`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive -the request for a content publish. +In addition to making publish content API calls through a job, it is also required to set up a [`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive the request for a content publish. -The goal of broadcast intents is mainly for app reactivation and forcing data -sync. Broadcast intents are not designed to be sent very frequently. It is only -triggered when the Engage Service determines the content might be stale (for -example, a week old). That way, there is more confidence that the user can have -a fresh content experience, even if the application has not been executed for a -long period of time. +The goal of broadcast intents is mainly for app reactivation and forcing data sync. Broadcast intents are not designed to be sent very frequently. It is only triggered when the Engage Service determines the content might be stale (for example, a week old). That way, there is more confidence that the user can have a fresh content experience, even if the application has not been executed for a long period of time. The `BroadcastReceiver` must be set up in the following two ways: -- Dynamically register an instance of the `BroadcastReceiver` class using - `Context.registerReceiver()`. This enables communication from applications - that are still live in memory. +- Dynamically register an instance of the `BroadcastReceiver` class using `Context.registerReceiver()`. This enables communication from applications that are still live in memory. ### Kotlin @@ -1336,10 +1219,7 @@ The `BroadcastReceiver` must be set up in the following two ways: } -- Statically declare an implementation with the `` tag in your - `AndroidManifest.xml` file. This allows the application to receive broadcast - intents when it is not running, and also allows the application to publish - the content. +- Statically declare an implementation with the `` tag in your `AndroidManifest.xml` file. This allows the application to receive broadcast intents when it is not running, and also allows the application to publish the content. -The following [intents](https://developer.android.com/reference/android/content/Intent) is sent by the -service: +The following [intents](https://developer.android.com/reference/android/content/Intent) is sent by the service: - `com.google.android.engage.action.PUBLISH_RECOMMENDATION` It is recommended to start a `publishRecommendationClusters` call when receiving this intent. - `com.google.android.engage.action.PUBLISH_FEATURED` It is recommended to start a `publishFeaturedCluster` call when receiving this intent. @@ -1372,19 +1251,15 @@ service: ## Integration workflow -For a step-by-step guide on verifying your integration after it is complete, see -[Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). +For a step-by-step guide on verifying your integration after it is complete, see [Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). ## FAQs -See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for -FAQs. +See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for FAQs. ## Contact -Contact -[`engage-developers@google.com`](mailto:engage-developers@google.com) if there are -any questions during the integration process. +Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during the integration process. ## Next steps diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/continue-watching/index.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/continue-watching/index.md index 555b293..dd88e0e 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/continue-watching/index.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/continue-watching/index.md @@ -1,19 +1,10 @@ -Continue watching leverages the **Continuation cluster** to show unfinished -videos, and next episodes to be watched from the same TV show, from multiple -apps in one UI grouping. You can feature your entities in this continuation -cluster. Follow this guide to learn how to enhance user engagement through the -continue watching experience using [Engage SDK](https://developer.android.com/guide/playcore/engage). +Continue watching leverages the **Continuation cluster** to show unfinished videos, and next episodes to be watched from the same TV show, from multiple apps in one UI grouping. You can feature your entities in this continuation cluster. Follow this guide to learn how to enhance user engagement through the continue watching experience using [Engage SDK](https://developer.android.com/guide/playcore/engage). -You manage the continuation cluster by using the client API in a TV app or from -a REST API: +You manage the continuation cluster by using the client API in a TV app or from a REST API: - [Integrate continue watching on Android TV](https://developer.android.com/guide/playcore/engage/tv/continue-watching/client) - [Integrate continue watching using REST API](https://developer.android.com/guide/playcore/engage/tv/continue-watching/rest) ## Sample code -This [sample app](https://github.com/googlesamples/tv-video-discovery-samples) demonstrates how you can integrate with Engage SDK -to send personalized user data to Google. It shows how to build a common module -that you can import in both mobile and TV apps. The sample also illustrates -when to call the publish and delete APIs, as well as how to use Workers to -make these calls. \ No newline at end of file +This [sample app](https://github.com/googlesamples/tv-video-discovery-samples) demonstrates how you can integrate with Engage SDK to send personalized user data to Google. It shows how to build a common module that you can import in both mobile and TV apps. The sample also illustrates when to call the publish and delete APIs, as well as how to use Workers to make these calls. \ No newline at end of file diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/entitlements.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/entitlements.md index a2ce68c..5ef572e 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/entitlements.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/entitlements.md @@ -1,17 +1,11 @@ -This guide contains instructions for developers to share app subscription and -entitlement data with Google TV using [Engage SDK](https://developer.android.com/guide/playcore/engage). Users can find -content they are entitled to and enable Google TV to deliver highly relevant -content recommendations to users, directly within Google TV experiences on TV, -mobile, and tablet. +This guide contains instructions for developers to share app subscription and entitlement data with Google TV using [Engage SDK](https://developer.android.com/guide/playcore/engage). Users can find content they are entitled to and enable Google TV to deliver highly relevant content recommendations to users, directly within Google TV experiences on TV, mobile, and tablet. ## Prerequisites > [!IMPORTANT] > **Important:** [Express interest in developing with Engage](http://g.co/tv/vda). -Onboarding the media actions feed is required before you can use the device -entitlement API. If you haven't already done so, complete the [media actions -feed](https://developers.google.com/actions/media?authuser=0) onboarding process. +Onboarding the media actions feed is required before you can use the device entitlement API. If you haven't already done so, complete the [media actions feed](https://developers.google.com/actions/media?authuser=0) onboarding process. ## Pre-work @@ -26,17 +20,13 @@ Complete the [Pre-work](https://developer.android.com/guide/playcore/engage/tv/g ## Integration -This section provides the necessary code examples and instructions for -implementing `SubscriptionEntity` to manage various subscription types. +This section provides the necessary code examples and instructions for implementing `SubscriptionEntity` to manage various subscription types. ### Common tier subscription -For users with basic subscriptions to media provider services, for example, a -service that has one subscription tier that grants access to all the paid -content, provide these essential details: +For users with basic subscriptions to media provider services, for example, a service that has one subscription tier that grants access to all the paid content, provide these essential details: -1. `SubscriptionType`: Clearly indicate the specific subscription plan the user - has. +1. `SubscriptionType`: Clearly indicate the specific subscription plan the user has. - `SUBSCRIPTION_TYPE_ACTIVE`: User has an active paid subscription. - `SUBSCRIPTION_TYPE_ACTIVE_TRIAL`: User has a trial subscription. @@ -45,11 +35,9 @@ content, provide these essential details: > [!IMPORTANT] > **Important:** Only users with `SUBSCRIPTION_TYPE_ACTIVE` or `SUBSCRIPTION_TYPE_ACTIVE_TRIAL` are eligible for personalized content recommendations based on their subscription. -2. `ExpirationTimeMillis`: Optional time in milliseconds. Specify when the - subscription is set to expire. +2. `ExpirationTimeMillis`: Optional time in milliseconds. Specify when the subscription is set to expire. -3. `ProviderPackageName`: Specify the package name of the app that handles the - subscription. +3. `ProviderPackageName`: Specify the package name of the app that handles the subscription. Example for the sample media provider feed. @@ -83,9 +71,7 @@ The following example creates a `SubscriptionEntity` for a user: ### Premium subscription -If app offer multi-tiered premium subscription packages, which includes expanded -content or features beyond the common tier, represent this by adding one or more -entitlements to Subscription. +If app offer multi-tiered premium subscription packages, which includes expanded content or features beyond the common tier, represent this by adding one or more entitlements to Subscription. This entitlement has the following fields: @@ -158,9 +144,7 @@ The following example creates a `SubscriptionEntity` for a subscribed user: ### Subscription for linked service package -While subscriptions typically belong to the originating app's media provider, a -subscription can be attributed to a linked service package by specifying the -linked service package name within the subscription. +While subscriptions typically belong to the originating app's media provider, a subscription can be attributed to a linked service package by specifying the linked service package name within the subscription. Following code sample demonstrate how to create user subscription. @@ -175,8 +159,7 @@ Following code sample demonstrate how to create user subscription. .setExpirationTimeMillis(1767052800000) .build() -In addition, if the user has another subscription to a subsidiary service, add -another subscription and set the linked service package name accordingly. +In addition, if the user has another subscription to a subsidiary service, add another subscription and set the linked service package name accordingly. // Subscription for linked service package val linkedSubscription = Subscription.Builder() @@ -211,11 +194,9 @@ Optionally, add entitlements to a linked service subscription too. Run the content publish job while the app is in the foreground. -Use the `publishSubscriptionCluster()` method, from the -`AppEngagePublishClient` class, to publish a `SubscriptionCluster` object. +Use the `publishSubscriptionCluster()` method, from the `AppEngagePublishClient` class, to publish a `SubscriptionCluster` object. -Make sure to initialize the client and check for service availability as -described in the [Getting Started guide](https://developer.android.com/guide/playcore/engage/tv/getting-started#common-integration). +Make sure to initialize the client and check for service availability as described in the [Getting Started guide](https://developer.android.com/guide/playcore/engage/tv/getting-started#common-integration). client.publishSubscription( PublishSubscriptionRequest.Builder() @@ -224,35 +205,22 @@ described in the [Getting Started guide](https://developer.android.com/guide/pla .build() ) -Use `setSubscription()` to verify that user should have only one subscription to -the service. +Use `setSubscription()` to verify that user should have only one subscription to the service. -Use `addLinkedSubscription()`, or `addLinkedSubscriptions()` which accept a list -of linked subscriptions, to enable user to have zero or more linked -subscriptions. +Use `addLinkedSubscription()`, or `addLinkedSubscriptions()` which accept a list of linked subscriptions, to enable user to have zero or more linked subscriptions. -When the service receives the request, a new entry is created and the old entry -is automatically deleted after 60 days. The system always uses the latest entry. -In case of an error, the entire request is rejected and the existing state is -maintained. +When the service receives the request, a new entry is created and the old entry is automatically deleted after 60 days. The system always uses the latest entry. In case of an error, the entire request is rejected and the existing state is maintained. ### Keep subscription up-to-date -1. To provide immediate updates upon changes, call - `publishSubscriptionCluster` whenever a user's subscription state changes - like activation, deactivation, upgrades, downgrades. +1. To provide immediate updates upon changes, call `publishSubscriptionCluster` whenever a user's subscription state changes like activation, deactivation, upgrades, downgrades. -2. To provide regular validation for ongoing accuracy, call - `publishSubscriptionCluster` at least once per month. +2. To provide regular validation for ongoing accuracy, call `publishSubscriptionCluster` at least once per month. > [!NOTE] > **Note:** As Google TV automatically deletes historical data beyond 60 days to safeguard user privacy, publishing user subscription data at least once per month verify the validity of data. Unlike `publishContinuationCluster` for continue watching data, don't set `syncAcrossDevices` flag, as subscription information is by default used to provide content across all devices. -3. To delete the Engage data, manually delete a user's data from the - Google TV server before the standard 60-day retention period, use the - `client.deleteClusters` method. This deletes all existing Engage - data for the account profile, or for the entire account depending on the - given [`DeleteReason`](https://developer.android.com/reference/com/google/android/engage/service/DeleteReason). +3. To delete the Engage data, manually delete a user's data from the Google TV server before the standard 60-day retention period, use the `client.deleteClusters` method. This deletes all existing Engage data for the account profile, or for the entire account depending on the given [`DeleteReason`](https://developer.android.com/reference/com/google/android/engage/service/DeleteReason). The following code snippet shows how to remove a user subscription: @@ -266,8 +234,7 @@ maintained. .build() ) - The following code snippet demonstrates removal of user subscription - when user revokes the consent: + The following code snippet demonstrates removal of user subscription when user revokes the consent: // If the user revokes the consent to share across device, make the call // to remove subscription and other Engage data from all google @@ -279,8 +246,7 @@ maintained. .build() ) - Following code demonstrates how to remove subscription data on user profile - deletion. + Following code demonstrates how to remove subscription data on user profile deletion. // If the user delete a specific profile, you must make the following call // to remove subscription data and other Engage data. @@ -293,13 +259,11 @@ maintained. ### Testing -This section provides a step-by-step guide for testing subscription -implementation. Verify data accuracy and proper functionality before launch. +This section provides a step-by-step guide for testing subscription implementation. Verify data accuracy and proper functionality before launch. #### Publish Integration checklist -1. Publishing should happen when the app is in the foreground and user the - actively interacting with it. +1. Publishing should happen when the app is in the foreground and user the actively interacting with it. 2. Publish when: @@ -308,12 +272,9 @@ implementation. Verify data accuracy and proper functionality before launch. - User purchases new subscription. - User upgrades subscription. - User subscription expires. -3. Check if app is correctly calling `isServiceAvailable()` and - `publishClusters()` APIs in logcat, on the publishing events. +3. Check if app is correctly calling `isServiceAvailable()` and `publishClusters()` APIs in logcat, on the publishing events. -4. Verify that data is visible in the verification app. The verification app - should display subscription as a separate row. When the publish API is - invoked, the data should show up in the verification app. +4. Verify that data is visible in the verification app. The verification app should display subscription as a separate row. When the publish API is invoked, the data should show up in the verification app. > [!IMPORTANT] > **Important:** Verify that the [Engage Service Flag](https://developer.android.com/guide/playcore/engage/workflow#switch-to-prod) is **not** set to production. @@ -331,23 +292,15 @@ implementation. Verify data accuracy and proper functionality before launch. To test your integration, use the [verification app](https://developer.android.com/guide/playcore/engage/tv/getting-started#testing). 1. For each of the events, check if app has invoked the `publishSubscription` API. Verify the published data in the verification app. **Verify that everything is green in verification app** -2. If all the entity's information is correct, it shows an "All Good" green - check in all entities. +2. If all the entity's information is correct, it shows an "All Good" green check in all entities. ![Verification App Success Screenshot](https://developer.android.com/static/images/guide/playcore/engage/ett-va-success.png) **Figure 1.** Successful subscription 3. Problems are also highlighted in verification app ![Verification App Error Screenshot](https://developer.android.com/static/images/guide/playcore/engage/ett-va-error.png) **Figure 2.**Subscription unsuccessful -4. To see the problems in the bundled subscription, use the TV remote to focus - on that specific bundled subscription and click to see the problems. You - might have to first focus on the row and move to the right to find Bundled - Subscription card. The problems are highlighted as red as shown in Fig 3. - Also, use the remote to move down to see problems in the entitlements within - bundled subscription +4. To see the problems in the bundled subscription, use the TV remote to focus on that specific bundled subscription and click to see the problems. You might have to first focus on the row and move to the right to find Bundled Subscription card. The problems are highlighted as red as shown in Fig 3. Also, use the remote to move down to see problems in the entitlements within bundled subscription ![Verification App Error Details Screenshot](https://developer.android.com/static/images/guide/playcore/engage/ett-va-error-details.png) **Figure 3.**Subscription Errors -5. To see the problems in the entitlement, use the TV remote to focus on that - specific entitlement and click to see the problems. The problems are - highlighted as red. +5. To see the problems in the entitlement, use the TV remote to focus on that specific entitlement and click to see the problems. The problems are highlighted as red. ![Verification App Error Screenshot](https://developer.android.com/static/images/guide/playcore/engage/ett-va-details.png) **Figure 4.**Subscription Error Details \ No newline at end of file diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/getting-started.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/getting-started.md index 49d8975..578edc4 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/getting-started.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/getting-started.md @@ -1,11 +1,8 @@
-[Engage SDK](https://developer.android.com/guide/playcore/engage) lets you deliver personalized recommendations -and continuation content directly to users on Google TV. +[Engage SDK](https://developer.android.com/guide/playcore/engage) lets you deliver personalized recommendations and continuation content directly to users on Google TV. -This guide covers how to get started with Engage SDK integrations for TV. After -you complete the pre-work on this page, you can integrate one or more -of the TV features: +This guide covers how to get started with Engage SDK integrations for TV. After you complete the pre-work on this page, you can integrate one or more of the TV features: - [Publish continue watching data](https://developer.android.com/guide/playcore/engage/tv/continue-watching) - [Publish device entitlements](https://developer.android.com/guide/playcore/engage/tv/entitlements) @@ -15,16 +12,13 @@ of the TV features: Before you begin, complete the following steps: -1. [Express interest in developing with Engage SDK](http://g.co/tv/engage) to enroll in - the program, if eligible. +1. [Express interest in developing with Engage SDK](http://g.co/tv/engage) to enroll in the program, if eligible. -2. Verify that your app targets Android 4.4 (API level 19) or higher for this - integration. +2. Verify that your app targets Android 4.4 (API level 19) or higher for this integration. 3. Add the `com.google.android.engage` library to your app: - There are separate SDKs to use in the integration: one for mobile apps and - one for TV apps. + There are separate SDKs to use in the integration: one for mobile apps and one for TV apps. ### Mobile @@ -42,18 +36,19 @@ Before you begin, complete the following steps: -5. Verify reliable content publishing by using a background service, such as - `androidx.work`, for scheduling. +5. Verify reliable content publishing by using a background service, such as `androidx.work`, for scheduling. -6. Test your implementation using the verification app as outlined in the - [Testing section](https://developer.android.com/guide/playcore/engage/tv/getting-started#testing). +6. Test your implementation using the verification app as outlined in the [Testing section](https://developer.android.com/guide/playcore/engage/tv/getting-started#testing). -7. In your production app, set the Engage service environment to production in - the `AndroidManifest.xml` file. +7. In your production app, set the Engage service environment to production by adding the `` element directly under the `` tag in your `AndroidManifest.xml` file. Don't place this tag inside an ``. - + + + + + > [!IMPORTANT] > **Important:** The Engage service environment declaration is only needed for your release build. For your local testing with the verification app, don't include this element. @@ -62,8 +57,7 @@ Before you begin, complete the following steps: ### Initialize the client -Use `AppEngagePublishClient` to interact with the service. Always check if the -service is available before publishing. +Use `AppEngagePublishClient` to interact with the service. Always check if the service is available before publishing. val client = AppEngagePublishClient(context) @@ -77,8 +71,7 @@ service is available before publishing. ### Create an account profile -`AccountProfile` identifies the user. You can specify an account ID, and -optionally a profile ID and locale. +`AccountProfile` identifies the user. You can specify an account ID, and optionally a profile ID and locale. val accountProfile = AccountProfile.Builder() .setAccountId("your_users_account_id") @@ -86,19 +79,15 @@ optionally a profile ID and locale. .setLocale(Locale.US.toLanguageTag()) // Optional, e.g., "en-US" .build() -An `AccountProfile` must be provided with an account ID in order for content to -be synchronized between devices. See [Cross-device syncing](https://developer.android.com/guide/playcore/engage/tv/continue-watching/client#cross-device_syncing). +An `AccountProfile` must be provided with an account ID in order for content to be synchronized between devices. See [Cross-device syncing](https://developer.android.com/guide/playcore/engage/tv/continue-watching/client#cross-device_syncing). ## Testing To test your integration, download the verification app: -[Download verification -app](https://developer.android.com/guide/playcore/engage/tv/getting-started#lightbox-trigger) +[Download verification app](https://developer.android.com/guide/playcore/engage/tv/getting-started#lightbox-trigger) -The verification app is an Android app with capabilities to help you test your -integration. It let you to check data accuracy and proper functionality by -verifying published data and broadcast intents before launch. +The verification app is an Android app with capabilities to help you test your integration. It let you to check data accuracy and proper functionality by verifying published data and broadcast intents before launch. 1. Install and open the Engage Verification app. 2. If the value of `isServiceAvailable` is `false` in the verification app, click the **Toggle** button within the verification app to set it to `true`. diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/recommendations.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/recommendations.md index a2fd19b..404104f 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/recommendations.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/tv/recommendations.md @@ -1,11 +1,6 @@ -This guide contains instructions for developers to integrate their recommended -video content, using the [Engage SDK](https://developer.android.com/guide/playcore/engage), to populate recommendations -experiences across Google surfaces, such as TV, mobile, and tablet. +This guide contains instructions for developers to integrate their recommended video content, using the [Engage SDK](https://developer.android.com/guide/playcore/engage), to populate recommendations experiences across Google surfaces, such as TV, mobile, and tablet. -Recommendation leverages the **Recommendation cluster** to show movies and TV -shows, from multiple apps in one UI grouping. Each developer partner can -broadcast a maximum **of 25 entities** in each recommendations cluster and there -can be a maximum **of 7** recommendation clusters per request. +Recommendation leverages the **Recommendation cluster** to show movies and TV shows, from multiple apps in one UI grouping. Each developer partner can broadcast a maximum **of 25 entities** in each recommendations cluster and there can be a maximum **of 7** recommendation clusters per request. ## Pre-work @@ -21,22 +16,17 @@ Complete the [Pre-work](https://developer.android.com/guide/playcore/engage/tv/g ## Integration -`AppEngagePublishClient` publishes the recommendation cluster. Use the -`publishRecommendationClusters` method to publish a recommendations object. +`AppEngagePublishClient` publishes the recommendation cluster. Use the `publishRecommendationClusters` method to publish a recommendations object. -Make sure to initialize the client and check for service availability as -described in the [Getting Started guide](https://developer.android.com/guide/playcore/engage/tv/getting-started#common-integration). +Make sure to initialize the client and check for service availability as described in the [Getting Started guide](https://developer.android.com/guide/playcore/engage/tv/getting-started#common-integration). client.publishRecommendationClusters(recommendationRequest) ### Upserting recommendation clusters -Clusters are logical grouping of the entities. The following code examples -explains how to build the clusters based on your preference and how to create a -publishing request and upsert all clusters. +Clusters are logical grouping of the entities. The following code examples explains how to build the clusters based on your preference and how to create a publishing request and upsert all clusters. -The [`RecommendationClusterType`](https://developer.android.com/reference/com/google/android/engage/common/datamodel/RecommendationClusterType) determines how the -cluster will be displayed. +The [`RecommendationClusterType`](https://developer.android.com/reference/com/google/android/engage/common/datamodel/RecommendationClusterType) determines how the cluster will be displayed. // cluster for popular movies val recommendationCluster1 = RecommendationCluster @@ -73,8 +63,7 @@ cluster will be displayed. .addRecommendationCluster(recommendationCluster2) .build() -When the service receives the request, the following actions occur within one -transaction: +When the service receives the request, the following actions occur within one transaction: - Existing `RecommendationsCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated `RecommendationsCluster`. In case of an error, the entire request is rejected and the existing state is maintained. @@ -84,27 +73,17 @@ transaction: ### Cross-device sync -`SyncAcrossDevices` flag controls whether a user's recommendations cluster data -is shared with Google TV and available across their devices such as TV, phone, -tablets. In order for the recommendation to work, it must be set to true. +`SyncAcrossDevices` flag controls whether a user's recommendations cluster data is shared with Google TV and available across their devices such as TV, phone, tablets. In order for the recommendation to work, it must be set to true. ### Obtain consent -The media application must provide a clear setting to enable or disable -cross-device syncing. Explain the benefits to the user and store the user's -preference once and apply it in `publishRecommendations` Request accordingly. To -get the most out of cross-device feature, verify app obtains user -consent and enables `SyncAcrossDevices` to `true`. +The media application must provide a clear setting to enable or disable cross-device syncing. Explain the benefits to the user and store the user's preference once and apply it in `publishRecommendations` Request accordingly. To get the most out of cross-device feature, verify app obtains user consent and enables `SyncAcrossDevices` to `true`. ### Delete the Engage data -To manually delete a user's data from the Google TV server before the standard -60-day retention period, use the `client.deleteClusters()` method. Upon -receiving the request, the service deletes all existing Engage -data for the account profile, or for the entire account. +To manually delete a user's data from the Google TV server before the standard 60-day retention period, use the `client.deleteClusters()` method. Upon receiving the request, the service deletes all existing Engage data for the account profile, or for the entire account. -The [`DeleteReason`](https://developer.android.com/reference/com/google/android/engage/service/DeleteReason) enum defines the reason for data deletion. -The following code removes recommendations on logout. +The [`DeleteReason`](https://developer.android.com/reference/com/google/android/engage/service/DeleteReason) enum defines the reason for data deletion. The following code removes recommendations on logout. // If the user logs out from your media app, you must make the following call // to remove recommendations data from the current Google TV device, otherwise, @@ -129,8 +108,7 @@ The following code removes recommendations on logout. ## Create entities -The SDK has defined different entities to represent each item type. Following -entities are supported for the Recommendation cluster: +The SDK has defined different entities to represent each item type. Following entities are supported for the Recommendation cluster: 1. [`MediaActionFeedEntity`](https://developer.android.com/reference/com/google/android/engage/video/datamodel/MediaActionFeedEntity) 2. [`MovieEntity`](https://developer.android.com/reference/com/google/android/engage/video/datamodel/MovieEntity) @@ -140,27 +118,21 @@ entities are supported for the Recommendation cluster: ### Provide descriptions -Provide a short description for each entity; this description will be displayed -when users hover over the entity, providing them with additional details. +Provide a short description for each entity; this description will be displayed when users hover over the entity, providing them with additional details. ### Call to action text -Provide an optional call to action text for each entity. This text will be -displayed to the user to encourage engagement. +Provide an optional call to action text for each entity. This text will be displayed to the user to encourage engagement. ### Tags -Optionally provide a list of tags for each entity. Tags can be used for -categorization and filtering. +Optionally provide a list of tags for each entity. Tags can be used for categorization and filtering. ### Platform specific playBack URIs -Create playback URIs for each supported platform: Android TV, Android, or iOS. -This allows the system to select the appropriate URI for video playback on the -respective platform. +Create playback URIs for each supported platform: Android TV, Android, or iOS. This allows the system to select the appropriate URI for video playback on the respective platform. -In the rare case when the playback URIs are identical for all platforms, -repeat it for every platform. +In the rare case when the playback URIs are identical for all platforms, repeat it for every platform. // Required. Set this when you want recommended entities to show up on // Google TV @@ -198,12 +170,7 @@ repeat it for every platform. ### Poster images -Poster images require a URI and pixel dimensions (height and width). Target -different form factors by providing multiple poster images, but verify all -images maintain a 16:9 aspect ratio and a minimum height of 200 pixels for -correct display of the "Recommendations" entity, especially within Google's -[Entertainment Space](https://support.google.com/entertainmentspace/answer/10346911). Images with a height less than 200 -pixels may not be shown. +Poster images require a URI and pixel dimensions (height and width). Target different form factors by providing multiple poster images, but verify all images maintain a 16:9 aspect ratio and a minimum height of 200 pixels for correct display of the "Recommendations" entity, especially within Google's [Entertainment Space](https://support.google.com/entertainmentspace/answer/10346911). Images with a height less than 200 pixels may not be shown. Image image1 = new Image.Builder() .setImageUri(Uri.parse("http://www.example.com/entity_image1.png");) @@ -222,9 +189,7 @@ pixels may not be shown. ### Recommendation reason -Optionally provide a recommendation reason which can be used by Google -TV to construct reasons as to why to suggest a specific Movie or TV Show to -the user. +Optionally provide a recommendation reason which can be used by Google TV to construct reasons as to why to suggest a specific Movie or TV Show to the user. //Allows us to construct reason: "Because it is top 10 on your Channel" val topOnPartner = RecommendationReasonTopOnPartner @@ -271,11 +236,7 @@ the user. ### Display time window -If an entity should only be available for a limited time, set a custom -expiration time. Without an explicit expiration time, entities will -automatically expire and be erased after 60 days. So set an expiration time only -when the entities need to be expired sooner. Specify multiple such -availability windows. +If an entity should only be available for a limited time, set a custom expiration time. Without an explicit expiration time, entities will automatically expire and be erased after 60 days. So set an expiration time only when the entities need to be expired sooner. Specify multiple such availability windows. val window1 = DisplayTimeWindow .Builder() @@ -290,12 +251,7 @@ availability windows. ### DataFeedElementId -If you have integrated your Media catalogue or Media action feed with Google TV, -you need not create separate entities for Movie or TV Show and instead you can -create a [`MediaActionFeedEntity`](https://developer.android.com/reference/com/google/android/engage/video/datamodel/MediaActionFeedEntity) which includes the -required field DataFeedElementId. This Id must be unique and must match with the -ID in Media Action Feed as it helps to identify ingested feed content and -perform media content lookups. +If you have integrated your Media catalogue or Media action feed with Google TV, you need not create separate entities for Movie or TV Show and instead you can create a [`MediaActionFeedEntity`](https://developer.android.com/reference/com/google/android/engage/video/datamodel/MediaActionFeedEntity) which includes the required field DataFeedElementId. This Id must be unique and must match with the ID in Media Action Feed as it helps to identify ingested feed content and perform media content lookups. val id = "dataFeedElementId" @@ -314,9 +270,7 @@ Here's an example of creating a `MovieEntity` with all the required fields: .addTag("Action") .build() -You can provide additional data such as genres, content ratings, release date, -recommendation reason and availability time windows, which may be used by Google -TV for enhanced displays or filtering purposes. +You can provide additional data such as genres, content ratings, release date, recommendation reason and availability time windows, which may be used by Google TV for enhanced displays or filtering purposes. val genres = Arrays.asList("Action", "Science fiction"); val rating1 = RatingSystem.Builder().setAgencyName("MPAA").setRating("pg-13").build(); @@ -345,9 +299,7 @@ Here's an example of creating a `TvShowEntity` with all the required fields: .addTag("Drama") .build(); -Optionally provide additional data such as genres, content ratings, -recommendation reason, offer price, season count or availability time window, -which may be used by Google TV for enhanced displays or filtering purposes. +Optionally provide additional data such as genres, content ratings, recommendation reason, offer price, season count or availability time window, which may be used by Google TV for enhanced displays or filtering purposes. val genres = Arrays.asList("Action", "Science fiction"); val rating1 = RatingSystem.Builder() @@ -372,8 +324,7 @@ which may be used by Google TV for enhanced displays or filtering purposes. ### `MediaActionFeedEntity` -Here's an example of creating an `MediaActionFeedEntity` with all the required -fields: +Here's an example of creating an `MediaActionFeedEntity` with all the required fields: val mediaActionFeedEntity = MediaActionFeedEntity.Builder() .setDataFeedElementId(id) @@ -381,9 +332,7 @@ fields: .addTag("Action") .build() -Optionally provide additional data such as description, recommendation reason -and display time window, which may be used by Google TV for enhanced displays or -filtering purposes. +Optionally provide additional data such as description, recommendation reason and display time window, which may be used by Google TV for enhanced displays or filtering purposes. val mediaActionFeedEntity = MediaActionFeedEntity.Builder() .setName("Movie name or TV Show name") @@ -394,8 +343,7 @@ filtering purposes. ### `LiveTvChannelEntity` -This represents a live TV channel. Here's an example of creating a -`LiveTvChannelEntity` with all the required fields: +This represents a live TV channel. Here's an example of creating a `LiveTvChannelEntity` with all the required fields: val liveTvChannelEntity = LiveTvChannelEntity.Builder() .setName("Channel Name") @@ -409,8 +357,7 @@ This represents a live TV channel. Here's an example of creating a .addTag("News") .build() -Optionally provide additional data such as content ratings or -recommendation reason. +Optionally provide additional data such as content ratings or recommendation reason. val rating1 = RatingSystem.Builder() .setAgencyName("MPAA") @@ -426,9 +373,7 @@ recommendation reason. ### `LiveTvProgramEntity` -This represents a live TV program card airing or scheduled to air on -a live TV channel. Here's an example of creating a `LiveTvProgramEntity` -with all the required fields: +This represents a live TV program card airing or scheduled to air on a live TV channel. Here's an example of creating a `LiveTvProgramEntity` with all the required fields: val liveTvProgramEntity = LiveTvProgramEntity.Builder() // First set the channel information @@ -450,8 +395,7 @@ with all the required fields: .addTag("Sports") .build() -Optionally provide additional data such as content ratings, genres, or -recommendation reason. +Optionally provide additional data such as content ratings, genres, or recommendation reason. val rating1 = RatingSystem.Builder() .setAgencyName("MPAA") diff --git a/play/engage-sdk-integration/references/android/guide/playcore/engage/watch.md b/play/engage-sdk-integration/references/android/guide/playcore/engage/watch.md index 3dc495e..4507511 100644 --- a/play/engage-sdk-integration/references/android/guide/playcore/engage/watch.md +++ b/play/engage-sdk-integration/references/android/guide/playcore/engage/watch.md @@ -1,18 +1,9 @@ > [!IMPORTANT] > **Important:** Engage SDK has superseded Media Home, which is now deprecated. If you have an existing Media Home integration, follow the instructions in these guides to migrate your content to Engage SDK, which allows your content to be published to more devices and form factors. Please contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if you have any questions. -Boost app engagement by reaching your users where they are. Integrate Engage -SDK to deliver Continue Watching content and personalized recommendations -directly to users across multiple on-device surfaces -**[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , -**[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The -integration adds less than 50 KB (compressed) to the average APK and takes -most apps about a week of developer time. Learn more at our -**[business site](http://play.google.com/console/about/programs/EngageSDK)**. +Boost app engagement by reaching your users where they are. Integrate Engage SDK to deliver Continue Watching content and personalized recommendations directly to users across multiple on-device surfaces **[Collections](https://android-developers.googleblog.com/2024/07/introducing-collections-powered-by-engage-sdk.html)** , **[Entertainment Space](https://blog.google/products/android/entertainment-space/)** , and the Play Store. The integration adds less than 50 KB (compressed) to the average APK and takes most apps about a week of developer time. Learn more at our **[business site](http://play.google.com/console/about/programs/EngageSDK)**. -This guide contains instructions for developer partners to integrate their video -content, using the Engage SDK to populate both this new surface area and -existing Google surfaces. +This guide contains instructions for developer partners to integrate their video content, using the Engage SDK to populate both this new surface area and existing Google surfaces. > [!NOTE] > **Note:** Check the [TV integration guide](https://developer.android.com/guide/playcore/engage/tv) to learn more about the Continue Watching experience on Google TV. @@ -21,35 +12,21 @@ existing Google surfaces. ### Terminology -This integration includes the following three cluster types: **Recommendation** , -**Continuation** , and **Featured**. +This integration includes the following three cluster types: **Recommendation** , **Continuation** , and **Featured**. -- **Recommendation** clusters show personalized suggestions for content to watch - from an individual developer partner. +- **Recommendation** clusters show personalized suggestions for content to watch from an individual developer partner. Your recommendations take the following structure: - - **Recommendation Cluster:** A UI view that contains a group of - recommendations from the same developer partner. + - **Recommendation Cluster:** A UI view that contains a group of recommendations from the same developer partner. ![](https://developer.android.com/static/images/guide/playcore/engage/watch-term-1.png) **Figure 1.** Entertainment Space UI showing a Recommendation Cluster from a single partner. - - **Entity:** An object representing a single item in a cluster. An entity - can be a movie, a TV show, a TV series, live video, and more. See the - [Provide entity data](https://developer.android.com/guide/playcore/engage/watch#provide-entity-data) section for a list of - supported entity types. + - **Entity:** An object representing a single item in a cluster. An entity can be a movie, a TV show, a TV series, live video, and more. See the [Provide entity data](https://developer.android.com/guide/playcore/engage/watch#provide-entity-data) section for a list of supported entity types. ![](https://developer.android.com/static/images/guide/playcore/engage/watch-term-2.png) **Figure 2.** Entertainment Space UI showing a single Entity within a single partner's Recommendation Cluster. -- The **Continuation** cluster shows unfinished videos and relevant newly - released episodes from multiple developer partners in one UI grouping. Each - developer partner will be allowed to broadcast a maximum of 10 entities in the - Continuation cluster. Research has shown that personalized recommendations - along with personalized Continuation content creates the best user engagement. +- The **Continuation** cluster shows unfinished videos and relevant newly released episodes from multiple developer partners in one UI grouping. Each developer partner will be allowed to broadcast a maximum of 10 entities in the Continuation cluster. Research has shown that personalized recommendations along with personalized Continuation content creates the best user engagement. ![](https://developer.android.com/static/images/guide/playcore/engage/watch-term-3.png) **Figure 3.** Entertainment Space UI showing a Continuation cluster with unfinished recommendations from multiple partners (only one recommendation is currently visible). -- The **Featured** cluster showcases a selection of entities from multiple - developer partners in one UI grouping. There will be a single Featured - cluster, which is surfaced near the top of the UI with a priority placement - above all Recommendation clusters. Each developer partner will be allowed to - broadcast up to 10 entities in the Featured cluster. +- The **Featured** cluster showcases a selection of entities from multiple developer partners in one UI grouping. There will be a single Featured cluster, which is surfaced near the top of the UI with a priority placement above all Recommendation clusters. Each developer partner will be allowed to broadcast up to 10 entities in the Featured cluster. ![](https://developer.android.com/static/images/guide/playcore/engage/watch-term-4.png) **Figure 4.** Entertainment Space UI showing a Featured cluster with recommendations from multiple partners (only one recommendation is currently visible). @@ -64,16 +41,13 @@ Add the `com.google.android.engage:engage-core` library to your app: implementation 'com.google.android.engage:engage-core:1.6.0' } -For more information, see [Package visibility in Android -11](https://developer.android.com/about/versions/11/privacy/package-visibility). +For more information, see [Package visibility in Android 11](https://developer.android.com/about/versions/11/privacy/package-visibility). ### Summary -The design is based on an implementation of a [bound -service](https://developer.android.com/guide/components/bound-services). +The design is based on an implementation of a [bound service](https://developer.android.com/guide/components/bound-services). -The data a client can publish is subject to the following limits for different -cluster types: +The data a client can publish is subject to the following limits for different cluster types: | Cluster type | Cluster limits | Maximum entity limits in a cluster | |---|---|---| @@ -82,16 +56,13 @@ cluster types: | Featured Cluster | At most 1 | At most 20 | > [!IMPORTANT] -> **Important:** Engage SDK has superseded Media Home, which is now deprecated. If you have an existing Media Home integration, follow the instructions in [Step -> 0](https://developer.android.com/guide/playcore/engage/watch#migration) to migrate your content to Engage SDK, which allows your content to be published to more devices and form factors. Contact [`engage-developers@google.com`](mailto:engage-developers@google.com). If you don't have an existing Media Home integration, skip to [Step -> 1](https://developer.android.com/guide/playcore/engage/watch#provide-entity-data). +> **Important:** Engage SDK has superseded Media Home, which is now deprecated. If you have an existing Media Home integration, follow the instructions in [Step 0](https://developer.android.com/guide/playcore/engage/watch#migration) to migrate your content to Engage SDK, which allows your content to be published to more devices and form factors. Contact [`engage-developers@google.com`](mailto:engage-developers@google.com). If you don't have an existing Media Home integration, skip to [Step 1](https://developer.android.com/guide/playcore/engage/watch#provide-entity-data). ### Step 0: Migration from existing Media Home SDK integration #### Map data models from existing integration -If you are migrating from an existing Media Home integration, the following -table outlines how to map data models in existing SDKs to the new Engage SDK: +If you are migrating from an existing Media Home integration, the following table outlines how to map data models in existing SDKs to the new Engage SDK: | MediaHomeVideoContract integration equivalent | Engage SDK integration equivalent | |---|---| @@ -123,9 +94,7 @@ With Media Home SDK, clusters and entities were published through separate APIs: // 5. publish new programs in the channel PreviewChannelHelper.publishPreviewProgram(builder.build()); -With Engage SDK, cluster and entity publishing are combined into a single API -call. All entities that belong to a cluster are published together with that -cluster: +With Engage SDK, cluster and entity publishing are combined into a single API call. All entities that belong to a cluster are published together with that cluster: ### Kotlin @@ -147,8 +116,7 @@ cluster: ### Step 1: Provide entity data -The SDK has defined different entities to represent each item type. We support -the following entities for the Watch category: +The SDK has defined different entities to represent each item type. We support the following entities for the Watch category: 1. [`MovieEntity`](https://developer.android.com/guide/playcore/engage/watch#movieentity) 2. [`TvShowEntity`](https://developer.android.com/guide/playcore/engage/watch#tvshowentity) @@ -262,8 +230,7 @@ The following chart outlines attributes and requirements for each type. #### `VideoClipEntity` -The `VideoClipEntity` object represents a video entity coming from social media, -such as TikTok or YouTube. +The `VideoClipEntity` object represents a video entity coming from social media, such as TikTok or YouTube. | Attribute | Requirement | Notes | |---|---|---| @@ -344,13 +311,9 @@ PNG, JPG, static GIF, WebP ### Step 2: Provide Cluster data -It's recommended to have the content publish job executed in the background -(for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) -and scheduled on a regular basis or on an event basis (for example, every time -the user opens the app or when the user just added something to their cart). +It's recommended to have the content publish job executed in the background (for example, using [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager)) and scheduled on a regular basis or on an event basis (for example, every time the user opens the app or when the user just added something to their cart). -`AppEngagePublishClient` is responsible for publishing clusters. Following -APIs are available in the client: +`AppEngagePublishClient` is responsible for publishing clusters. Following APIs are available in the client: - `isServiceAvailable` - `publishRecommendationClusters` @@ -366,16 +329,29 @@ APIs are available in the client: #### `isServiceAvailable` -This API is used to check if the service is available for integration and -whether the content can be presented on the device. +This API is used to check if the service is available for integration and whether the content can be presented on the device. ##### For Engage SDK v1.6.0 and higher (Recommended) -You can check the service availability for every cluster type that you intend to -publish. The `isServiceAvailable` API accepts a request object, -`ServiceAvailabilityRequest`, which contains the cluster types for which service -availability needs to be checked. You can find the `ClusterType` enum values -required for `ServiceAvailabilityRequest` from the following table. +
+ +## Android skills + +[View on GitHub](https://github.com/android/skills/tree/main/play/engage-sdk-integration) + +### Engage SDK integration + +To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run: + + android skills add --skill engage-sdk-integration + +If your team uses AI coding tools (such as Gemini in Android Studio), you can automate this migration by prompting your AI assistant: + + Use the engage-sdk-integration skill to use Engage SDK 1.6.0 and refactor isServiceAvailable to pass ServiceAvailabilityRequest for publishing all cluster types. + +
+ +You can check the service availability for every cluster type that you intend to publish. The `isServiceAvailable` API accepts a request object, `ServiceAvailabilityRequest`, which contains the cluster types for which service availability needs to be checked. You can find the `ClusterType` enum values required for `ServiceAvailabilityRequest` from the following table. | Cluster Type | Cluster Type Constant | Integer Value | |---|---|---| @@ -433,25 +409,11 @@ required for `ServiceAvailabilityRequest` from the following table. ###### Conditional Service Availability Feature -Some integrated apps request a special configuration that enables and disables -the Engage service intermittently in order to reduce their serving cost. This -intermittent content ingestion strategy, although possible, negatively affects -the user and the product -- stale content will not be presented and some surfaces -will not be served at all. +Some integrated apps request a special configuration that enables and disables the Engage service intermittently in order to reduce their serving cost. This intermittent content ingestion strategy, although possible, negatively affects the user and the product -- stale content will not be presented and some surfaces will not be served at all. -Starting with v1.6.0, the Engage SDK allows checking availability for specific -cluster types. This provides more flexibility so that if the intermittent -content strategy was adopted by a given application, some cluster types can -follow that intermittent strategy while other cluster types are always enabled -(i.e. continuation clusters). +Starting with v1.6.0, the Engage SDK allows checking availability for specific cluster types. This provides more flexibility so that if the intermittent content strategy was adopted by a given application, some cluster types can follow that intermittent strategy while other cluster types are always enabled (i.e. continuation clusters). -If the Engage service should not be 'continuously' enabled on all supported -devices for whatever reason, and is configured for intermittent ingestion for -any set of devices, all continuation cluster publications (e.g. Continue -Watching) will be still enabled by default configuration, and the rest of the -cluster types will be enabled and disabled intermittently. If intermittent -ingestion applies to you but this default configuration is not suitable for -your needs, please contact engage-developers@google.com. +If the Engage service should not be 'continuously' enabled on all supported devices for whatever reason, and is configured for intermittent ingestion for any set of devices, all continuation cluster publications (e.g. Continue Watching) will be still enabled by default configuration, and the rest of the cluster types will be enabled and disabled intermittently. If intermittent ingestion applies to you but this default configuration is not suitable for your needs, please contact engage-developers@google.com. ##### For SDK versions prior to v1.6.0 (Deprecated) @@ -525,14 +487,12 @@ This API is used to publish a list of `RecommendationCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `RecommendationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Recommendation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishFeaturedCluster` @@ -563,14 +523,12 @@ This API is used to publish a list of `FeaturedCluster` objects. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `FeaturedCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Featured Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishContinuationCluster` @@ -601,20 +559,16 @@ This API is used to publish a `ContinuationCluster` object. .build()) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `ContinuationCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated Continuation Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `publishUserAccountManagementRequest` -This API is used to publish a Sign In card . The signin action directs users to -the app's sign in page so that the app can publish content (or provide more -personalized content) +This API is used to publish a Sign In card . The signin action directs users to the app's sign in page so that the app can publish content (or provide more personalized content) The following metadata is part of the Sign In Card - @@ -667,21 +621,16 @@ The following metadata is part of the Sign In Card - .setSignInCardEntity(SIGN_IN_CARD_ENTITY) .build()); -When the service receives the request, the following actions take place within -one transaction: +When the service receives the request, the following actions take place within one transaction: - Existing `UserAccountManagementCluster` data from the developer partner is removed. - Data from the request is parsed and stored in the updated UserAccountManagementCluster Cluster. -In case of an error, the entire request is rejected and the existing state is -maintained. +In case of an error, the entire request is rejected and the existing state is maintained. #### `updatePublishStatus` -If for any internal business reason, none of the clusters is published, -we **strongly recommend** updating the publish status using the -**updatePublishStatus** API. -This is important because : +If for any internal business reason, none of the clusters is published, we **strongly recommend** updating the publish status using the **updatePublishStatus** API. This is important because : - Providing the status in all scenarios, even when the content is published (STATUS == PUBLISHED), is critical to populate dashboards that use this explicit status to convey the health and other metrics of your integration. - If no content is published but the integration status isn't broken (STATUS == NOT_PUBLISHED), Google can avoid triggering alerts in the app health dashboards. It confirms that content is not published due to an **expected** situation from the provider's standpoint. @@ -721,11 +670,7 @@ The list of eligible publish status codes are : // Reach out to engage-developers@ before using this enum. AppEngagePublishStatusCode.NOT_PUBLISHED_OTHER -If the content is not published due to a user not logged in, -Google would recommend publishing the Sign In Card. -If for any reason providers are not able to publish the Sign In Card -then we recommend calling the **updatePublishStatus** API -with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** +If the content is not published due to a user not logged in, Google would recommend publishing the Sign In Card. If for any reason providers are not able to publish the Sign In Card then we recommend calling the **updatePublishStatus** API with the status code **NOT_PUBLISHED_REQUIRES_SIGN_IN** ### Kotlin @@ -756,9 +701,7 @@ This API is used to delete the content of Recommendation Clusters. client.deleteRecommendationClusters(); -When the service receives the request, it removes the existing data from the -Recommendation Clusters. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Recommendation Clusters. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -778,9 +721,7 @@ This API is used to delete the content of Featured Cluster. client.deleteFeaturedCluster(); -When the service receives the request, it removes the existing data from the -Featured Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Featured Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -800,9 +741,7 @@ This API is used to delete the content of Continuation Cluster. client.deleteContinuationCluster(); -When the service receives the request, it removes the existing data from the -Continuation Cluster. In case of an error, the entire request is rejected -and the existing state is maintained. +When the service receives the request, it removes the existing data from the Continuation Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -822,9 +761,7 @@ This API is used to delete the content of UserAccountManagement Cluster. client.deleteUserManagementCluster(); -When the service receives the request, it removes the existing data from the -UserAccountManagement Cluster. In case of an error, the entire request is -rejected and the existing state is maintained. +When the service receives the request, it removes the existing data from the UserAccountManagement Cluster. In case of an error, the entire request is rejected and the existing state is maintained. > [!NOTE] > **Note:** This api is available from version 1.1.0 onwards. @@ -854,15 +791,11 @@ This API is used to delete the content of a given cluster type. .addClusterType(ClusterType.TYPE_RECOMMENDATION) .build()); -When the service receives the request, it removes the existing data from all -clusters matching the specified cluster types. Clients can choose to pass one or -many cluster types. In case of an error, the entire request is rejected and the -existing state is maintained. +When the service receives the request, it removes the existing data from all clusters matching the specified cluster types. Clients can choose to pass one or many cluster types. In case of an error, the entire request is rejected and the existing state is maintained. #### Error handling -It is highly recommended to listen to the task result from the publish APIs such -that a follow-up action can be taken to recover and resubmit an successful task. +It is highly recommended to listen to the task result from the publish APIs such that a follow-up action can be taken to recover and resubmit an successful task. ### Kotlin @@ -906,8 +839,7 @@ that a follow-up action can be taken to recover and resubmit an successful task. } }); -The error is returned as an `AppEngageException` with the cause included as an -error code. +The error is returned as an `AppEngageException` with the cause included as an error code. | Error code | Error name | Note | |---|---|---| @@ -921,23 +853,13 @@ error code. ### Step 3: Handle broadcast intents -In addition to making publish content API calls through a job, it is also -required to set up a -[`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive -the request for a content publish. +In addition to making publish content API calls through a job, it is also required to set up a [`BroadcastReceiver`](https://developer.android.com/reference/android/content/BroadcastReceiver) to receive the request for a content publish. -The goal of broadcast intents is mainly for app reactivation and forcing data -sync. Broadcast intents are not designed to be sent very frequently. It is only -triggered when the Engage Service determines the content might be stale (for -example, a week old). That way, there is more confidence that the user can have -a fresh content experience, even if the application has not been executed for a -long period of time. +The goal of broadcast intents is mainly for app reactivation and forcing data sync. Broadcast intents are not designed to be sent very frequently. It is only triggered when the Engage Service determines the content might be stale (for example, a week old). That way, there is more confidence that the user can have a fresh content experience, even if the application has not been executed for a long period of time. The `BroadcastReceiver` must be set up in the following two ways: -- Dynamically register an instance of the `BroadcastReceiver` class using - `Context.registerReceiver()`. This enables communication from applications - that are still live in memory. +- Dynamically register an instance of the `BroadcastReceiver` class using `Context.registerReceiver()`. This enables communication from applications that are still live in memory. ### Kotlin @@ -1008,10 +930,7 @@ The `BroadcastReceiver` must be set up in the following two ways: } -- Statically declare an implementation with the `` tag in your - `AndroidManifest.xml` file. This allows the application to receive broadcast - intents when it is not running, and also allows the application to publish - the content. +- Statically declare an implementation with the `` tag in your `AndroidManifest.xml` file. This allows the application to receive broadcast intents when it is not running, and also allows the application to publish the content. -The following [intents](https://developer.android.com/reference/android/content/Intent) is sent by the -service: +The following [intents](https://developer.android.com/reference/android/content/Intent) is sent by the service: - `com.google.android.engage.action.PUBLISH_RECOMMENDATION` It is recommended to start a `publishRecommendationClusters` call when receiving this intent. - `com.google.android.engage.action.PUBLISH_FEATURED` It is recommended to start a `publishFeaturedCluster` call when receiving this intent. @@ -1040,19 +958,15 @@ service: ## Integration workflow -For a step-by-step guide on verifying your integration after it is complete, see -[Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). +For a step-by-step guide on verifying your integration after it is complete, see [Engage developer integration workflow](https://developer.android.com/guide/playcore/engage/workflow). ## FAQs -See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for -FAQs. +See [Engage SDK Frequently Asked Questions](https://developer.android.com/guide/playcore/engage/faq) for FAQs. ## Contact -Contact -[`engage-developers@google.com`](mailto:engage-developers@google.com) if there are -any questions during the integration process. +Contact [`engage-developers@google.com`](mailto:engage-developers@google.com) if there are any questions during the integration process. ## Next steps diff --git a/play/engage-sdk-integration/references/patterns.md b/play/engage-sdk-integration/references/patterns.md index 099c410..76d8adc 100644 --- a/play/engage-sdk-integration/references/patterns.md +++ b/play/engage-sdk-integration/references/patterns.md @@ -1,12 +1,10 @@ ## EngageBroadcastReceiver -Setting up the `BroadcastReceiver` correctly requires **both** static and -dynamic registration. Static registration allows the app to receive broadcasts -even when it isn't running, while dynamic registration is required on newer -Android versions to safely receive broadcasts when the app is live in memory. +Setting up the `BroadcastReceiver` correctly requires **both** static and dynamic registration. Static registration allows the app to receive broadcasts even when it isn't running, while dynamic registration is required on newer Android versions to safely receive broadcasts when the app is live in memory. ### BroadcastReceiver implementation +
```kotlin import android.content.BroadcastReceiver @@ -65,15 +63,16 @@ class EngageBroadcastReceiver : BroadcastReceiver() { } } } + ```
### Static registration in AndroidManifest.xml -Add the `` tag inside the `` block in -`AndroidManifest.xml` +Add the `` tag inside the `` block in `AndroidManifest.xml` +
```xml @@ -90,12 +89,14 @@ Add the `` tag inside the `` block in + ```
## EngageWorker +
```kotlin import android.content.Context @@ -294,12 +295,14 @@ class EngageWorker(context: Context, workerParams: WorkerParameters) : Coroutine } } } + ```
## ClusterRequestFactory +
```kotlin class ClusterRequestFactory(context: Context) { @@ -353,12 +356,14 @@ class ClusterRequestFactory(context: Context) { .setSignInCardEntity(signInCard) .build() } + ```
## EngagePublisher +
```kotlin object EngagePublisher { @@ -378,12 +383,14 @@ object EngagePublisher { WorkManager.getInstance(context).enqueueUniqueWork("EngageOneTime", ExistingWorkPolicy.REPLACE, workRequest) } } + ```
## Constants +
```kotlin object Constants { @@ -399,12 +406,14 @@ object Constants { // const val PUBLISH_TYPE_FOOD_SHOPPING_CARD = "FOOD_SHOPPING_CARD" // const val PUBLISH_TYPE_RESERVATION = "RESERVATION" } + ```
## ItemToEntityConverter +
```kotlin object ItemToEntityConverter { @@ -419,22 +428,16 @@ object ItemToEntityConverter { .build() } } + ```
-> **Strict image aspect ratio requirement** : Play Engage has strict -> requirements for image aspect ratios depending on the vertical and entity type -> (e.g., 16:9 for landscape, 1:1 for square, 2:3 for portrait). Ensure your -> `ItemToEntityConverter` maps images that conform to these strict requirements -> to avoid cropping or content rejection by Play. +> **Strict image aspect ratio requirement** : Play Engage has strict requirements for image aspect ratios depending on the vertical and entity type (e.g., 16:9 for landscape, 1:1 for square, 2:3 for portrait). Ensure your `ItemToEntityConverter` maps images that conform to these strict requirements to avoid cropping or content rejection by Play. ## Dependency specifications (libs.versions.toml) -This skill specifies all dependencies using the `libs.versions.toml` format. -Adapt these definitions to other formats (such as standard Groovy `build.gradle` -or Kotlin DSL `build.gradle.kts` implementation lines) as required by the -project. +This skill specifies all dependencies using the `libs.versions.toml` format. Adapt these definitions to other formats (such as standard Groovy `build.gradle` or Kotlin DSL `build.gradle.kts` implementation lines) as required by the project. [versions] engage-core = "1.6.0" @@ -455,10 +458,9 @@ project. ## Dual content rating fields for Watch and TV -For Watch and TV integrations, you must populate both the new `contentRatings` -(which uses `RatingSystem`) and the legacy `contentRatingsLegacies` (which uses -`String` lists) to ensure compatibility across all Google Play surfaces. +For Watch and TV integrations, you must populate both the new `contentRatings` (which uses `RatingSystem`) and the legacy `contentRatingsLegacies` (which uses `String` lists) to ensure compatibility across all Google Play surfaces. +
```kotlin fun convertMovie(movie: MovieData): MovieEntity { @@ -474,27 +476,30 @@ fun convertMovie(movie: MovieData): MovieEntity { .addContentRatingsLegacy(listOf("MPAA:PG-13")) // Legacy API for backward compatibility .build() } + ```
## TV integrations -The following patterns and configurations are specific to Android TV -integrations. +The following patterns and configurations are specific to Android TV integrations. ### AndroidManifest.xml for TV +
```xml + ```
### PlatformSpecificUri example +
```kotlin val platformSpecificPlaybackUris = listOf( @@ -507,12 +512,14 @@ val platformSpecificPlaybackUris = listOf( .setActionUri(Uri.parse("https://www.example.com/mobile/play/123")) .build() ) + ```
### AccountProfile example +
```kotlin val accountProfile: AccountProfile @@ -522,6 +529,7 @@ val accountProfile: AccountProfile // AppCompatDelegate.getApplicationLocales().get(0) for Per-App Language Preferences .setLocale(Locale.getDefault().toLanguageTag()) .build() + ```
\ No newline at end of file diff --git a/play/engage-sdk-integration/references/requests.md b/play/engage-sdk-integration/references/requests.md index 00849e6..f841032 100644 --- a/play/engage-sdk-integration/references/requests.md +++ b/play/engage-sdk-integration/references/requests.md @@ -1,5 +1,4 @@ -Defines the request structures for publishing various data models in -the Engage SDK. +Defines the request structures for publishing various data models in the Engage SDK. { "PublishRecommendationClustersRequest": { diff --git a/play/play-billing-library-version-upgrade/SKILL.md b/play/play-billing-library-version-upgrade/SKILL.md index 6784606..8c96d85 100644 --- a/play/play-billing-library-version-upgrade/SKILL.md +++ b/play/play-billing-library-version-upgrade/SKILL.md @@ -6,7 +6,7 @@ description: Use this skill when upgrading or migrating an Android project from license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-07-02' + last-updated: '2026-08-06' keywords: - android - play billing @@ -20,8 +20,7 @@ metadata: ## Phase 0: Intent Message -**Reporting Action**: Before proceeding, immediately tell the user: "I will -upgrade Play Billing Library to the latest version." +**Reporting Action**: Before proceeding, immediately tell the user: "I will upgrade Play Billing Library to the latest version." ## Phase 1: Discovery \& Situational Awareness @@ -29,22 +28,18 @@ upgrade Play Billing Library to the latest version." 2. **Initial Compilation Test**: Attempt to sync and build the project immediately. 3. **Fallback Discovery (Effective Version)** : - **Trigger**: Only if the build fails immediately, scan the source code for deprecated artifacts. - - **Logic** : The presence of deprecated APIs indicates the **"Effective - Version"** ---defined as the version where those specific APIs were **last - available**, not when they were introduced. + - **Logic** : The presence of deprecated APIs indicates the **"Effective Version"** ---defined as the version where those specific APIs were **last available**, not when they were introduced. - **Example** : If `SkuDetails` is present, treat the baseline as **PBL v7** or earlier (regardless of the version string in `build.gradle`). 4. **Identify Target \& Path** : Access the version tool or release notes to find the latest stable version and calculate a \[Direct/Stepped\] migration path based on the **Effective Version** baseline. - **Calculate Migration Path** : - If the **Effective Version** is within 2 major versions of the target: Plan a **Direct Migration**. - - If it is more than 2 major versions behind: Plan a **Stepped - Migration**. Migrate by two major versions at a time (e.g., v4 -\> v6 -\> v8) until you are within two versions of the target. + - If it is more than 2 major versions behind: Plan a **Stepped Migration**. Migrate by two major versions at a time (e.g., v4 -\> v6 -\> v8) until you are within two versions of the target. - **Reporting Action**: Before proceeding, tell the user: "I've detected you are effectively on PBL \[Current\] and the latest is \[Target\]. I am planning a \[direct/stepped\] migration path." ## Phase 2: Contextual Document Mapping \& Planning -For every major version jump identified in your path, you **MUST** synthesize -instructions from: +For every major version jump identified in your path, you **MUST** synthesize instructions from: - **[Migration Guide](https://developer.android.com/google/play/billing/migrate-gpblv%5BX%5D)** (where `[X]` is the target major version). - **Release Highlights** : The "Deprecations" and "Breaking Changes" sections of the relevant [Release Notes](references/android/google/play/billing/release-notes.md). @@ -53,9 +48,7 @@ instructions from: ## Phase 3: Instructions for Execution -*Reporting Action: For each of the following steps, give a brief explanation of -what you will be doing prior to execution, and a brief summary of what you -accomplished afterwards.* +*Reporting Action: For each of the following steps, give a brief explanation of what you will be doing prior to execution, and a brief summary of what you accomplished afterwards.* ### Step 1: SDK \& Environment Alignment @@ -64,8 +57,7 @@ accomplished afterwards.* ### Step 2: Intent-based Refactoring -Analyze the intent of the existing code rather than performing purely textual -string replacement. +Analyze the intent of the existing code rather than performing purely textual string replacement. - **Action** : You **MUST** follow all deprecation instructions and refactor patterns from **both** the [references/migration-logic.md](references/migration-logic.md) section, the official migration guides, and the general documentation pages identified in Phase 2. - **Verification** : Verify you are doing **all steps from all documentation** and then making sure you follow the specific directions from the checklist in the references. diff --git a/play/play-billing-library-version-upgrade/references/android/google/play/billing/release-notes.md b/play/play-billing-library-version-upgrade/references/android/google/play/billing/release-notes.md index 462f373..1d1105c 100644 --- a/play/play-billing-library-version-upgrade/references/android/google/play/billing/release-notes.md +++ b/play/play-billing-library-version-upgrade/references/android/google/play/billing/release-notes.md @@ -23,37 +23,21 @@ Version 9.1.0 of the Google Play Billing Library and Kotlin extensions are now a ## Google Play Billing Library 9.0.0 Release (2026-05-19) -Version 9.0.0 of the Google Play Billing Library and Kotlin extensions are -now available. See the [PBL 9 migration guide](https://developer.android.com/google/play/billing/migrate-pbl-latest) if you want to migrate from -the previous versions of PBL. +Version 9.0.0 of the Google Play Billing Library and Kotlin extensions are now available. See the [PBL 9 migration guide](https://developer.android.com/google/play/billing/migrate-pbl-latest) if you want to migrate from the previous versions of PBL. ### Summary of changes -- **Updated error codes for blocked Play Store activity** : Error codes for - blocked Play Store apps have been updated. For instances where - the Play Store app is blocked by the system - (for example, in OEM-customized kids mode), the response code has - changed from `ERROR` to `BILLING_UNAVAILABLE`. Additionally, the - `BillingResult` for such cases now provides a *Play Store is blocked* - debug message. +- **Updated error codes for blocked Play Store activity** : Error codes for blocked Play Store apps have been updated. For instances where the Play Store app is blocked by the system (for example, in OEM-customized kids mode), the response code has changed from `ERROR` to `BILLING_UNAVAILABLE`. Additionally, the `BillingResult` for such cases now provides a *Play Store is blocked* debug message. > [!NOTE] > **Note:** For this feature to work, you need [AndroidX.core library](https://developer.android.com/jetpack/androidx/releases/core#core_and_core-ktx_version_190_2) version 1.9 or later. -- **Nullability update for developer-provided billing** : The - [`DeveloperProvidedBillingDetails.getLinkUri()`](https://developer.android.com/reference/com/android/billingclient/api/DeveloperProvidedBillingDetails#getLinkUri()) method has - been updated to be `@Nullable`. This change supports scenarios where - the direct link URI for external payments is unavailable during the - payment selection stage. +- **Nullability update for developer-provided billing** : The [`DeveloperProvidedBillingDetails.getLinkUri()`](https://developer.android.com/reference/com/android/billingclient/api/DeveloperProvidedBillingDetails#getLinkUri()) method has been updated to be `@Nullable`. This change supports scenarios where the direct link URI for external payments is unavailable during the payment selection stage. - To handle this change safely, ensure your integration code handles both - `null` and empty string (`""`) values from the - [`DeveloperProvidedBillingDetails.getLinkUri()`](https://developer.android.com/reference/com/android/billingclient/api/DeveloperProvidedBillingDetails#getLinkUri()) method before parsing - or launching browser intents. + To handle this change safely, ensure your integration code handles both `null` and empty string (`""`) values from the [`DeveloperProvidedBillingDetails.getLinkUri()`](https://developer.android.com/reference/com/android/billingclient/api/DeveloperProvidedBillingDetails#getLinkUri()) method before parsing or launching browser intents. - Updated `targetSdkVersion` to 35. -- You can now use [in-app messaging](https://developer.android.com/google/play/billing/subscriptions#in-app-messaging) to notify users - of an upcoming opt-in price increase. This lets users confirm the price increase without leaving the app. The message for an outstanding opt-in price increase is shown starting on the first day the user can accept the price increase, and the message is shown a maximum of once every 7 days. +- You can now use [in-app messaging](https://developer.android.com/google/play/billing/subscriptions#in-app-messaging) to notify users of an upcoming opt-in price increase. This lets users confirm the price increase without leaving the app. The message for an outstanding opt-in price increase is shown starting on the first day the user can accept the price increase, and the message is shown a maximum of once every 7 days. ## Google Play Billing Library 8.3.0 Release (2025-12-23) @@ -74,8 +58,7 @@ Version 8.3.0 of the Google Play Billing Library and Kotlin extensions are now a ## Google Play Billing Library 8.2.1 Release (2025-12-15) -Version 8.2.1 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 8.2.1 of the Google Play Billing Library and Kotlin extensions are now available. ### Bug fixes @@ -109,46 +92,29 @@ Version 8.1.0 of the Google Play Billing Library and Kotlin extensions are now a - Suspended subscriptions - A new parameter has been added to the - [`BillingClient.queryPurchasesAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(com.android.billingclient.api.QueryPurchasesParams,com.android.billingclient.api.PurchasesResponseListener)) - method to include suspended subscriptions when querying for subscriptions. - Suspended subscriptions are still attributed to the user, but are not active, - either because the user paused the subscription or their renewal payment method - was declined. + A new parameter has been added to the [`BillingClient.queryPurchasesAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(com.android.billingclient.api.QueryPurchasesParams,com.android.billingclient.api.PurchasesResponseListener)) method to include suspended subscriptions when querying for subscriptions. Suspended subscriptions are still attributed to the user, but are not active, either because the user paused the subscription or their renewal payment method was declined. - The [`Purchase`](https://developer.android.com/reference/com/android/billingclient/api/Purchase) object returned in the listener will return `isSuspended() = true` - for any suspended subscriptions. In this case, you shouldn't grant access - to the purchased subscription, and instead guide the user to the - [subscriptions center](https://play.google.com/store/account/subscriptions) - where the user can manage their payment methods - or pause state to re-activate their subscription. + The [`Purchase`](https://developer.android.com/reference/com/android/billingclient/api/Purchase) object returned in the listener will return `isSuspended() = true` for any suspended subscriptions. In this case, you shouldn't grant access to the purchased subscription, and instead guide the user to the [subscriptions center](https://play.google.com/store/account/subscriptions) where the user can manage their payment methods or pause state to re-activate their subscription. - Updates to [subscriptions](https://developer.android.com/google/play/billing/subscriptions): - - The [`BillingFlowParams.ProductDetailsParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProductDetailsParams) - object now has the `setSubscriptionProductReplacementParams()` method - in which you can specify product level replacement information. + - The [`BillingFlowParams.ProductDetailsParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProductDetailsParams) object now has the `setSubscriptionProductReplacementParams()` method in which you can specify product level replacement information. - - The `SubscriptionProductReplacementParams` object has - two setter methods: + - The `SubscriptionProductReplacementParams` object has two setter methods: - `setOldProductId`: The old product that needs to be replaced by the product in current [`ProductDetails`](https://developer.android.com/reference/com/android/billingclient/api/ProductDetails). - `setReplacementMode`: This is the item level replacement mode. The modes are essentially the same as SubscriptionUpdateParams, but the value mapping has been updated. A new replacement mode `KEEP_EXISTING` is introduced that lets you keep the existing payment schedule unchanged for an item. - - [SubscriptionUpdateParams setSubscriptionReplacementMode](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setSubscriptionReplacementMode(int)) will be - deprecated. You should use `SubscriptionProductReplacementParams.setReplacementMode` - instead. + - [SubscriptionUpdateParams setSubscriptionReplacementMode](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setSubscriptionReplacementMode(int)) will be deprecated. You should use `SubscriptionProductReplacementParams.setReplacementMode` instead. - Updated `minSdkVersion` to 23. - Enabled [pre-order APIs for one-time products](https://developer.android.com/google/play/billing/one-time-product-multi-purchase-options-offers#pre-order) - The `ProductDetails.oneTimePurchaseOfferDetails.getPreorderDetails()` API - that gets the pre-order details is now available for use. + The `ProductDetails.oneTimePurchaseOfferDetails.getPreorderDetails()` API that gets the pre-order details is now available for use. - Google Play Billing Library now supports [Kotlin version 2.2.0](https://kotlinlang.org/docs/whatsnew22.html). ## Google Play Billing Library 8.0.0 Release (2025-06-30) -Version 8.0.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 8.0.0 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes @@ -156,137 +122,87 @@ available. - Multiple purchase options and offers for one-time products. - You can now have multiple purchase options and offers for your one-time - products. This provides you flexibility in how you sell your products and - reduces the complexity of managing them. + You can now have multiple purchase options and offers for your one-time products. This provides you flexibility in how you sell your products and reduces the complexity of managing them. - Improved the [`queryProductDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryProductDetailsAsync(com.android.billingclient.api.QueryProductDetailsParams,com.android.billingclient.api.ProductDetailsResponseListener)) method. - Prior to PBL 8.0.0, the [`queryProductDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryProductDetailsAsync(com.android.billingclient.api.QueryProductDetailsParams,com.android.billingclient.api.ProductDetailsResponseListener)) method didn't - return products that couldn't be fetched. This could be due to reasons such - as the product is not found or no offers are available to the user. With PBL - 8.0.0, unfetched products are returned with a new product-level status code - that provides information about unfetched products. Note that there is a - change in the signature of the - [`ProductDetailsResponseListener.onProductDetailsResponse()`](https://developer.android.com/google/play/billing/integrate#automatic-service-reconnection) which - requires changes in your app. For more information, see [process the - result](https://developer.android.com/google/play/billing/integrate#process-the-result). + Prior to PBL 8.0.0, the [`queryProductDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryProductDetailsAsync(com.android.billingclient.api.QueryProductDetailsParams,com.android.billingclient.api.ProductDetailsResponseListener)) method didn't return products that couldn't be fetched. This could be due to reasons such as the product is not found or no offers are available to the user. With PBL 8.0.0, unfetched products are returned with a new product-level status code that provides information about unfetched products. Note that there is a change in the signature of the [`ProductDetailsResponseListener.onProductDetailsResponse()`](https://developer.android.com/google/play/billing/integrate#automatic-service-reconnection) which requires changes in your app. For more information, see [process the result](https://developer.android.com/google/play/billing/integrate#process-the-result). - Automatic service reconnection. - The new `BillingClient.Builder.enableAutoServiceReconnection()` builder - parameter lets developers opt-in to automatic service reconnection, which - simplifies connection management by handling reconnections to - the Play Billing Service automatically and eliminating the need to manually - call `startConnection()` in the event of a service disconnection. - For more information, see [Automatically Re-establish a Connection](https://developer.android.com/google/play/billing/integrate#automatic-service-reconnection). + The new `BillingClient.Builder.enableAutoServiceReconnection()` builder parameter lets developers opt-in to automatic service reconnection, which simplifies connection management by handling reconnections to the Play Billing Service automatically and eliminating the need to manually call `startConnection()` in the event of a service disconnection. For more information, see [Automatically Re-establish a Connection](https://developer.android.com/google/play/billing/integrate#automatic-service-reconnection). - Sub-response codes for the [`launchBillingFlow()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#launchBillingFlow(android.app.Activity,com.android.billingclient.api.BillingFlowParams)) method. - The [BillingResult](https://developer.android.com/reference/com/android/billingclient/api/BillingResult) returned from [`launchBillingFlow()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#launchBillingFlow(android.app.Activity,com.android.billingclient.api.BillingFlowParams)) will now - include a sub-response code field. This field will only be populated in some - cases to provide a more specific reason for the failure. The sub-response - field can have the following values: + The [BillingResult](https://developer.android.com/reference/com/android/billingclient/api/BillingResult) returned from [`launchBillingFlow()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#launchBillingFlow(android.app.Activity,com.android.billingclient.api.BillingFlowParams)) will now include a sub-response code field. This field will only be populated in some cases to provide a more specific reason for the failure. The sub-response field can have the following values: - `PAYMENT_DECLINED_DUE_TO_INSUFFICIENT_FUNDS` - Returned when the user's funds are less than the price of the item they are attempting to purchase. - `USER_INELIGIBLE` - Returned when the user doesn't meet the configured eligibility requirements for a subscription offer. - `NO_APPLICABLE_SUB_RESPONSE_CODE` - The default value, returned when no other sub-response code is applicable. - Removed the `queryPurchaseHistory()` method. - The `queryPurchaseHistory()` method that was previously marked as - deprecated has now been removed. See [Query Purchase History](https://developer.android.com/google/play/billing/query-purchase-history) for - details on what alternative APIs to use instead. + The `queryPurchaseHistory()` method that was previously marked as deprecated has now been removed. See [Query Purchase History](https://developer.android.com/google/play/billing/query-purchase-history) for details on what alternative APIs to use instead. - Removed the `querySkuDetailsAsync()` method. - The `querySkuDetailsAsync()` method that was previously marked as deprecated - has now been removed. You should use [queryProductDetailsAsync](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryProductDetailsAsync(com.android.billingclient.api.QueryProductDetailsParams,com.android.billingclient.api.ProductDetailsResponseListener)) instead. + The `querySkuDetailsAsync()` method that was previously marked as deprecated has now been removed. You should use [queryProductDetailsAsync](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryProductDetailsAsync(com.android.billingclient.api.QueryProductDetailsParams,com.android.billingclient.api.ProductDetailsResponseListener)) instead. - Removed the `BillingClient.Builder.enablePendingPurchases()` method. - The `enablePendingPurchases()` method with no parameters that was previously - marked as deprecated has now been removed. You should use - `enablePendingPurchases(PendingPurchaseParams params)` instead. Note that - the deprecated `enablePendingPurchases()` is functionally equivalent to - `enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())`. + The `enablePendingPurchases()` method with no parameters that was previously marked as deprecated has now been removed. You should use `enablePendingPurchases(PendingPurchaseParams params)` instead. Note that the deprecated `enablePendingPurchases()` is functionally equivalent to `enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())`. - Removed the overloaded `queryPurchasesAsync()` method that takes a [skuType](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.SkuType). - The `queryPurchasesAsync(String skuType, PurchasesResponseListener - listener)` method that was previously marked as - deprecated has now been removed. Alternately, use - [`queryPurchasesAsync(QueryPurchasesParams queryPurchasesParams, - PurchasesResponseListener listener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(com.android.billingclient.api.QueryPurchasesParams,com.android.billingclient.api.PurchasesResponseListener)). + The `queryPurchasesAsync(String skuType, PurchasesResponseListener listener)` method that was previously marked as deprecated has now been removed. Alternately, use [`queryPurchasesAsync(QueryPurchasesParams queryPurchasesParams, PurchasesResponseListener listener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(com.android.billingclient.api.QueryPurchasesParams,com.android.billingclient.api.PurchasesResponseListener)). ## Google Play Billing Library 7.1.1 Release (2024-10-03) -Version 7.1.1 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 7.1.1 of the Google Play Billing Library and Kotlin extensions are now available. ### Bug fixes -- Fixed a bug in Play Billing Library 7.1.0 related to [testing - `BillingResult` response codes](https://developer.android.com/google/play/billing/test-response-codes). +- Fixed a bug in Play Billing Library 7.1.0 related to [testing `BillingResult` response codes](https://developer.android.com/google/play/billing/test-response-codes). ## Google Play Billing Library 7.1.0 Release (2024-09-19) -Version 7.1.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 7.1.0 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes - Improved thread safety related to connection status and management. -- Introduced partial changes for testing [`BillingResult`](https://developer.android.com/reference/com/android/billingclient/api/BillingResult) response codes which is fully released in Play Billing Library 7.1.1. To test your integration using this feature, you'll need to upgrade to Play Billing Library 7.1.1. A bug exists that will only impact applications with [billing overrides testing enabled](https://developer.android.com/google/play/billing/test-response-codes#enable-billing-overrides-testing) and does not affect regular usage. For more information, see [Test `BillingResult` - response codes](https://developer.android.com/google/play/billing/test-response-codes). +- Introduced partial changes for testing [`BillingResult`](https://developer.android.com/reference/com/android/billingclient/api/BillingResult) response codes which is fully released in Play Billing Library 7.1.1. To test your integration using this feature, you'll need to upgrade to Play Billing Library 7.1.1. A bug exists that will only impact applications with [billing overrides testing enabled](https://developer.android.com/google/play/billing/test-response-codes#enable-billing-overrides-testing) and does not affect regular usage. For more information, see [Test `BillingResult` response codes](https://developer.android.com/google/play/billing/test-response-codes). ## Google Play Billing Library 7.0.0 Release (2024-05-14) -Version 7.0.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 7.0.0 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes - Added APIs to support installment subscriptions. - Added [`ProductDetails.InstallmentPlanDetails`](https://developer.android.com/reference/com/android/billingclient/api/ProductDetails.InstallmentPlanDetails) for installment base plans that users are eligible to purchase. This API helps your app identify the installment plan and its commitment setup to provide related information to the user. To learn more, see our [subscription installments guide](https://developer.android.com/google/play/billing/subscriptions#installments). -- Added [`PendingPurchasesParams`](https://developer.android.com/reference/com/android/billingclient/api/PendingPurchasesParams) and - [`BillingClient.Builder.enablePendingPurchases(PendingPurchaseParams)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enablePendingPurchases(PendingPurchaseParams)) - to replace - [`BillingClient.Builder.enablePendingPurchases()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enablePendingPurchases()), - which has been deprecated in this release. +- Added [`PendingPurchasesParams`](https://developer.android.com/reference/com/android/billingclient/api/PendingPurchasesParams) and [`BillingClient.Builder.enablePendingPurchases(PendingPurchaseParams)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enablePendingPurchases(PendingPurchaseParams)) to replace [`BillingClient.Builder.enablePendingPurchases()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enablePendingPurchases()), which has been deprecated in this release. - The deprecated `enablePendingPurchases()` is functionally equivalent to `enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())`. - Added APIs to support pending transactions for subscription prepaid plans: - - Use [`PendingPurchasesParams.Builder.enablePrepaidPlans()`](https://developer.android.com/reference/com/android/billingclient/api/PendingPurchasesParams.Builder#enablePrepaidPlans()) along with [`BillingClient.Builder.enablePendingPurchases(PendingPurchaseParams)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enablePendingPurchases(PendingPurchaseParams)) to enable pending transactions for subscription prepaid plans. When adding support, be sure that your app also correctly manages subscription lifecycles. To learn more see our [pending purchases - guide](https://developer.android.com/google/play/billing/subscriptions#pending). + - Use [`PendingPurchasesParams.Builder.enablePrepaidPlans()`](https://developer.android.com/reference/com/android/billingclient/api/PendingPurchasesParams.Builder#enablePrepaidPlans()) along with [`BillingClient.Builder.enablePendingPurchases(PendingPurchaseParams)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enablePendingPurchases(PendingPurchaseParams)) to enable pending transactions for subscription prepaid plans. When adding support, be sure that your app also correctly manages subscription lifecycles. To learn more see our [pending purchases guide](https://developer.android.com/google/play/billing/subscriptions#pending). - Added [`Purchase.PendingPurchaseUpdate`](https://developer.android.com/reference/com/android/billingclient/api/Purchase.PendingPurchaseUpdate) and [`Purchase.getPendingPurchaseUpdate()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase.getPendingPurchaseUpdate()) for retrieving the pending top-up or upgrade or downgrade to an existing subscription. -- Removed - [`BillingClient.Builder.enableAlternativeBilling()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enableAlternativeBilling(com.android.billingclient.api.AlternativeBillingListener)), - [`AlternativeBillingListener`](https://developer.android.com/reference/com/android/billingclient/api/AlternativeBillingListener), and - [`AlternativeChoiceDetails`](https://developer.android.com/reference/com/android/billingclient/api/AlternativeChoiceDetails). +- Removed [`BillingClient.Builder.enableAlternativeBilling()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enableAlternativeBilling(com.android.billingclient.api.AlternativeBillingListener)), [`AlternativeBillingListener`](https://developer.android.com/reference/com/android/billingclient/api/AlternativeBillingListener), and [`AlternativeChoiceDetails`](https://developer.android.com/reference/com/android/billingclient/api/AlternativeChoiceDetails). - Developers should use [`BillingClient.Builder.enableUserChoiceBilling()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enableUserChoiceBilling(com.android.billingclient.api.UserChoiceBillingListener)) with [`UserChoiceBillingListener`](https://developer.android.com/reference/com/android/billingclient/api/UserChoiceBillingListener) and [`UserChoiceDetails`](https://developer.android.com/reference/com/android/billingclient/api/UserChoiceDetails) in the listener callback instead. -- Removed [`BillingFlowParams.ProrationMode`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProrationMode), - [`BillingFlowParams.SubscriptionUpdateParams.Builder.setReplaceProrationMode()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setReplaceProrationMode(int)), - and - [`BillingFlowParams.SubscriptionUpdateParams.Builder.setReplaceSkusProrationMode()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setReplaceSkusProrationMode(int)). +- Removed [`BillingFlowParams.ProrationMode`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProrationMode), [`BillingFlowParams.SubscriptionUpdateParams.Builder.setReplaceProrationMode()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setReplaceProrationMode(int)), and [`BillingFlowParams.SubscriptionUpdateParams.Builder.setReplaceSkusProrationMode()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setReplaceSkusProrationMode(int)). - Developers should use [`BillingFlowParams.SubscriptionUpdateParams.ReplacementMode`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.ReplacementMode) with [`BillingFlowParams.SubscriptionUpdateParams.Builder#setSubscriptionReplacementMode(int)`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setSubscriptionReplacementMode(int)) instead. -- Removed - [`BillingFlowParams.SubscriptionUpdateParams.Builder#setOldSkuPurchaseToken()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setOldSkuPurchaseToken(java.lang.String)). +- Removed [`BillingFlowParams.SubscriptionUpdateParams.Builder#setOldSkuPurchaseToken()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setOldSkuPurchaseToken(java.lang.String)). - Developers should use [`BillingFlowParams.SubscriptionUpdateParams.Builder#setOldPurchaseToken(java.lang.String)`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setOldPurchaseToken(java.lang.String)) instead. -- [`BillingClient.queryPurchaseHistoryAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchaseHistoryAsync(com.android.billingclient.api.QueryPurchaseHistoryParams,com.android.billingclient.api.PurchaseHistoryResponseListener)) - has been deprecated and will be removed in a future release. Developers - should use the following alternatives instead: +- [`BillingClient.queryPurchaseHistoryAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchaseHistoryAsync(com.android.billingclient.api.QueryPurchaseHistoryParams,com.android.billingclient.api.PurchaseHistoryResponseListener)) has been deprecated and will be removed in a future release. Developers should use the following alternatives instead: - Acknowledged and pending purchases: Use [`BillingClient.queryPurchasesAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(com.android.billingclient.api.QueryPurchasesParams,%20com.android.billingclient.api.PurchasesResponseListener)) to fetch the active purchases. - Consumed purchases: Developers should keep track of consumed purchases on their own servers. - Canceled purchases: Use the [voided-purchases](https://developers.google.com/android-publisher/voided-purchases) developer API. - For more details, see [Query Purchase History](https://developer.android.com/google/play/billing/query-purchase-history) -- [`BillingFlowParams.ProductDetailsParams.setOfferToken()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProductDetailsParams.Builder#setOfferToken(java.lang.String)) - now throws an exception when developers specify an empty `offerToken`. +- [`BillingFlowParams.ProductDetailsParams.setOfferToken()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProductDetailsParams.Builder#setOfferToken(java.lang.String)) now throws an exception when developers specify an empty `offerToken`. - Updated `minSdkVersion` to 21 and `targetSdkVersion` to 34. ## Google Play Billing Library 6.2.1 Release (2024-04-16) -Version 6.2.1 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 6.2.1 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes @@ -294,8 +210,7 @@ available. ## Google Play Billing Library 6.2.0 Release (2024-03-06) -Version 6.2.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 6.2.0 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes @@ -307,8 +222,7 @@ available. ## Google Play Billing Library 6.1.0 Release (2023-11-14) -Version 6.1.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 6.1.0 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes @@ -325,8 +239,7 @@ available. ## Google Play Billing Library 6.0.1 Release (2023-06-22) -Version 6.0.1 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 6.0.1 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes @@ -334,65 +247,37 @@ Update Play Billing Library to be compatible with Android 14. ## Google Play Billing Library 6.0 Release (2023-05-10) -Version 6.0.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 6.0.0 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes -- Added new [`ReplacementMode`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.ReplacementMode) - enum to replace - [`ProrationMode`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProrationMode). +- Added new [`ReplacementMode`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.ReplacementMode) enum to replace [`ProrationMode`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProrationMode). - Note that `ProrationMode` is still available for backward compatibility - reasons. -- Removed order ID for [`PENDING`](https://developer.android.com/reference/com/android/billingclient/api/Purchase.PurchaseState#PENDING) - purchases. + Note that `ProrationMode` is still available for backward compatibility reasons. +- Removed order ID for [`PENDING`](https://developer.android.com/reference/com/android/billingclient/api/Purchase.PurchaseState#PENDING) purchases. - Previously, the order ID would always be created even if the purchase was - pending. Starting with version 6.0.0, an order ID will not be created for - pending purchases, and for these purchases, the order ID will be populated - after the purchase is moved to the - [`PURCHASED`](https://developer.android.com/reference/com/android/billingclient/api/Purchase.PurchaseState#PURCHASED) - state. + Previously, the order ID would always be created even if the purchase was pending. Starting with version 6.0.0, an order ID will not be created for pending purchases, and for these purchases, the order ID will be populated after the purchase is moved to the [`PURCHASED`](https://developer.android.com/reference/com/android/billingclient/api/Purchase.PurchaseState#PURCHASED) state. - Removed `queryPurchases` and `launchPriceConfirmationFlow` methods. - The `queryPurchases` and `launchPriceConfirmationFlow` methods that have - previously been marked as deprecated have now been removed in Play Billing - Library 6.0.0. Developers should use - [`queryPurchasesAsync`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(com.android.billingclient.api.QueryPurchasesParams,%20com.android.billingclient.api.PurchasesResponseListener)) - instead of `queryPurchases`. For `launchPriceConfirmationFlow` alternatives, - see [Price changes](https://developer.android.com/google/play/billing/price-changes). + The `queryPurchases` and `launchPriceConfirmationFlow` methods that have previously been marked as deprecated have now been removed in Play Billing Library 6.0.0. Developers should use [`queryPurchasesAsync`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(com.android.billingclient.api.QueryPurchasesParams,%20com.android.billingclient.api.PurchasesResponseListener)) instead of `queryPurchases`. For `launchPriceConfirmationFlow` alternatives, see [Price changes](https://developer.android.com/google/play/billing/price-changes). - Added new network error response code. - A new network error response code, - [`NETWORK_ERROR`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponseCode#NETWORK_ERROR), - has been added starting with PBL version 6.0.0. This code is returned when - an error occurs due to a network connection issue. These network connection - errors were previously reported as `SERVICE_UNAVAILABLE`. -- Updated [`SERVICE_UNAVAILABLE`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponseCode#SERVICE_UNAVAILABLE) - and - [`SERVICE_TIMEOUT`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponseCode#SERVICE_TIMEOUT). + A new network error response code, [`NETWORK_ERROR`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponseCode#NETWORK_ERROR), has been added starting with PBL version 6.0.0. This code is returned when an error occurs due to a network connection issue. These network connection errors were previously reported as `SERVICE_UNAVAILABLE`. +- Updated [`SERVICE_UNAVAILABLE`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponseCode#SERVICE_UNAVAILABLE) and [`SERVICE_TIMEOUT`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponseCode#SERVICE_TIMEOUT). - Starting with PBL version 6.0.0, errors due to timeout in processing will be - returned as `SERVICE_UNAVAILABLE` instead of the current `SERVICE_TIMEOUT`. + Starting with PBL version 6.0.0, errors due to timeout in processing will be returned as `SERVICE_UNAVAILABLE` instead of the current `SERVICE_TIMEOUT`. The behavior does not change in earlier versions of PBL. -- Removed - [`SERVICE_TIMEOUT`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponseCode#SERVICE_TIMEOUT). +- Removed [`SERVICE_TIMEOUT`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponseCode#SERVICE_TIMEOUT). - Starting with PBL version 6.0.0, `SERVICE_TIMEOUT` will no longer be - returned. Previous versions of PBL will still return this code. + Starting with PBL version 6.0.0, `SERVICE_TIMEOUT` will no longer be returned. Previous versions of PBL will still return this code. - Added additional logging. - The Play Billing Library 6 release includes additional logging, which - provides insight into API usage (such as success and failure) and service - connection issues. This information will be used to improve the performance - of the Play Billing Library and provide better support for errors. + The Play Billing Library 6 release includes additional logging, which provides insight into API usage (such as success and failure) and service connection issues. This information will be used to improve the performance of the Play Billing Library and provide better support for errors. ## Google Play Billing Library 5.2.1 Release (2023-06-22) -Version 5.2.1 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 5.2.1 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes @@ -400,8 +285,7 @@ Update Play Billing Library to be compatible with Android 14. ## Google Play Billing Library 5.2 Release (2023-04-06) -Version 5.2.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 5.2.0 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes @@ -414,8 +298,7 @@ available. ## Google Play Billing Library 5.1 Release (2022-10-31) -Version 5.1.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 5.1.0 of the Google Play Billing Library and Kotlin extensions are now available. This version contains the following changes. @@ -427,8 +310,7 @@ This version contains the following changes. ## Google Play Billing Library 5.0 Release (2022-05-11) -Version 5.0.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 5.0.0 of the Google Play Billing Library and Kotlin extensions are now available. This version contains the following changes. @@ -436,75 +318,46 @@ This version contains the following changes. - Introduced a new model for subscriptions, including new entities that enable you to create multiple offers for a single subscription product. For more information, see the [migration guide](https://developer.android.com/google/play/billing/migrate-gpblv5). - Added [`BillingClient.queryProductDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryProductDetailsAsync(com.android.billingclient.api.QueryProductDetailsParams,%20com.android.billingclient.api.ProductDetailsResponseListener)) to replace `BillingClient.querySkuDetailsAsync()`. -- Added `setIsOfferPersonalized()` method for EU personalized pricing disclosure requirements. To learn more about how to use this method, see [Indicate a personalized - price](https://developer.android.com/google/play/billing/integrate#personalized-price). +- Added `setIsOfferPersonalized()` method for EU personalized pricing disclosure requirements. To learn more about how to use this method, see [Indicate a personalized price](https://developer.android.com/google/play/billing/integrate#personalized-price). - Removed `queryPurchases()`, which was previously deprecated and replaced by queryPurchasesAsync introduced in Google Play Billing Library 4.0.0. -- `launchPriceChangeFlow` has been deprecated and will be removed in a future release. To learn more about alternatives, see [Launch a price change - confirmation flow](https://developer.android.com/google/play/billing/subscriptions#price-change-launch). +- `launchPriceChangeFlow` has been deprecated and will be removed in a future release. To learn more about alternatives, see [Launch a price change confirmation flow](https://developer.android.com/google/play/billing/subscriptions#price-change-launch). - Removed [`setVrPurchaseFlow()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setVrPurchaseFlow(boolean)), which was previously used when instantiating a purchase flow. In previous versions, this method redirected the user to complete the purchase on their Android-powered device. Once you remove this method, users will complete the purchase through the standard purchase flow. ## Google Play Billing Library 4.1 release (2022-02-23) -Version 4.1.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 4.1.0 of the Google Play Billing Library and Kotlin extensions are now available. This version contains the following changes. ### Summary of changes -- Added [`BillingClient.showInAppMessages()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#showInAppMessages(android.app.Activity,%20com.android.billingclient.api.InAppMessageParams,%20com.android.billingclient.api.InAppMessageResponseListener)) to help with handling subscription payment declines. To learn more about how to use in-app messaging for handling subscriptions payment declines, see [Handling payment - declines](https://developer.android.com/google/play/billing/subscriptions#payment-declines). +- Added [`BillingClient.showInAppMessages()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#showInAppMessages(android.app.Activity,%20com.android.billingclient.api.InAppMessageParams,%20com.android.billingclient.api.InAppMessageResponseListener)) to help with handling subscription payment declines. To learn more about how to use in-app messaging for handling subscriptions payment declines, see [Handling payment declines](https://developer.android.com/google/play/billing/subscriptions#payment-declines). ## Google Play Billing Library 4.0 Release (2021-05-18) -Version 4.0.0 of the Google Play Billing Library and Kotlin extensions are now -available. +Version 4.0.0 of the Google Play Billing Library and Kotlin extensions are now available. ### Summary of changes -- Added - [`BillingClient.queryPurchasesAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(java.lang.String,%20com.android.billingclient.api.PurchasesResponseListener)) - to replace - [`BillingClient.queryPurchases()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchases(java.lang.String)) - which will be removed in a future release. +- Added [`BillingClient.queryPurchasesAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(java.lang.String,%20com.android.billingclient.api.PurchasesResponseListener)) to replace [`BillingClient.queryPurchases()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchases(java.lang.String)) which will be removed in a future release. -- Added new subscription replacement mode - [`IMMEDIATE_AND_CHARGE_FULL_PRICE`](https://developer.android.com/google/play/billing/subscriptions#change). +- Added new subscription replacement mode [`IMMEDIATE_AND_CHARGE_FULL_PRICE`](https://developer.android.com/google/play/billing/subscriptions#change). -- Added - [`BillingClient.getConnectionState()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#getConnectionState()) - method to retrieve the Play Billing Library's connection state. +- Added [`BillingClient.getConnectionState()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#getConnectionState()) method to retrieve the Play Billing Library's connection state. -- Updated Javadoc and implementation to indicate which thread a method can be - called on and which thread results are posted. +- Updated Javadoc and implementation to indicate which thread a method can be called on and which thread results are posted. -- Added - [`BillingFlowParams.Builder.setSubscriptionUpdateParams()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setSubscriptionUpdateParams(com.android.billingclient.api.BillingFlowParams.SubscriptionUpdateParams)) - as a new way to initiate subscription updates. This replaces - `BillingFlowParams#getReplaceSkusProrationMode`, - `BillingFlowParams#getOldSkuPurchaseToken`, `BillingFlowParams#getOldSku`, - `BillingFlowParams.Builder#setReplaceSkusProrationMode`, - `BillingFlowParams.Builder#setOldSku` which have been removed. +- Added [`BillingFlowParams.Builder.setSubscriptionUpdateParams()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setSubscriptionUpdateParams(com.android.billingclient.api.BillingFlowParams.SubscriptionUpdateParams)) as a new way to initiate subscription updates. This replaces `BillingFlowParams#getReplaceSkusProrationMode`, `BillingFlowParams#getOldSkuPurchaseToken`, `BillingFlowParams#getOldSku`, `BillingFlowParams.Builder#setReplaceSkusProrationMode`, `BillingFlowParams.Builder#setOldSku` which have been removed. -- Added - [`Purchase.getQuantity()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#getQuantity()) - and - [`PurchaseHistoryRecord.getQuantity()`](https://developer.android.com/reference/com/android/billingclient/api/PurchaseHistoryRecord#getQuantity()). +- Added [`Purchase.getQuantity()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#getQuantity()) and [`PurchaseHistoryRecord.getQuantity()`](https://developer.android.com/reference/com/android/billingclient/api/PurchaseHistoryRecord#getQuantity()). -- Added - [`Purchase#getSkus()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#getSkus()) - and - [`PurchaseHistoryRecord#getSkus()`](https://developer.android.com/reference/com/android/billingclient/api/PurchaseHistoryRecord#getSkus()). - These replace `Purchase#getSku` and `PurchaseHistoryRecord#getSku` which - have been removed. +- Added [`Purchase#getSkus()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#getSkus()) and [`PurchaseHistoryRecord#getSkus()`](https://developer.android.com/reference/com/android/billingclient/api/PurchaseHistoryRecord#getSkus()). These replace `Purchase#getSku` and `PurchaseHistoryRecord#getSku` which have been removed. -- Removed `BillingFlowParams#getSku`, `BillingFlowParams#getSkuDetails` and - `BillingFlowParams#getSkuType`. +- Removed `BillingFlowParams#getSku`, `BillingFlowParams#getSkuDetails` and `BillingFlowParams#getSkuType`. ## Google Play Billing Library 3.0.3 Release (2021-03-12) -Version 3.0.3 of the Google Play Billing Library, Kotlin extension, and Unity -plugin are now available. +Version 3.0.3 of the Google Play Billing Library, Kotlin extension, and Unity plugin are now available. ### Java and Kotlin Bug fixes @@ -517,8 +370,7 @@ plugin are now available. ## Google Play Billing Library 3.0.2 Release (2020-11-24) -Version 3.0.2 of the Google Play Billing Library and Kotlin extension are now -available. +Version 3.0.2 of the Google Play Billing Library and Kotlin extension are now available. ### Bug fixes @@ -527,8 +379,7 @@ available. ## Google Play Billing Library 3.0.1 Release (2020-09-30) -Version 3.0.1 of the Google Play Billing Library and Kotlin extension are now -available. +Version 3.0.1 of the Google Play Billing Library and Kotlin extension are now available. ### Bug fixes @@ -536,8 +387,7 @@ available. ## Google Play Billing Library 3.0 Release (2020-06-08) -Version 3.0.0 of the Google Play Billing Library, Kotlin extension, and Unity -plugin are now available. +Version 3.0.0 of the Google Play Billing Library, Kotlin extension, and Unity plugin are now available. ### Summary of changes @@ -563,23 +413,13 @@ Version 2.2.1 of the Google Play Billing library is now available. ## Google Play Billing Library 2.2.0 release and Unity support (2020-03-23) -Version 2.2.0 of the Google Play Billing provides functionality that helps -developers ensure purchases are attributed to the correct user. These changes -replace the need to build custom solutions based on developer payload. As part -of this update, the developer payload functionality has been deprecated and will -be removed in a future release. For more information, including recommended -alternatives, see [Developer payload](https://developer.android.com/google/play/billing/developer-payload). +Version 2.2.0 of the Google Play Billing provides functionality that helps developers ensure purchases are attributed to the correct user. These changes replace the need to build custom solutions based on developer payload. As part of this update, the developer payload functionality has been deprecated and will be removed in a future release. For more information, including recommended alternatives, see [Developer payload](https://developer.android.com/google/play/billing/developer-payload). ### Google Play Billing Billing Library 2 for Unity -In addition to the current Java and Kotlin versions of Google Play Billing -Library 2, we released a version of the library for use with Unity. Game -developers using the Unity in-app purchase API can upgrade now to take advantage -of all Google Play Billing Library 2 features and to make the subsequent -upgrades to future versions of the Google Play Billing Library easier. +In addition to the current Java and Kotlin versions of Google Play Billing Library 2, we released a version of the library for use with Unity. Game developers using the Unity in-app purchase API can upgrade now to take advantage of all Google Play Billing Library 2 features and to make the subsequent upgrades to future versions of the Google Play Billing Library easier. -To learn more, see [Use Google Play Billing with -Unity](https://developer.android.com/google/play/billing/unity). +To learn more, see [Use Google Play Billing with Unity](https://developer.android.com/google/play/billing/unity). ### Summary of changes @@ -587,27 +427,19 @@ Unity](https://developer.android.com/google/play/billing/unity). - In [`AcknowledgePurchaseParams`](https://developer.android.com/reference/com/android/billingclient/api/AcknowledgePurchaseParams), deprecated [`setDeveloperPayload()`](https://developer.android.com/reference/com/android/billingclient/api/AcknowledgePurchaseParams.Builder#setDeveloperPayload(java.lang.String)) and [`getDeveloperPayload()`](https://developer.android.com/reference/com/android/billingclient/api/AcknowledgePurchaseParams#getDeveloperPayload()) methods. - In [`ConsumeParams`](https://developer.android.com/reference/com/android/billingclient/api/ConsumeParams), deprecated [`setDeveloperPayload()`](https://developer.android.com/reference/com/android/billingclient/api/ConsumeParams.Builder#setDeveloperPayload(java.lang.String)) and [`getDeveloperPayload()`](https://developer.android.com/reference/com/android/billingclient/api/ConsumeParams#getdeveloperpayload) methods. - In [`BillingFlowParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder), renamed [`setAccountId()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setAccountId(java.lang.String)) to [`setObfuscatedAccountId()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setObfuscatedAccountId(java.lang.String)), and documented length restriction of 64 characters and restriction disallowing Personally Identifiable Information (PII) in this field. [`setAccountId()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setaccountid) has been marked as deprecated and will be removed in a future library version. - - In `BillingFlowParams`, added [`setObfuscatedProfileId()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setobfuscatedprofileid) which works similarly to [`setObfuscatedAccountId()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setObfuscatedAccountId(java.lang.String)). For more information, see [Developer payload updates and - alternatives](https://developer.android.com/google/play/billing/developer-payload). + - In `BillingFlowParams`, added [`setObfuscatedProfileId()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setobfuscatedprofileid) which works similarly to [`setObfuscatedAccountId()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setObfuscatedAccountId(java.lang.String)). For more information, see [Developer payload updates and alternatives](https://developer.android.com/google/play/billing/developer-payload). - In [`Purchase`](https://developer.android.com/reference/com/android/billingclient/api/Purchase), added the [`getAccountIdentifiers()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#getAccountIdentifiers()) method to return the obfuscated account identifiers set in `BillingFlowParams`. - - In [`BillingClient`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient), the [`loadRewardedSku()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#loadRewardedSku(com.android.billingclient.api.RewardLoadParams,%20com.android.billingclient.api.RewardResponseListener)) method has been marked deprecated as part of deprecating rewarded SKUs. You can find more information about the deprecation in the [Play Console - Help - Center](https://support.google.com/googleplay/android-developer/answer/9155268). + - In [`BillingClient`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient), the [`loadRewardedSku()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#loadRewardedSku(com.android.billingclient.api.RewardLoadParams,%20com.android.billingclient.api.RewardResponseListener)) method has been marked deprecated as part of deprecating rewarded SKUs. You can find more information about the deprecation in the [Play Console Help Center](https://support.google.com/googleplay/android-developer/answer/9155268). ## Google Play Billing Library 2.1.0 Release and Kotlin Extension 2.1.0 Release (2019-12-10) -Version 2.1.0 of the Google Play Billing library and the new Kotlin extension -are now available. The Play Billing Library Kotlin extension provides idiomatic -API alternatives for Kotlin consumption, featuring better null-safety and -coroutines. For code examples, see [Use the Google Play Billing -Library](https://developer.android.com/google/play/billing/billing_library_overview). +Version 2.1.0 of the Google Play Billing library and the new Kotlin extension are now available. The Play Billing Library Kotlin extension provides idiomatic API alternatives for Kotlin consumption, featuring better null-safety and coroutines. For code examples, see [Use the Google Play Billing Library](https://developer.android.com/google/play/billing/billing_library_overview). This version contains the following changes. ### Summary of changes -- In [`BillingFlowParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams), deprecated `setOldSku(String oldSku)` and replaced with `setOldSku(String - oldSku, String purchaseToken)`, to disambiguate when multiple accounts on the device own the same sku. +- In [`BillingFlowParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams), deprecated `setOldSku(String oldSku)` and replaced with `setOldSku(String oldSku, String purchaseToken)`, to disambiguate when multiple accounts on the device own the same sku. ## Google Play Billing Library 2.0.3 Release (2019-08-05) @@ -619,14 +451,11 @@ Version 2.0.3 of the Google Play Billing library is now available. ## Google Play Billing Library 2.0.2 Release (2019-07-08) -Version 2.0.2 of the Google Play Billing library is now available. This release -contains updates to the reference documentation and does not change library -functionality. +Version 2.0.2 of the Google Play Billing library is now available. This release contains updates to the reference documentation and does not change library functionality. ## Google Play Billing Library 2.0.1 Release (2019-06-06) -Version 2.0.1 of the Google Play Billing library is now available. This version -contains the following changes. +Version 2.0.1 of the Google Play Billing library is now available. This version contains the following changes. ### Bug fixes @@ -635,8 +464,7 @@ contains the following changes. ## Google Play Billing Library 2.0 Release (2019-05-07) -Version 2.0 of the Google Play Billing library is now available. This version -contains the following changes. +Version 2.0 of the Google Play Billing library is now available. This version contains the following changes. ### Purchases must be acknowledged within three days @@ -646,32 +474,11 @@ contains the following changes. > [!NOTE] > **Note:** This requirement applies only to apps that use the Google Play Billing Library version 2.0 and newer. This requirement doesn't apply if you use an older version of the Google Play Billing Library, or if you use the AIDL API. -Google Play supports purchasing products from inside of your app (in-app) or -outside of your app (out-of-app). In order for Google Play to ensure a -consistent purchase experience regardless of where the user purchases your -product, you must acknowledge all purchases received through the Google Play -Billing Library as soon as possible after granting entitlement to the user. If -you don't acknowledge a purchase within three days, the user automatically -receives a refund, and Google Play revokes the purchase. For [pending -transactions](https://developer.android.com/google/play/billing/release-notes#2_0_pending) (new in version 2.0), the three-day window starts -when the purchase has moved to the `PURCHASED` state and does not apply while -the purchase is in a `PENDING` state. +Google Play supports purchasing products from inside of your app (in-app) or outside of your app (out-of-app). In order for Google Play to ensure a consistent purchase experience regardless of where the user purchases your product, you must acknowledge all purchases received through the Google Play Billing Library as soon as possible after granting entitlement to the user. If you don't acknowledge a purchase within three days, the user automatically receives a refund, and Google Play revokes the purchase. For [pending transactions](https://developer.android.com/google/play/billing/release-notes#2_0_pending) (new in version 2.0), the three-day window starts when the purchase has moved to the `PURCHASED` state and does not apply while the purchase is in a `PENDING` state. -For subscriptions, you must acknowledge any purchase that has a new purchase -token. This means that all initial purchases, plan changes, and re-signups need -to be acknowledged, but you don't need to acknowledge subsequent renewals. To -determine if a purchase needs acknowledgment, you can check the acknowledgement -field in the purchase. +For subscriptions, you must acknowledge any purchase that has a new purchase token. This means that all initial purchases, plan changes, and re-signups need to be acknowledged, but you don't need to acknowledge subsequent renewals. To determine if a purchase needs acknowledgment, you can check the acknowledgement field in the purchase. -The `Purchase` object now includes an -[`isAcknowledged()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#isacknowledged) -method that indicates whether a purchase has been acknowledged. In addition, the -Google Play Developer API includes acknowledgement boolean values for both -[`Purchases.products`](https://developers.google.com/android-publisher/api-ref/purchases/products) -and -[`Purchases.subscriptions`](https://developers.google.com/android-publisher/api-ref/purchases/subscriptions). -Before acknowledging a purchase, be sure to use these methods to determine if -the purchase has already been acknowledged. +The `Purchase` object now includes an [`isAcknowledged()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#isacknowledged) method that indicates whether a purchase has been acknowledged. In addition, the Google Play Developer API includes acknowledgement boolean values for both [`Purchases.products`](https://developers.google.com/android-publisher/api-ref/purchases/products) and [`Purchases.subscriptions`](https://developers.google.com/android-publisher/api-ref/purchases/subscriptions). Before acknowledging a purchase, be sure to use these methods to determine if the purchase has already been acknowledged. You can acknowledge a purchase by using one of the following methods: @@ -681,32 +488,18 @@ You can acknowledge a purchase by using one of the following methods: ### BillingFlowParams.setSku() has been removed -The previously-deprecated `BillingFlowParams#setSku()` method has been removed -in this release. Before rendering products in a purchase flow, you must now call -[`BillingClient.querySkuDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryskudetailsasync), -passing the resulting -[`SkuDetails`](https://developer.android.com/reference/com/android/billingclient/api/SkuDetails) object to -[`BillingFlowParams.Builder.setSkuDetails()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setskudetails). +The previously-deprecated `BillingFlowParams#setSku()` method has been removed in this release. Before rendering products in a purchase flow, you must now call [`BillingClient.querySkuDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryskudetailsasync), passing the resulting [`SkuDetails`](https://developer.android.com/reference/com/android/billingclient/api/SkuDetails) object to [`BillingFlowParams.Builder.setSkuDetails()`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setskudetails). > [!NOTE] > **Note:** Caching `SkuDetails` between user sessions is not recommended, as `SkuDetails` objects are valid only for a limited time before you must refresh them again by calling `querySkuDetailsAsync()`. -For code examples, see [Use the Google Play Billing -Library](https://developer.android.com/google/play/billing/billing_library_overview). +For code examples, see [Use the Google Play Billing Library](https://developer.android.com/google/play/billing/billing_library_overview). ### Developer payload is supported -Version 2.0 of the Google Play Billing library adds support for *developer -payload* ---arbitrary strings that can be attached to purchases. You can -attach a developer payload parameter to a purchase, but only when the purchase -is acknowledged or consumed. This is unlike developer payload in AIDL, where the -payload could be specified when launching the purchase flow. Because purchases -can now be initiated [from outside of your app](https://developer.android.com/google/play/billing/release-notes#2_0_acknowledge), this change -ensures that you always have an opportunity to add a payload to purchases. +Version 2.0 of the Google Play Billing library adds support for *developer payload* ---arbitrary strings that can be attached to purchases. You can attach a developer payload parameter to a purchase, but only when the purchase is acknowledged or consumed. This is unlike developer payload in AIDL, where the payload could be specified when launching the purchase flow. Because purchases can now be initiated [from outside of your app](https://developer.android.com/google/play/billing/release-notes#2_0_acknowledge), this change ensures that you always have an opportunity to add a payload to purchases. -To access the payload in the new library, `Purchase` objects now include a -[`getDeveloperPayload()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#getdeveloperpayload) -method. +To access the payload in the new library, `Purchase` objects now include a [`getDeveloperPayload()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#getdeveloperpayload) method. > [!NOTE] > **Note:** You cannot modify a payload after it is assigned. @@ -716,11 +509,9 @@ method. > [!NOTE] > **Note:** This feature is being tested, and general availability is not guaranteed. -When you offer a discounted SKU, Google Play now returns the original price of -the SKU so that you can show users that they are receiving a discount. +When you offer a discounted SKU, Google Play now returns the original price of the SKU so that you can show users that they are receiving a discount. -[`SkuDetails`](https://developer.android.com/reference/com/android/billingclient/api/SkuDetails) contains two -new methods for retrieving the original SKU price: +[`SkuDetails`](https://developer.android.com/reference/com/android/billingclient/api/SkuDetails) contains two new methods for retrieving the original SKU price: - [`getOriginalPriceAmountMicros()`](https://developer.android.com/reference/com/android/billingclient/api/SkuDetails#getOriginalPriceAmountMicros()) - returns the unformatted original price of the SKU before discount. @@ -729,78 +520,42 @@ new methods for retrieving the original SKU price: ### Pending transactions -With version 2.0 of the Google Play Billing library, you *must* support -purchases where additional action is required before granting entitlement. For -example, a user might choose to purchase your in-app product at a physical store -using cash. This means that the transaction is completed outside of your app. In -this scenario, you should grant entitlement only after the user has completed -the transaction. +With version 2.0 of the Google Play Billing library, you *must* support purchases where additional action is required before granting entitlement. For example, a user might choose to purchase your in-app product at a physical store using cash. This means that the transaction is completed outside of your app. In this scenario, you should grant entitlement only after the user has completed the transaction. -To enable pending purchases, call -[`enablePendingPurchases()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enablependingpurchases) -as part of initializing your app. +To enable pending purchases, call [`enablePendingPurchases()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder#enablependingpurchases) as part of initializing your app. -Use -[`Purchase.getPurchaseState()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#getpurchasestate) -to determine whether the purchase state is `PURCHASED` or `PENDING`. Note that -you should grant entitlement only when the state is `PURCHASED`. You should -check for `Purchase` status updates by doing the following: +Use [`Purchase.getPurchaseState()`](https://developer.android.com/reference/com/android/billingclient/api/Purchase#getpurchasestate) to determine whether the purchase state is `PURCHASED` or `PENDING`. Note that you should grant entitlement only when the state is `PURCHASED`. You should check for `Purchase` status updates by doing the following: 1. When starting your app, call [`BillingClient.queryPurchases()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#querypurchases) to retrieve the list of unconsumed products associated with the user. 2. Call `Purchase.getPurchaseState()` on each returned `Purchase` object. 3. Implement the [`onPurchasesUpdated()`](https://developer.android.com/reference/com/android/billingclient/api/PurchasesUpdatedListener#onpurchasesupdated) method to respond to changes to `Purchase` objects. -In addition, the Google Play Developer API includes a `PENDING` state for -[`Purchases.products`](https://developers.google.com/android-publisher/api-ref/purchases/products). -Pending transactions are not supported for subscriptions. +In addition, the Google Play Developer API includes a `PENDING` state for [`Purchases.products`](https://developers.google.com/android-publisher/api-ref/purchases/products). Pending transactions are not supported for subscriptions. -This release also introduces a new real-time developer notification type, -`OneTimeProductNotification`. This notification type contains a single message -whose value is either `ONE_TIME_PRODUCT_PURCHASED` or -`ONE_TIME_PRODUCT_CANCELED`. This notification type is sent only for purchases -associated with delayed forms of payment, such as cash. +This release also introduces a new real-time developer notification type, `OneTimeProductNotification`. This notification type contains a single message whose value is either `ONE_TIME_PRODUCT_PURCHASED` or `ONE_TIME_PRODUCT_CANCELED`. This notification type is sent only for purchases associated with delayed forms of payment, such as cash. -When acknowledging pending purchases, be sure to acknowledge only when the -purchase state is `PURCHASED` and not `PENDING`. +When acknowledging pending purchases, be sure to acknowledge only when the purchase state is `PURCHASED` and not `PENDING`. > [!NOTE] > **Note:** Pending transactions can be tested using license testers. In addition to two test credit cards, license testers have access to two new test instruments for delayed forms of payment which automatically complete or cancel after a couple of minutes. While testing your application, you should verify that your application does not grant entitlement or acknowledge the purchase immediately after purchasing with either of these two new instruments. When purchasing using the new test instrument that automatically completes, you should verify that your application grants entitlement and acknowledges the purchase once the purchase completes. ### API changes -Version 2.0 of the Google Play Billing library contains several API changes to -support new features and clarify existing functionality. +Version 2.0 of the Google Play Billing library contains several API changes to support new features and clarify existing functionality. #### consumeAsync -[`consumeAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#consumeasync) -now takes a -[`ConsumeParams`](https://developer.android.com/reference/com/android/billingclient/api/ConsumeParams) object -instead of a `purchaseToken`. `ConsumeParams` contains the `purchaseToken` as -well as an optional developer payload. +[`consumeAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#consumeasync) now takes a [`ConsumeParams`](https://developer.android.com/reference/com/android/billingclient/api/ConsumeParams) object instead of a `purchaseToken`. `ConsumeParams` contains the `purchaseToken` as well as an optional developer payload. The previous version of `consumeAsync()` has been removed in this release. #### queryPurchaseHistoryAsync -To minimize confusion, -[`queryPurchaseHistoryAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchaseHistoryAsync(java.lang.String,%20com.android.billingclient.api.PurchaseHistoryResponseListener)) -now returns a -[`PurchaseHistoryRecord`](https://developer.android.com/reference/com/android/billingclient/api/PurchaseHistoryRecord) -object instead of a `Purchase` object. The `PurchaseHistoryRecord` object is the -same as a `Purchase` object, except that it reflects only the values returned by -`queryPurchaseHistoryAsync()` and does not contain the `autoRenewing`, -`orderId`, and `packageName` fields. Note that nothing has changed with the -returned data---`queryPurchaseHistoryAsync()` returns the same data as -before. +To minimize confusion, [`queryPurchaseHistoryAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchaseHistoryAsync(java.lang.String,%20com.android.billingclient.api.PurchaseHistoryResponseListener)) now returns a [`PurchaseHistoryRecord`](https://developer.android.com/reference/com/android/billingclient/api/PurchaseHistoryRecord) object instead of a `Purchase` object. The `PurchaseHistoryRecord` object is the same as a `Purchase` object, except that it reflects only the values returned by `queryPurchaseHistoryAsync()` and does not contain the `autoRenewing`, `orderId`, and `packageName` fields. Note that nothing has changed with the returned data---`queryPurchaseHistoryAsync()` returns the same data as before. #### BillingResult return values -APIs that previously returned a `BillingResponse` integer value now return a -[`BillingResult`](https://developer.android.com/reference/com/android/billingclient/api/BillingResult) -object. `BillingResult` contains the `BillingResponse` integer as well as a -debug string that you can use to diagnose errors. The debug string uses an en-US -locale and is not meant to be shown to end users. +APIs that previously returned a `BillingResponse` integer value now return a [`BillingResult`](https://developer.android.com/reference/com/android/billingclient/api/BillingResult) object. `BillingResult` contains the `BillingResponse` integer as well as a debug string that you can use to diagnose errors. The debug string uses an en-US locale and is not meant to be shown to end users. ### Bug fixes @@ -808,8 +563,7 @@ locale and is not meant to be shown to end users. ## Google Play Billing Library 1.2.2 Release (2019-03-07) -Version 1.2.2 of the Google Play Billing library is now available. This version -contains the following changes. +Version 1.2.2 of the Google Play Billing library is now available. This version contains the following changes. ### Bug fixes @@ -822,14 +576,11 @@ contains the following changes. ## Play Billing Library 1.2.1 Release (2019-03-04) -Version 1.2.1 of the Google Play Billing library is now available. This version -contains the following changes. +Version 1.2.1 of the Google Play Billing library is now available. This version contains the following changes. ### Major changes -- Added support for [rewarded - products](https://developer.android.com/google/play/billing/billing_rewarded_products). For more information on monetization options, see [Add rewarded-product-specific - features](https://developer.android.com/distribute/best-practices/earn/monetization-options). +- Added support for [rewarded products](https://developer.android.com/google/play/billing/billing_rewarded_products). For more information on monetization options, see [Add rewarded-product-specific features](https://developer.android.com/distribute/best-practices/earn/monetization-options). ### Other changes @@ -843,13 +594,11 @@ contains the following changes. ## Google Play Billing Library 1.2 Release (2018-10-18) -Version 1.2 of the Google Play Billing library is now available. This version -contains the following changes. +Version 1.2 of the Google Play Billing library is now available. This version contains the following changes. ### Summary of changes -- The Google Play Billing Library is now licensed under the [Android Software - Development Kit License Agreement](https://developer.android.com/studio/terms). +- The Google Play Billing Library is now licensed under the [Android Software Development Kit License Agreement](https://developer.android.com/studio/terms). - Added the `launchPriceChangeConfirmationFlow` API, which prompts users to review a pending change to a subscription price. - Added support for a new proration mode, `DEFERRED`, when upgrading or downgrading a user's subscription. - In the `BillingFlowParams` class, replaced `setSku()` with `setSkuDetails()`. @@ -857,14 +606,9 @@ contains the following changes. #### Price change confirmation -You can now change the price of a subscription in Google Play Console -and prompt users to review and accept the new price when they enter your app. +You can now change the price of a subscription in Google Play Console and prompt users to review and accept the new price when they enter your app. -To use this API, create a `PriceChangeFlowParams` object by using the -`skuDetails` of the subscription product, and then call -`launchPriceChangeConfirmationFlow()`. Implement the -`PriceChangeConfirmationListener` to handle the result when the price change -confirmation flow finishes, as shown in the following code snippet: +To use this API, create a `PriceChangeFlowParams` object by using the `skuDetails` of the subscription product, and then call `launchPriceChangeConfirmationFlow()`. Implement the `PriceChangeConfirmationListener` to handle the result when the price change confirmation flow finishes, as shown in the following code snippet: ### Kotlin @@ -900,32 +644,19 @@ billingClient.launchPriceChangeConfirmationFlow(activity, }); ``` -The price change confirmation flow displays a dialog containing the new pricing -information, asking users to accept the new price. This flow returns a response -code of type -[`BillingClient.BillingResponse`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponse). +The price change confirmation flow displays a dialog containing the new pricing information, asking users to accept the new price. This flow returns a response code of type [`BillingClient.BillingResponse`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponse). #### New proration mode -When upgrading or downgrading a user's subscription, you can use a new proration -mode, `DEFERRED`. This mode updates the user's subscription when it next renews. -To learn more about how to set this proration mode, see [Set proration -mode](https://developer.android.com/google/play/billing/billing_subscriptions#set-proration-mode). +When upgrading or downgrading a user's subscription, you can use a new proration mode, `DEFERRED`. This mode updates the user's subscription when it next renews. To learn more about how to set this proration mode, see [Set proration mode](https://developer.android.com/google/play/billing/billing_subscriptions#set-proration-mode). #### New method for setting SKU details -In the `BillingFlowParams` class, the `setSku()` method has been deprecated. -This change serves to optimize the Google Play Billing flow. +In the `BillingFlowParams` class, the `setSku()` method has been deprecated. This change serves to optimize the Google Play Billing flow. -When constructing a new instance of `BillingFlowParams` in your in-app billing -client, we recommend that you instead work with the JSON object directly using -`setSkuDetails()`, as shown in the following code snippet: +When constructing a new instance of `BillingFlowParams` in your in-app billing client, we recommend that you instead work with the JSON object directly using `setSkuDetails()`, as shown in the following code snippet: -In the `BillingFlowParams` Builder class, the `setSku()` method has been -deprecated. Instead, use the `setSkuDetails()` method, as shown in the following -code snippet. The object passed into `setSkuDetails()` object comes from the -[`querySkuDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#querySkuDetailsAsync(com.android.billingclient.api.SkuDetailsParams,%20com.android.billingclient.api.SkuDetailsResponseListener)) -method. +In the `BillingFlowParams` Builder class, the `setSku()` method has been deprecated. Instead, use the `setSkuDetails()` method, as shown in the following code snippet. The object passed into `setSkuDetails()` object comes from the [`querySkuDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#querySkuDetailsAsync(com.android.billingclient.api.SkuDetailsParams,%20com.android.billingclient.api.SkuDetailsResponseListener)) method. ### Kotlin @@ -984,8 +715,7 @@ private void startPurchase(String skuId) { ## Play Billing Library 1.1 Release (2018-05-07) -Version 1.1 of the Google Play Billing library is now available. This version -contains the following changes. +Version 1.1 of the Google Play Billing library is now available. This version contains the following changes. ### Summary of changes @@ -995,13 +725,11 @@ contains the following changes. ### Behavior changes -Version 1.1 of the Google Play Billing library contains the following behavior -changes. +Version 1.1 of the Google Play Billing library contains the following behavior changes. #### Developers can set `replaceSkusProrationMode` in [`BillingFlowParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams) class -A `ProrationMode` provides further details on the type of proration when -upgrading or downgrading a user's subscription. +A `ProrationMode` provides further details on the type of proration when upgrading or downgrading a user's subscription. ### Kotlin @@ -1040,20 +768,11 @@ Google Play supports following proration modes: ### `replaceSkusProration` is no longer supported in [`BillingFlowParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.html) class -Developers used to be able to set a boolean flag to charge a prorated amount for -a subscription upgrade request. Given that we are supporting `ProrationMode`, -which contains more detailed proration instruction, this boolean flag is no -longer supported. +Developers used to be able to set a boolean flag to charge a prorated amount for a subscription upgrade request. Given that we are supporting `ProrationMode`, which contains more detailed proration instruction, this boolean flag is no longer supported. ### [`launchBillingFlow()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#launchBillingFlow(android.app.Activity,%20com.android.billingclient.api.BillingFlowParams)) now triggers a callback for failed responses -The Billing Library will always trigger the -[`PurhcasesUpdatedListener`](https://developer.android.com/reference/com/android/billingclient/api/PurchasesUpdatedListener) -callback and return a -[`BillingResponse`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponse) -asynchronously. The synchronous return value of -[`BillingResponse`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponse) -is kept as well. +The Billing Library will always trigger the [`PurhcasesUpdatedListener`](https://developer.android.com/reference/com/android/billingclient/api/PurchasesUpdatedListener) callback and return a [`BillingResponse`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponse) asynchronously. The synchronous return value of [`BillingResponse`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponse) is kept as well. ### Bug fixes @@ -1063,8 +782,7 @@ is kept as well. ## Google Play Billing Library 1.0 Release (2017-09-19, [Announcement](https://android-developers.googleblog.com/2017/09/google-play-billing-library-10-released.html)) -Version 1.0 of the Google Play Billing library is now available. This version -contains the following changes. +Version 1.0 of the Google Play Billing library is now available. This version contains the following changes. ### Important changes @@ -1075,13 +793,11 @@ contains the following changes. ### Behavior changes -Version 1.0 of the Google Play Billing library contains the following behavior -changes. +Version 1.0 of the Google Play Billing library contains the following behavior changes. #### BillingClient.Builder class -[`BillingClient.Builder`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder.html) -is now initialized via the newBuilder pattern: +[`BillingClient.Builder`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder.html) is now initialized via the newBuilder pattern: ### Kotlin @@ -1097,10 +813,7 @@ billingClient = BillingClient.newBuilder(context).setListener(this).build(); #### launchBillingFlow method is now called using a BillingFlowParams class -To initiate the billing flow for a purchase or subscription, the -[`launchBillingFlow()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#launchBillingFlow(android.app.Activity,%0Acom.android.billingclient.api.BillingFlowParams)) method receives a -[`BillingFlowParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.html) -instance initialized with parameters specific to the request: +To initiate the billing flow for a purchase or subscription, the [`launchBillingFlow()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#launchBillingFlow(android.app.Activity,%0Acom.android.billingclient.api.BillingFlowParams)) method receives a [`BillingFlowParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.html) instance initialized with parameters specific to the request: ### Kotlin @@ -1128,10 +841,7 @@ int responseCode = billingClient.launchBillingFlow(builder.build()); #### New way to query available products -Arguments for -[`queryPurchaseHistoryAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#queryPurchaseHistoryAsync(java.lang.String,%0Acom.android.billingclient.api.PurchaseHistoryResponseListener)) and -[`querySkuDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#querySkuDetailsAsync(com.android.billingclient.api.SkuDetailsParams,%0Acom.android.billingclient.api.SkuDetailsResponseListener)) methods were wrapped -into a Builder pattern: +Arguments for [`queryPurchaseHistoryAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#queryPurchaseHistoryAsync(java.lang.String,%0Acom.android.billingclient.api.PurchaseHistoryResponseListener)) and [`querySkuDetailsAsync()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#querySkuDetailsAsync(com.android.billingclient.api.SkuDetailsParams,%0Acom.android.billingclient.api.SkuDetailsResponseListener)) methods were wrapped into a Builder pattern: ### Kotlin @@ -1153,10 +863,7 @@ params.setSkusList(skuList) billingClient.querySkuDetailsAsync(params.build(), new SkuDetailsResponseListener() {...}) ``` -The result is now returned via result code and a list of -[`SkuDetails`](https://developer.android.com/reference/com/android/billingclient/api/SkuDetails.html) -objects instead of previous wrapper class for your convenience and to be -consistent across our API: +The result is now returned via result code and a list of [`SkuDetails`](https://developer.android.com/reference/com/android/billingclient/api/SkuDetails.html) objects instead of previous wrapper class for your convenience and to be consistent across our API: ### Kotlin @@ -1172,10 +879,7 @@ public void onSkuDetailsResponse(@BillingResponse int responseCode, List ### Bug fixes - [No response code in PURCHASES_UPDATED Bundle](https://issuetracker.google.com/issues/64075043) -- [Fix ProxyBillingActivity and PurchasesUpdatedListener issues during device - rotation](https://issuetracker.google.com/issues/63266562) +- [Fix ProxyBillingActivity and PurchasesUpdatedListener issues during device rotation](https://issuetracker.google.com/issues/63266562) ## Developer Preview 1 Release (2017-06-12, [Announcement](https://android-developers.googleblog.com/2017/06/money-made-easily-with-new-google-play.html)) -Developer preview launched, aimed to simplify the development process when it -comes to billing, allowing developers to focus their efforts on implementing -logic specific to the Android app, such as application architecture and -navigation structure. +Developer preview launched, aimed to simplify the development process when it comes to billing, allowing developers to focus their efforts on implementing logic specific to the Android app, such as application architecture and navigation structure. -The library includes several convenient classes and features for you to use when -integrating your Android apps with the Google Play Billing API. The library also -provides an abstraction layer on top of the Android Interface Definition -Language (AIDL) service, making it easier for developers to define the interface -between the app and the Google Play Billing API. \ No newline at end of file +The library includes several convenient classes and features for you to use when integrating your Android apps with the Google Play Billing API. The library also provides an abstraction layer on top of the Android Interface Definition Language (AIDL) service, making it easier for developers to define the interface between the app and the Google Play Billing API. \ No newline at end of file diff --git a/play/play-billing-library-version-upgrade/references/migration-logic.md b/play/play-billing-library-version-upgrade/references/migration-logic.md index 227a537..b0a095a 100644 --- a/play/play-billing-library-version-upgrade/references/migration-logic.md +++ b/play/play-billing-library-version-upgrade/references/migration-logic.md @@ -2,8 +2,7 @@ ### 1. Connection Management (The v8+ Reconnection Shift) -**Intent**: Move from developer-managed state (manual retries) to -library-managed state. +**Intent**: Move from developer-managed state (manual retries) to library-managed state. - **Remove** : Manual `startConnection()` calls or retry timers inside `onServiceDisconnected()`. - **Add** : `.enableAutoServiceReconnection()` to `BillingClient.Builder`. @@ -11,8 +10,7 @@ library-managed state. ### 2. Product Querying \& Models (The v5-v8 Architectural Shift) -**Intent**: Support the "One Product, Multiple Offers" model introduced in v5 -and refined in v8. +**Intent**: Support the "One Product, Multiple Offers" model introduced in v5 and refined in v8. - **Data Model Swap** : - **Legacy** : `SkuDetails` (1:1 mapping of ID to price). @@ -20,13 +18,7 @@ and refined in v8. - **Result Handling (v8+ Logic)** : - **Change** : `queryProductDetailsAsync` no longer returns a list in the listener. - **New Intent** : You must receive a `QueryProductDetailsResult` object. - - **Refactor** : `kotlin - // PBL 8+ Pattern - billingClient.queryProductDetailsAsync(params) { result: QueryProductDetailsResult -> - val responseCode = result.billingResult.responseCode - val productDetailsList = result.productDetailsList // Retrieve list from result object - // Process list... - }` + - **Refactor** : `kotlin // PBL 8+ Pattern billingClient.queryProductDetailsAsync(params) { result: QueryProductDetailsResult -> val responseCode = result.billingResult.responseCode val productDetailsList = result.productDetailsList // Retrieve list from result object // Process list... }` ### 3. Subscription Modernization (v6 \& v7) @@ -44,8 +36,7 @@ and refined in v8. ### 4. Purchase Handling \& History (v6+) -**Intent**: Move away from local-only purchase caches to real-time status -checks. +**Intent**: Move away from local-only purchase caches to real-time status checks. - **Active Purchases** : - **Deprecated** : `queryPurchases()` (synchronous). @@ -69,8 +60,7 @@ checks. ### 7. User-Facing Features (Post-Upgrade Recommendations) -Once the upgrade is complete, the following features are enabled by these -versions: +Once the upgrade is complete, the following features are enabled by these versions: - **v7** : **Installments** (Monthly payments for annual plans). - **v8** : **Prepaid Plans** (Users can top-up time without auto-renewing). diff --git a/play/play-billing-library-version-upgrade/references/version-checklist.md b/play/play-billing-library-version-upgrade/references/version-checklist.md index 98f5831..47005eb 100644 --- a/play/play-billing-library-version-upgrade/references/version-checklist.md +++ b/play/play-billing-library-version-upgrade/references/version-checklist.md @@ -1,7 +1,6 @@ ## Play Billing Library: Smart Version-Specific Checklist -Use this checklist to verify that every technical requirement between your -\[Current Version\] and \[Target Version\] has been met. +Use this checklist to verify that every technical requirement between your \[Current Version\] and \[Target Version\] has been met. ## PBL v1.x through v3.x diff --git a/security/android-intent-security/SKILL.md b/security/android-intent-security/SKILL.md index a94df09..b1f5f42 100644 --- a/security/android-intent-security/SKILL.md +++ b/security/android-intent-security/SKILL.md @@ -7,7 +7,7 @@ description: Best practices for Android Intent security. Use this skill when aud license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-06-25' + last-updated: '2026-08-06' keywords: - recipe - Android @@ -24,9 +24,7 @@ metadata: - Best Practices --- -This skill provides guidelines and patterns to secure Android components -(Activities, Services, Broadcast Receivers, Content Providers) and handle -Intents safely, preventing privilege escalation and unauthorized access. +This skill provides guidelines and patterns to secure Android components (Activities, Services, Broadcast Receivers, Content Providers) and handle Intents safely, preventing privilege escalation and unauthorized access. ## Glossary @@ -84,45 +82,19 @@ Evaluate the security implications of PendingIntent mutability flags: ### 3. Intent handling and redirection logic -IF (the component receives a nested Intent as an extra) { -IF (AndroidX Core 1.9.0+ and higher is available) { -MUST construct an `IntentSanitizer` to explicitly allowlist components, actions, data, and extras. -MUST call `sanitizeByThrowing()` or `sanitizeByFiltering()` before launching. -} ELSE { -MUST verify that the nested Intent's target package matches the current application package. -MUST verify that the target component of the nested Intent is publicly exported. -} -NEVER launch the nested Intent directly without validation. -} ELSE IF (the component handles broadcasts) { -MUST rely on the system's Protected Broadcast mechanism for system events (which guarantees the sender is the system framework). -MUST protect custom receivers with signature-level permissions or use `RECEIVER_NOT_EXPORTED` for dynamic receivers to restrict the sender. -} +IF (the component receives a nested Intent as an extra) { IF (AndroidX Core 1.9.0+ and higher is available) { MUST construct an `IntentSanitizer` to explicitly allowlist components, actions, data, and extras. MUST call `sanitizeByThrowing()` or `sanitizeByFiltering()` before launching. } ELSE { MUST verify that the nested Intent's target package matches the current application package. MUST verify that the target component of the nested Intent is publicly exported. } NEVER launch the nested Intent directly without validation. } ELSE IF (the component handles broadcasts) { MUST rely on the system's Protected Broadcast mechanism for system events (which guarantees the sender is the system framework). MUST protect custom receivers with signature-level permissions or use `RECEIVER_NOT_EXPORTED` for dynamic receivers to restrict the sender. } ### 4. PendingIntent security logic -IF (a PendingIntent is created for delivery to another application) { -MUST use `PendingIntent.FLAG_IMMUTABLE` by default. -IF (the PendingIntent must be mutable) { -MUST set the explicit target component or package name on the base `Intent`. -NEVER create an implicit, mutable `PendingIntent`. -} -} +IF (a PendingIntent is created for delivery to another application) { MUST use `PendingIntent.FLAG_IMMUTABLE` by default. IF (the PendingIntent must be mutable) { MUST set the explicit target component or package name on the base `Intent`. NEVER create an implicit, mutable `PendingIntent`. } } ### 5. ContentProvider security logic -IF (the ContentProvider is only for internal app use) { -MUST set `android:exported="false"`. -} ELSE { -MUST protect it with `android:readPermission` and `android:writePermission`. -MUST set `android:grantUriPermissions="false"` unless temporary URL access is strictly required. -} +IF (the ContentProvider is only for internal app use) { MUST set `android:exported="false"`. } ELSE { MUST protect it with `android:readPermission` and `android:writePermission`. MUST set `android:grantUriPermissions="false"` unless temporary URL access is strictly required. } ### 6. Service caller verification logic -IF (an exported service communicates with trusted sister/partner apps) { -MUST retrieve the calling UID using `Binder.getCallingUid()` and resolve it to package names using `PackageManager.getPackagesForUid()`. -MUST verify that the calling package signature fingerprint matches your trusted certificate hash. -} +IF (an exported service communicates with trusted sister/partner apps) { MUST retrieve the calling UID using `Binder.getCallingUid()` and resolve it to package names using `PackageManager.getPackagesForUid()`. MUST verify that the calling package signature fingerprint matches your trusted certificate hash. } *** ** * ** *** @@ -130,14 +102,14 @@ MUST verify that the calling package signature fingerprint matches your trusted ### 1. Safe intent redirection (manual verification) -Validate the target of a nested intent before launching it when modern -sanitization libraries are unavailable. +Validate the target of a nested intent before launching it when modern sanitization libraries are unavailable. - **Expected Inputs:** - An incoming `Intent` containing a nested `Intent` extra named `EXTRA_NESTED_INTENT`. - **Expected Outputs:** - Launches the target component if safe; throws `SecurityException` if validation fails. +
```kotlin fun safeIntentRedirectionManual() { @@ -179,20 +151,21 @@ fun safeIntentRedirectionManual() { } } } + ```
### 2. Safe intent redirection using IntentSanitizer -Filter or reject dynamic intents using AndroidX `IntentSanitizer` (AndroidX Core -1.9.0+). +Filter or reject dynamic intents using AndroidX `IntentSanitizer` (AndroidX Core 1.9.0+). - **Expected Inputs:** - An untrusted incoming `Intent`. - **Expected Outputs:** - `Intent`: A sanitized copy containing only allowlisted components, categories, and actions. Throws `SecurityException` on violations if using `sanitizeByThrowing()`. +
```kotlin fun safeIntentRedirectionSanitizer() { @@ -221,27 +194,30 @@ fun safeIntentRedirectionSanitizer() { // startActivity(filteredIntent) } } + ```
### 3. Custom signature permission protection -Declare a custom signature-level permission in the manifest to secure family app -communication. +Declare a custom signature-level permission in the manifest to secure family app communication. - **Expected Inputs:** Manifest configuration. - **Expected Outputs:** An activity that can only be launched by apps signed with the same developer certificate. +
```xml + ```
+
```xml + ```
### 4. Safe onNewIntent lifecycle verification (warm boot protection) -Ensure that activities reusing dynamic intents (for example, in background -launch paths) apply the same strict security filters inside `onNewIntent`. +Ensure that activities reusing dynamic intents (for example, in background launch paths) apply the same strict security filters inside `onNewIntent`. - **Expected Inputs:** - `newIntent` (`Intent`): The newly delivered intent. - **Expected Outputs:** - Executes processing logic only if the new intent passes security validation. +
```kotlin override fun onNewIntent(newIntent: Intent) { @@ -286,6 +263,7 @@ override fun onNewIntent(newIntent: Intent) { private fun validateIntent(intent: Intent): Boolean { return intent.hasExtra("VALID_PAYLOAD_MARKER") } + ```
@@ -299,6 +277,7 @@ Enforce immutability unless mutability is explicitly required. - **Expected Inputs (Mutable):** An intent with an explicit component set. - **Expected Outputs (Mutable):** A mutable `PendingIntent` locked to a specific receiver component to prevent hijacking. +
```kotlin fun createPendingIntents(context: Context) { @@ -323,14 +302,14 @@ fun createPendingIntents(context: Context) { PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) } + ```
### 6. Secure ContentProvider configuration and queries -Expose a ContentProvider securely and parameterize queries to prevent SQL -injection. +Expose a ContentProvider securely and parameterize queries to prevent SQL injection. - **Expected Inputs:** - `uri` (`Uri`): The query URI. @@ -340,6 +319,7 @@ injection. - **Expected Outputs:** - `Cursor`: Filtered query results, strictly bound to projection maps. +
```xml + ```
+
```kotlin override fun query( @@ -378,6 +360,7 @@ override fun query( val db = dbHelper.readableDatabase return queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder) } + ```
@@ -391,6 +374,7 @@ Verify the calling application's signature before binding to a service. - **Expected Outputs:** - `IBinder`: Local binder instance if caller signature matches trusted partner; throws `SecurityException` otherwise. +
```kotlin class SecureBoundService : Service() { @@ -439,6 +423,7 @@ class SecureBoundService : Service() { } } } + ```
@@ -447,9 +432,9 @@ class SecureBoundService : Service() { ## Error handling -Handle component binding, database queries, and intent redirection failures -securely to avoid exposing internal structures. +Handle component binding, database queries, and intent redirection failures securely to avoid exposing internal structures. +
```kotlin fun safeErrorHandling(callingPackage: String?) { @@ -469,6 +454,7 @@ fun safeErrorHandling(callingPackage: String?) { Log.w("INTEGRITY_WARNING", "Missing intent parameter", e) } } + ```
@@ -485,10 +471,7 @@ fun safeErrorHandling(callingPackage: String?) { ## Reporting guidelines -When this skill is executed to apply security hardening updates to a codebase, -the agent **MUST** generate a structured "Best Practices and Security Alignment -Update" report for the developer. The report **must** be written to the session -artifact folder (or printed in the final response) and include: +When this skill is executed to apply security hardening updates to a codebase, the agent **MUST** generate a structured "Best Practices and Security Alignment Update" report for the developer. The report **must** be written to the session artifact folder (or printed in the final response) and include: 1. **Security alignment area:** The category of improvement applied (for example, Safe Intent Redirection, Secure PendingIntent Configuration, ContentProvider Data Guarding). 2. **Impact and priority:** The potential safety risk addressed by the update (for example, Component Hijacking Prevention, Private Data Isolation). diff --git a/system/edge-to-edge/SKILL.md b/system/edge-to-edge/SKILL.md index f618ab2..ef19d2c 100644 --- a/system/edge-to-edge/SKILL.md +++ b/system/edge-to-edge/SKILL.md @@ -7,7 +7,7 @@ description: Use this skill to migrate your Jetpack Compose app to add adaptive license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-04-01' + last-updated: '2026-08-06' keywords: - android - compose @@ -35,11 +35,11 @@ metadata: ## Step 3: apply insets -- The app **MUST** apply system insets, or align content to rulers, so critical - UI remains tappable. Choose only one method to avoid double padding: +- The app **MUST** apply system insets, or align content to rulers, so critical UI remains tappable. Choose only one method to avoid double padding: 1. **PREFERRED:** When available, use `Scaffold`s and pass `PaddingValues` to the content lambda. +
```kotlin Scaffold { innerPadding -> @@ -51,6 +51,7 @@ metadata: contentPadding = innerPadding ) { /* Content */ } } + ```
@@ -76,6 +77,7 @@ metadata: 3. `TopAppBar(windowInsets = WindowInsets.systemBars.add(WindowInsets.captionBar))` 2. For components outside a Scaffold, use padding modifiers, such as `Modifier.safeDrawingPadding()` or `Modifier.windowInsetsPadding(WindowInsets.safeDrawing)`. +
```kotlin Box( @@ -90,16 +92,14 @@ metadata: Text("Login") } } + ```
3. For deeply nested components with excessive padding, use `WindowInsetsRulers` (e.g. `Modifier.fitInside(WindowInsetsRulers.SafeDrawing.current)`). See the *IME* section for a code sample. - 4. When you need an element (e.g. a custom header or decorative scrim) to - equal the dimensions of a system bar, use inset size modifiers (e.g. - `Modifier.windowInsetsTopHeight(WindowInsets.systemBars)`). - See the *Lists* section for a code sample. + 4. When you need an element (e.g. a custom header or decorative scrim) to equal the dimensions of a system bar, use inset size modifiers (e.g. `Modifier.windowInsetsTopHeight(WindowInsets.systemBars)`). See the *Lists* section for a code sample. ## Adaptive Scaffolds @@ -109,16 +109,13 @@ metadata: - For each Activity with a soft keyboard, check that `android:windowSoftInputMode="adjustResize"` is set in the AndroidManifest.xml. DO NOT use `SOFT_INPUT_ADJUST_RESIZE` because it is deprecated. Then, maintain focus on the input field. Choose one: - 1. **PREFERRED:** Add `Modifier.fitInside(WindowInsetsRulers.Ime.current)` to the content container. This is preferred over `imePadding()` because it reduces jank and extra padding caused by forgetting to consume insets upstream in the hierarchy. - - 2. Add `imePadding` to the content container. The padding modifier **MUST** be placed before `Modifier.verticalScroll()`. Do NOT use `Modifier.imePadding()` if the parent already accounts for the IME with `contentWindowInsets` (e.g. `contentWindowInsets = - WindowInsets.safeDrawing`). Doing so will cause double padding. + - 2. Add `imePadding` to the content container. The padding modifier **MUST** be placed before `Modifier.verticalScroll()`. Do NOT use `Modifier.imePadding()` if the parent already accounts for the IME with `contentWindowInsets` (e.g. `contentWindowInsets = WindowInsets.safeDrawing`). Doing so will cause double padding. ### IMEs with Scaffolds code patterns #### RIGHT -RIGHT because `contentWindowInsets` contains IME insets, which are passed to the -content lambda as `innerPadding`. - +RIGHT because `contentWindowInsets` contains IME insets, which are passed to the content lambda as `innerPadding`. ```kotlin // RIGHT @@ -130,15 +127,14 @@ Scaffold(contentWindowInsets = WindowInsets.safeDrawing) { innerPadding -> .verticalScroll(rememberScrollState()) ) { /* Content */ } } + ```
*** ** * ** *** -RIGHT because `fitInside` fits the content to the IME insets regardless of -`contentWindowInsets`. - +RIGHT because `fitInside` fits the content to the IME insets regardless of `contentWindowInsets`. ```kotlin // RIGHT @@ -151,15 +147,14 @@ Scaffold() { innerPadding -> .verticalScroll(rememberScrollState()) ) { /* Content */ } } + ```
*** ** * ** *** -RIGHT because the default `contentWindowInsets` does not contain IME insets, and -`imePadding()` applies IME insets: - +RIGHT because the default `contentWindowInsets` does not contain IME insets, and `imePadding()` applies IME insets: ```kotlin // RIGHT @@ -172,16 +167,14 @@ Scaffold() { innerPadding -> .verticalScroll(rememberScrollState()) ) { /* Content */ } } + ```
#### WRONG -WRONG because there will be excess padding when the IME opens. IME insets are -applied twice, once with innerPadding, which contains IME insets from the passed -`contentWindowInsets` values, and once with `imePadding`: - +WRONG because there will be excess padding when the IME opens. IME insets are applied twice, once with innerPadding, which contains IME insets from the passed `contentWindowInsets` values, and once with `imePadding`: ```kotlin // WRONG @@ -193,15 +186,14 @@ Scaffold( contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> .verticalScroll(rememberScrollState()) ) { /* Content */ } } + ```
*** ** * ** *** -WRONG because the IME will cover up the content. Scaffold's default -`contentWindowInsets` does NOT contain IME insets. - +WRONG because the IME will cover up the content. Scaffold's default `contentWindowInsets` does NOT contain IME insets. ```kotlin // WRONG @@ -212,6 +204,7 @@ Scaffold() { innerPadding -> .verticalScroll(rememberScrollState()) ) { /* Content */ } } + ```
@@ -222,7 +215,6 @@ Scaffold() { innerPadding -> The following code samples WILL NOT cause excessive padding. - ```kotlin // RIGHT Box( @@ -233,12 +225,14 @@ Box( modifier = Modifier.imePadding() ) { /* Content */ } } + ```
*** ** * ** *** +
```kotlin // RIGHT @@ -250,12 +244,14 @@ Box( modifier = Modifier.imePadding() ) { /* Content */ } } + ```
*** ** * ** *** +
```kotlin // RIGHT @@ -269,15 +265,14 @@ Box( .fitInside(WindowInsetsRulers.Ime.current) ) { /* Content */ } } + ```
#### WRONG -The following code sample WILL cause excessive padding because IME insets are -applied twice: - +The following code sample WILL cause excessive padding because IME insets are applied twice: ```kotlin // WRONG @@ -289,19 +284,16 @@ Box( modifier = Modifier.imePadding() ) { /* Content */ } } + ```
## Navigation Bar Contrast \& System Bar Icons -- If the Activity uses `enableEdgeToEdge` from `WindowCompat`, you **MUST** set - `isAppearanceLightNavigationBars` and `isAppearanceLightStatusBars` to the - inverse of the device theme for apps that support light and dark theme so the - system bar icons are legible. It's recommended to do this in your theme file. - DO NOT do this if the Activities use `enableEdgeToEdge` from `ComponentActivity` - because it handles the icon colors automatically. +- If the Activity uses `enableEdgeToEdge` from `WindowCompat`, you **MUST** set `isAppearanceLightNavigationBars` and `isAppearanceLightStatusBars` to the inverse of the device theme for apps that support light and dark theme so the system bar icons are legible. It's recommended to do this in your theme file. DO NOT do this if the Activities use `enableEdgeToEdge` from `ComponentActivity` because it handles the icon colors automatically. +
```kotlin // Only use if calling `enableEdgeToEdge` from `WindowCompat`. @@ -325,22 +317,19 @@ Box( MaterialTheme(content = content) } + ```
-- If any screen uses a `Scaffold` or a `NavigationSuiteScaffold` with a bottom - bar (e.g., `BottomAppBar`, `NavigationBar`), set - `window.isNavigationBarContrastEnforced = false` in the corresponding Activity - for SDK 29+. This prevents the system from adding a translucent background to - the navigation bar, verifying your bottom bar colors extend to the bottom of the - screen. +- If any screen uses a `Scaffold` or a `NavigationSuiteScaffold` with a bottom bar (e.g., `BottomAppBar`, `NavigationBar`), set `window.isNavigationBarContrastEnforced = false` in the corresponding Activity for SDK 29+. This prevents the system from adding a translucent background to the navigation bar, verifying your bottom bar colors extend to the bottom of the screen. ## Lists - Apply inset padding (like `Scaffold`'s `innerPadding`) to the `contentPadding` parameter of scrollable components (e.g. `LazyColumn`, `LazyRow`). DO NOT apply it as a `Modifier.padding()` to the list's parent container, as this clips the content and prevents it from scrolling behind the system bars. - Create a translucent composable covering the system bar so that the icons are still legible. +
```kotlin class SystemBarProtectionSnippets : ComponentActivity() { @@ -387,20 +376,18 @@ private fun StatusBarProtection( ) ) } + ```
## Dialogs -If both the following conditions are true, then the Dialog is full screen and -must be made edge-to-edge: -1. The `DialogProperties` contains `usePlatformDefaultWidth = false`. -2. The Dialog calls `Modifier.fillMaxSize()`. +If both the following conditions are true, then the Dialog is full screen and must be made edge-to-edge: 1. The `DialogProperties` contains `usePlatformDefaultWidth = false`. 2. The Dialog calls `Modifier.fillMaxSize()`. -To make a full screen Dialog edge-to-edge, set `decorFitsSystemWindows = false` -in the `DialogProperties`. +To make a full screen Dialog edge-to-edge, set `decorFitsSystemWindows = false` in the `DialogProperties`. +
```kotlin Dialog( @@ -412,6 +399,7 @@ Dialog( decorFitsSystemWindows = false ) ) { /* Content */ } + ```
diff --git a/testing/testing-setup/SKILL.md b/testing/testing-setup/SKILL.md index 31207c7..316e9d4 100644 --- a/testing/testing-setup/SKILL.md +++ b/testing/testing-setup/SKILL.md @@ -6,7 +6,7 @@ description: Analyze and create a testing strategy for native Android apps - ins license: Complete terms in LICENSE.txt metadata: author: Google LLC - last-updated: '2026-06-25' + last-updated: '2026-08-06' keywords: - android - testing @@ -17,8 +17,7 @@ metadata: ## Step 1: analyze the current testing setup -To understand the testing setup of an existing project, look for these -dependencies in the libs.versions.toml file, or build files: +To understand the testing setup of an existing project, look for these dependencies in the libs.versions.toml file, or build files: 1. Dependency Injection framework used. Examples: Hilt, Koin, Anvil, vanilla Dagger... 2. Unit (local) testing framework this project uses, Example JUnit4, JUnit5... @@ -40,35 +39,26 @@ dependencies in the libs.versions.toml file, or build files: ## Step 2: Set up Dependency Injection frameworks for testing -If there is no Dependency Injection framework, install one: if it's a -multiplatform application, ask the user whether they want to install Koin, or -kotlin-inject. If it's not multiplatform, install Hilt. +If there is no Dependency Injection framework, install one: if it's a multiplatform application, ask the user whether they want to install Koin, or kotlin-inject. If it's not multiplatform, install Hilt. -Install the testing dependencies (for example `com.google.dagger:hilt-compiler` -that should be applied with a `kspAndroidTest` configuration). +Install the testing dependencies (for example `com.google.dagger:hilt-compiler` that should be applied with a `kspAndroidTest` configuration). > [!IMPORTANT] > **Important:** Always consult the documentation of the applicable framework to learn about testing (for example: [Hilt testing guide](references/android/training/dependency-injection/hilt-testing.md), [Koin Instrumented tests](https://insert-koin.io/docs/reference/koin-android/instrumented-testing)). -For instrumented tests, create and configure (by adding -`testInstrumentationRunner` to the build gradle files) a new test runner and -apply the testing rules required by the framework (for example in Hilt, annotate -your test classes with `@HiltAndroidTest` and apply the `HiltAndroidRule`). -Other frameworks use other mechanisms, consult their documentation. +For instrumented tests, create and configure (by adding `testInstrumentationRunner` to the build gradle files) a new test runner and apply the testing rules required by the framework (for example in Hilt, annotate your test classes with `@HiltAndroidTest` and apply the `HiltAndroidRule`). Other frameworks use other mechanisms, consult their documentation. ## Step 3: Install frameworks Unless otherwise specified, respect the current stack of testing frameworks. -If there are no testing frameworks, and the user didn't specify any preference, -install the following: +If there are no testing frameworks, and the user didn't specify any preference, install the following: - JUnit4 for local and instrumented tests - Jacoco for test coverage - For UI tests: if the project has views, Espresso. If it's fully Compose, use the Compose Testing APIs. - Robolectric to run UI Tests -- Compose Preview Screenshot Testing tool for screenshot tests - check [setup - documentation](references/android/studio/preview/compose-screenshot-testing.md) and follow it strictly. +- Compose Preview Screenshot Testing tool for screenshot tests - check [setup documentation](references/android/studio/preview/compose-screenshot-testing.md) and follow it strictly. - Dropshots for device screenshot tests - If a mocking framework is necessary, install Mockk (`io.mockk:mockk`). Do not install it unless it is clearly necessary. @@ -80,43 +70,30 @@ If end-to-end testing is requested, install UI Automator. ### **Refactor for unit tests** -In the next sections you'll be asked to create tests. If you have dependencies -on Android framework classes, or entities that are not part of the codebase: +In the next sections you'll be asked to create tests. If you have dependencies on Android framework classes, or entities that are not part of the codebase: -- First, use a fake. If it doesn't exist, create an interface for the class - and a "Default" implementation with the existing code. Add the Fake version - to the test sourceset (test or androidTest). +- First, use a fake. If it doesn't exist, create an interface for the class and a "Default" implementation with the existing code. Add the Fake version to the test sourceset (test or androidTest). -- If not possible to use a fake (example: no access to the class or - interface), mock the dependencies. +- If not possible to use a fake (example: no access to the class or interface), mock the dependencies. ### **Refactor for UI tests** -If you need to fake components to make testing easier and faster and more -reliable, replace slow and problematic dependencies with fakes. Use runtime -fakes using the Dependency Injection framework installed to: +If you need to fake components to make testing easier and faster and more reliable, replace slow and problematic dependencies with fakes. Use runtime fakes using the Dependency Injection framework installed to: - **Simulate** different scenarios with the user (wrong credentials, reset password flow...), with a server (no connection, server down, bad JSON from server...) or with a platform component (insufficient permissions, no disk space, no front camera available) - **Improve** speed and reliability (replacing a database with an in-memory database, replacing a repository with an in-memory fake to avoid hitting the network) ## Step 5: Unit testing -Create a task to add or review unit tests in every file that contains business -logic (ViewModels, Repositories, database-related classes such as DAOs, etc.). -Don't create unit tests for Activities, Compose layouts, or dependency injection -configuration files. +Create a task to add or review unit tests in every file that contains business logic (ViewModels, Repositories, database-related classes such as DAOs, etc.). Don't create unit tests for Activities, Compose layouts, or dependency injection configuration files. ## Step 6: UI testing -Espresso or Compose UI tests live in the `test` sourceset because they will be -run with Robolectric. If instrumented (emulator or device) tests are requested, -put them in the `androidTest` sourceset. +Espresso or Compose UI tests live in the `test` sourceset because they will be run with Robolectric. If instrumented (emulator or device) tests are requested, put them in the `androidTest` sourceset. ## Step 7: Test databases -If the database is using SQLite (using Room, SQLDelight, etc.), create -instrumented tests using an in-memory database to make sure that they work with -the SQLite engine on device. +If the database is using SQLite (using Room, SQLDelight, etc.), create instrumented tests using an in-memory database to make sure that they work with the SQLite engine on device. ## Step 8: Screenshot tests @@ -128,14 +105,11 @@ Irrespective of the framework used, screenshot tests focus on 2 types of tests: - Font scale set to 1.5. - Component-level screenshot tests, where each component is tested in different themes and font scales. -Behavior isn't tested with screenshots, but do test different common scenarios -if their UIs change a lot depending on the state. For example, test loading -screens by injecting a loading state to the UI or simulating it with a fake. +Behavior isn't tested with screenshots, but do test different common scenarios if their UIs change a lot depending on the state. For example, test loading screens by injecting a loading state to the UI or simulating it with a fake. ## Step 9: UI Behavior tests -Test the UI logic using behavior tests, which ensures that the UIs react as -expected when different states are passed, and when user actions are performed. +Test the UI logic using behavior tests, which ensures that the UIs react as expected when different states are passed, and when user actions are performed. ### **Compose UI behavior tests** @@ -157,25 +131,17 @@ Create a test suite to verify navigation logic. Include: ## Step 11: Simulate different window sizes and settings -For Compose layouts, use `DeviceConfigurationOverride` described in "[UI testing -common patterns](references/android/develop/ui/compose/testing/common-patterns.md)" to simulate different window sizes, font scales +For Compose layouts, use `DeviceConfigurationOverride` described in "[UI testing common patterns](references/android/develop/ui/compose/testing/common-patterns.md)" to simulate different window sizes, font scales ## Step 12: End-to-end tests -Create a low number (about 5% of all tests) of end-to-end tests that cover big -user journeys. Use Compose Test APIs or Espresso for that. If you have to access -platform features (notifications, system UI...), use UI Automator. +Create a low number (about 5% of all tests) of end-to-end tests that cover big user journeys. Use Compose Test APIs or Espresso for that. If you have to access platform features (notifications, system UI...), use UI Automator. -If you need to take screenshots of the app running in a device, use -[Dropshots](https://raw.githubusercontent.com/dropbox/dropshots/refs/heads/main/README.md). You need a device for screenshot tests when verifying -interaction with the system UI (examples: edge-to-edge rendering, notifications, -picture-in-picture) +If you need to take screenshots of the app running in a device, use [Dropshots](https://raw.githubusercontent.com/dropbox/dropshots/refs/heads/main/README.md). You need a device for screenshot tests when verifying interaction with the system UI (examples: edge-to-edge rendering, notifications, picture-in-picture) ### Step 13: Instrumented Screenshot tests -Install the `com.dropbox.dropshots` plugin in the module and a `Dropshots()` -JUnit Rule. Create a new instrumented screenshot test for one of the app's -features. +Install the `com.dropbox.dropshots` plugin in the module and a `Dropshots()` JUnit Rule. Create a new instrumented screenshot test for one of the app's features. ### Step 14: Install jacoco @@ -185,14 +151,8 @@ Install jacoco for local testing code coverage. ## Final touches -- Ask whether to document the findings of the analysis and the changes applied - to the testing strategy. If the user agrees: +- Ask whether to document the findings of the analysis and the changes applied to the testing strategy. If the user agrees: - - If there is an AGENTS.md file present in the project, update it with any - changes you've made to the testing strategy. + - If there is an AGENTS.md file present in the project, update it with any changes you've made to the testing strategy. - - If there is no AGENTS.md file, create a new file (docs/testing.md) with - a description of the testing strategy, including the commands needed to - run every type of test, where the screenshot reference files live, etc. - Also create a new AGENTS.md file in the root and create a link to - docs/testing.md. + - If there is no AGENTS.md file, create a new file (docs/testing.md) with a description of the testing strategy, including the commands needed to run every type of test, where the screenshot reference files live, etc. Also create a new AGENTS.md file in the root and create a link to docs/testing.md. diff --git a/testing/testing-setup/references/android/develop/ui/compose/testing/common-patterns.md b/testing/testing-setup/references/android/develop/ui/compose/testing/common-patterns.md index 1bea76b..f0b2f75 100644 --- a/testing/testing-setup/references/android/develop/ui/compose/testing/common-patterns.md +++ b/testing/testing-setup/references/android/develop/ui/compose/testing/common-patterns.md @@ -4,24 +4,15 @@ You can test your Compose app with well-established approaches and patterns. ### Test in isolation -[`ComposeTestRule`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/junit4/ComposeTestRule) lets you start an activity displaying any composable: -your full application, a single screen, or a small element. It's also a good -practice to check that your composables are correctly encapsulated and they work -independently, allowing for easier and more focused UI testing. +[`ComposeTestRule`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/junit4/ComposeTestRule) lets you start an activity displaying any composable: your full application, a single screen, or a small element. It's also a good practice to check that your composables are correctly encapsulated and they work independently, allowing for easier and more focused UI testing. -This doesn't mean you should *only* create unit UI tests. UI tests scoping -larger parts of your UI are also very important. +This doesn't mean you should *only* create unit UI tests. UI tests scoping larger parts of your UI are also very important. ### Access the activity and resources after setting your own content -Oftentimes you need to set the content under test using -`composeTestRule.setContent` and you also need to access activity resources, for -example to assert that a displayed text matches a string resource. However, you -can't call `setContent` on a rule created with `createAndroidComposeRule()` if -the activity already calls it. +Oftentimes you need to set the content under test using `composeTestRule.setContent` and you also need to access activity resources, for example to assert that a displayed text matches a string resource. However, you can't call `setContent` on a rule created with `createAndroidComposeRule()` if the activity already calls it. -A common pattern to achieve this is to create an `AndroidComposeTestRule` using -an empty activity such as [`ComponentActivity`](https://developer.android.com/reference/androidx/activity/ComponentActivity). +A common pattern to achieve this is to create an `AndroidComposeTestRule` using an empty activity such as [`ComponentActivity`](https://developer.android.com/reference/androidx/activity/ComponentActivity). class MyComposeTest { @@ -41,17 +32,13 @@ an empty activity such as [`ComponentActivity`](https://developer.android.com/re } } -Note that `ComponentActivity` needs to be added to your app's -`AndroidManifest.xml` file. Enable that by adding this dependency to your -module: +Note that `ComponentActivity` needs to be added to your app's `AndroidManifest.xml` file. Enable that by adding this dependency to your module: debugImplementation("androidx.compose.ui:ui-test-manifest:$compose_version") ### Custom semantics properties -You can create custom [semantics](https://developer.android.com/develop/ui/compose/testing/semantics) properties to expose information to tests. -To do this, define a new `SemanticsPropertyKey` and make it available using the -`SemanticsPropertyReceiver`. +You can create custom [semantics](https://developer.android.com/develop/ui/compose/testing/semantics) properties to expose information to tests. To do this, define a new `SemanticsPropertyKey` and make it available using the `SemanticsPropertyReceiver`. // Creates a semantics property of type Long. val PickedDateKey = SemanticsPropertyKey("PickedDate") @@ -64,8 +51,7 @@ Now use that property in the `semantics` modifier: modifier = Modifier.semantics { pickedDate = datePickerValue } ) -From tests, use `SemanticsMatcher.expectValue` to assert the value of the -property: +From tests, use `SemanticsMatcher.expectValue` to assert the value of the property: composeTestRule .onNode(SemanticsMatcher.expectValue(PickedDateKey, 1445378400)) // 2015-10-21 @@ -76,12 +62,9 @@ property: ### Verify state restoration -Verify that the state of your Compose elements is correctly restored when the -activity or process is recreated. Perform such checks without relying on -activity recreation with the [`StateRestorationTester`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/junit4/StateRestorationTester) class. +Verify that the state of your Compose elements is correctly restored when the activity or process is recreated. Perform such checks without relying on activity recreation with the [`StateRestorationTester`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/junit4/StateRestorationTester) class. -This class lets you simulate the recreation of a composable. It's especially -useful to verify the implementation of [`rememberSaveable`](https://developer.android.com/reference/kotlin/androidx/compose/runtime/saveable/rememberSaveable.composable#rememberSaveable(kotlin.Array,androidx.compose.runtime.saveable.Saver,kotlin.String,kotlin.Function0)). +This class lets you simulate the recreation of a composable. It's especially useful to verify the implementation of [`rememberSaveable`](https://developer.android.com/reference/kotlin/androidx/compose/runtime/saveable/rememberSaveable.composable#rememberSaveable(kotlin.Array,androidx.compose.runtime.saveable.Saver,kotlin.String,kotlin.Function0)). class MyStateRestorationTests { @@ -106,40 +89,25 @@ useful to verify the implementation of [`rememberSaveable`](https://developer.an ### Test different device configurations -Android apps need to adapt to many changing conditions: window sizes, locales, -font sizes, dark and light themes, and more. Most of these conditions are -derived from device-level values controlled by the user and exposed with the -current [`Configuration`](https://developer.android.com/reference/android/content/res/Configuration) instance. Testing different configurations -directly in a test is difficult since the test must configure device-level -properties. +Android apps need to adapt to many changing conditions: window sizes, locales, font sizes, dark and light themes, and more. Most of these conditions are derived from device-level values controlled by the user and exposed with the current [`Configuration`](https://developer.android.com/reference/android/content/res/Configuration) instance. Testing different configurations directly in a test is difficult since the test must configure device-level properties. -[`DeviceConfigurationOverride`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride) is a test-only API that lets you simulate -different device configurations in a localized way for the `@Composable` content -under test. +[`DeviceConfigurationOverride`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride) is a test-only API that lets you simulate different device configurations in a localized way for the `@Composable` content under test. -The companion object of `DeviceConfigurationOverride` has the following -extension functions, which override device-level configuration properties: +The companion object of `DeviceConfigurationOverride` has the following extension functions, which override device-level configuration properties: - [`DeviceConfigurationOverride.DarkMode()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.Companion#(androidx.compose.ui.test.DeviceConfigurationOverride.Companion).DarkMode(kotlin.Boolean)): Overrides the system to dark theme or light theme. -- [`DeviceConfigurationOverride.FontScale()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.Companion#(androidx.compose.ui.test.DeviceConfigurationOverride.Companion).FontScale(kotlin.Float)): Overrides the [system font - scale](https://developer.android.com/training/multiscreen/screendensities#TaskUseDP). +- [`DeviceConfigurationOverride.FontScale()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.Companion#(androidx.compose.ui.test.DeviceConfigurationOverride.Companion).FontScale(kotlin.Float)): Overrides the [system font scale](https://developer.android.com/training/multiscreen/screendensities#TaskUseDP). - [`DeviceConfigurationOverride.FontWeightAdjustment()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.Companion#(androidx.compose.ui.test.DeviceConfigurationOverride.Companion).FontWeightAdjustment(kotlin.Int)): Overrides the system font weight adjustment. - [`DeviceConfigurationOverride.ForcedSize()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.Companion#(androidx.compose.ui.test.DeviceConfigurationOverride.Companion).ForcedSize(androidx.compose.ui.unit.DpSize)): Forces a specific amount of space regardless of device size. -- [`DeviceConfigurationOverride.LayoutDirection()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.Companion#(androidx.compose.ui.test.DeviceConfigurationOverride.Companion).LayoutDirection(androidx.compose.ui.unit.LayoutDirection)): Overrides the [layout - direction](https://developer.android.com/training/basics/supporting-devices/languages#SupportLayoutMirroring) (left-to-right or right-to-left). +- [`DeviceConfigurationOverride.LayoutDirection()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.Companion#(androidx.compose.ui.test.DeviceConfigurationOverride.Companion).LayoutDirection(androidx.compose.ui.unit.LayoutDirection)): Overrides the [layout direction](https://developer.android.com/training/basics/supporting-devices/languages#SupportLayoutMirroring) (left-to-right or right-to-left). - [`DeviceConfigurationOverride.Locales()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.Companion#(androidx.compose.ui.test.DeviceConfigurationOverride.Companion).Locales(androidx.compose.ui.text.intl.LocaleList)): Overrides the [locale](https://developer.android.com/guide/topics/resources/localization). - [`DeviceConfigurationOverride.RoundScreen()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.Companion#(androidx.compose.ui.test.DeviceConfigurationOverride.Companion).RoundScreen(kotlin.Boolean)): Overrides if the screen is [round](https://developer.android.com/design/ui/wear/guides/foundations/getting-started#design-for-round). -To apply a specific override, wrap the content under test in a call to the -[`DeviceConfigurationOverride()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.composable#DeviceConfigurationOverride(androidx.compose.ui.test.DeviceConfigurationOverride,kotlin.Function0)) top-level function, passing the override -to apply as a parameter. +To apply a specific override, wrap the content under test in a call to the [`DeviceConfigurationOverride()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride.composable#DeviceConfigurationOverride(androidx.compose.ui.test.DeviceConfigurationOverride,kotlin.Function0)) top-level function, passing the override to apply as a parameter. -For example, the following code applies the -`DeviceConfigurationOverride.ForcedSize()` override to change the density -locally, forcing the `MyScreen` composable to be rendered in a large landscape -window, even if the device the test is running on doesn't support that window -size directly: +For example, the following code applies the `DeviceConfigurationOverride.ForcedSize()` override to change the density locally, forcing the `MyScreen` composable to be rendered in a large landscape window, even if the device the test is running on doesn't support that window size directly: +
```kotlin composeTestRule.setContent { @@ -149,13 +117,14 @@ composeTestRule.setContent { MyScreen() // Will be rendered in the space for 1280dp by 800dp without clipping. } } + ```
-To apply multiple overrides together, use -[`DeviceConfigurationOverride.then()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride#(androidx.compose.ui.test.DeviceConfigurationOverride).then(androidx.compose.ui.test.DeviceConfigurationOverride)): +To apply multiple overrides together, use [`DeviceConfigurationOverride.then()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/test/DeviceConfigurationOverride#(androidx.compose.ui.test.DeviceConfigurationOverride).then(androidx.compose.ui.test.DeviceConfigurationOverride)): +
```kotlin composeTestRule.setContent { @@ -166,6 +135,7 @@ composeTestRule.setContent { Text(text = "text with increased scale and weight") } } + ```
diff --git a/testing/testing-setup/references/android/studio/preview/compose-screenshot-testing.md b/testing/testing-setup/references/android/studio/preview/compose-screenshot-testing.md index b1f7876..391510e 100644 --- a/testing/testing-setup/references/android/studio/preview/compose-screenshot-testing.md +++ b/testing/testing-setup/references/android/studio/preview/compose-screenshot-testing.md @@ -1,16 +1,9 @@ > [!WARNING] > **Experimental:** Compose Preview Screenshot Testing is still in development. Its features and APIs are subject to change substantially during the alpha phase. Report any feedback and issues through the [issue tracker](https://issuetracker.google.com/issues/new?component=192708&template=840533). -Screenshot testing is an effective way to verify how your UI looks to users. -The Compose Preview Screenshot Testing tool combines the simplicity and -features of [composable previews](https://developer.android.com/develop/ui/compose/tooling/previews) with the productivity -gains of running host-side screenshot tests. Compose Preview Screenshot Testing -is designed to be as straightforward to use as composable previews. +Screenshot testing is an effective way to verify how your UI looks to users. The Compose Preview Screenshot Testing tool combines the simplicity and features of [composable previews](https://developer.android.com/develop/ui/compose/tooling/previews) with the productivity gains of running host-side screenshot tests. Compose Preview Screenshot Testing is designed to be as straightforward to use as composable previews. -A screenshot test is an automated test that takes a screenshot of a piece of UI -and then compares it against a previously approved reference image. If the -images don't match, the test fails and produces an HTML report to help you -compare and find the differences. +A screenshot test is an automated test that takes a screenshot of a piece of UI and then compares it against a previously approved reference image. If the images don't match, the test fails and produces an HTML report to help you compare and find the differences. With the Compose Preview Screenshot Testing tool, you can: @@ -24,31 +17,30 @@ With the Compose Preview Screenshot Testing tool, you can: ## IDE integration -While you can use the Compose Preview Screenshot Testing tool by running the -underlying Gradle tasks (`updateScreenshotTest` and `validateScreenshotTest`) -manually, Android Studio Otter 3 Feature Drop Canary 4 introduces a full IDE -integration. This lets you generate reference images, run tests, and analyze -validation failures entirely within the IDE. Here are some of the key features: +While you can use the Compose Preview Screenshot Testing tool by running the underlying Gradle tasks (`updateScreenshotTest` and `validateScreenshotTest`) manually, Android Studio Otter 3 Feature Drop Canary 4 introduces a full IDE integration. This lets you generate reference images, run tests, and analyze validation failures entirely within the IDE. Here are some of the key features: - **In-editor gutter icons.** You can now run tests or update reference images directly from the source code. Green run icons appear in the gutter next to composables and classes annotated with `@PreviewTest`. - **Run screenshot tests.** Execute tests specifically for a single function or for an entire class. - **Add or update reference images.** Trigger the update flow specifically for the selected scope. + - **Interactive reference management.** Updating reference images is now safer and more granular. - **New reference image generation dialog.** Instead of running a bulk Gradle task, a new dialog lets you visualize and select exactly which previews to generate or update. - **Preview variations.** The dialog lists all preview variations (such as light theme or dark theme, or different devices) individually, allowing you to select or clear specific items before generating images. + - **Integrated test results and diff viewer.** View results without leaving the IDE. - **Unified run panel.** Screenshot test results appear in the standard **Run** tool window. Tests are grouped by class and function, with pass or fail status clearly marked. - **Visual diff tool.** When a test fails, the **Screenshot** tab lets you compare the *Reference* , *Actual* , and *Diff* images side-by-side. - **Detailed attributes.** An **Attributes** tab provides metadata on failed tests, including match percentage, image dimensions, and the specific preview configuration used (for example, `uiMode` or `fontScale`). + - **Flexible test scoping.** You can now execute screenshot tests with various scopes directly from the Project View. Right-click a module, directory, file, or class to run screenshot tests specifically for that selection. + ## Requirements -To use Compose Preview Screenshot Testing through the full IDE integration, your -project must meet the following requirements: +To use Compose Preview Screenshot Testing through the full IDE integration, your project must meet the following requirements: - Android Studio Panda 1 Canary 4 or higher. - Android Gradle Plugin (AGP) version 9.0 or higher. @@ -57,8 +49,7 @@ project must meet the following requirements: - JDK version 17 or higher. - Compose enabled for your project. We recommend enabling Compose using the [Compose Compiler Gradle plugin](https://developer.android.com/develop/ui/compose/compiler). -If you only want to use the underlying Gradle tasks without the IDE integration, -the requirements are as follows: +If you only want to use the underlying Gradle tasks without the IDE integration, the requirements are as follows: - Android Gradle Plugin (AGP) version 8.5.0 or higher. - Compose Preview Screenshot Testing plugin version [0.0.1-alpha15](https://developer.android.com/studio/preview/compose-screenshot-testing-release-notes#alpha15) or higher. @@ -71,22 +62,19 @@ the requirements are as follows: ## Setup -Both the integrated tool and the underlying Gradle tasks rely on the Compose -Preview Screenshot Testing plugin. To set up the plugin, follow these steps: +Both the integrated tool and the underlying Gradle tasks rely on the Compose Preview Screenshot Testing plugin. To set up the plugin, follow these steps: 1. Enable the experimental property in your project's `gradle.properties` file. android.experimental.enableScreenshotTest=true -2. In the `android {}` block of your module-level `build.gradle.kts` file, - enable the experimental flag to use the `screenshotTest` source set. +2. In the `android {}` block of your module-level `build.gradle.kts` file, enable the experimental flag to use the `screenshotTest` source set. android { experimentalProperties["android.experimental.enableScreenshotTest"] = true } -3. Add the `com.android.compose.screenshot` plugin, version `0.0.1-alpha15` to - your project. +3. Add the `com.android.compose.screenshot` plugin, version `0.0.1-alpha15` to your project. 1. Add the plugin to your version catalogs file: @@ -98,16 +86,13 @@ Preview Screenshot Testing plugin. To set up the plugin, follow these steps: [plugins] screenshot = { id = "com.android.compose.screenshot", version.ref = "screenshot"} - 2. In your module-level `build.gradle.kts` file, add the plugin in the - `plugins {}` block: + 2. In your module-level `build.gradle.kts` file, add the plugin in the `plugins {}` block: plugins { alias(libs.plugins.screenshot) } -4. Add the [`screenshot-validation-api`](https://maven.google.com/web/index.html?q=screenshot-validation-api#com.android.tools.screenshot:screenshot-validation-api) - and [`ui-tooling`](https://maven.google.com/web/index.html?q=tooling#androidx.compose.ui:ui-tooling) - dependencies. +4. Add the [`screenshot-validation-api`](https://maven.google.com/web/index.html?q=screenshot-validation-api#com.android.tools.screenshot:screenshot-validation-api) and [`ui-tooling`](https://maven.google.com/web/index.html?q=tooling#androidx.compose.ui:ui-tooling) dependencies. 1. Add them to your version catalogs: @@ -124,15 +109,11 @@ Preview Screenshot Testing plugin. To set up the plugin, follow these steps: ## Designate composable previews to use for screenshot tests -To designate the composable previews you want to use for screenshot tests, mark -the previews with the `@PreviewTest` annotation. The previews must be located in -the new `screenshotTest` source set, for example: +To designate the composable previews you want to use for screenshot tests, mark the previews with the `@PreviewTest` annotation. The previews must be located in the new `screenshotTest` source set, for example: -`app/src/screenshotTest/kotlin/com/example/yourapp/` -`ExamplePreviewScreenshotTest.kt` +`app/src/screenshotTest/kotlin/com/example/yourapp/` `ExamplePreviewScreenshotTest.kt` -You can add more composables or previews, including multi-previews, in -this file or other files created in the same source set. +You can add more composables or previews, including multi-previews, in this file or other files created in the same source set. package com.example.yourapp @@ -152,16 +133,11 @@ this file or other files created in the same source set. ## Generate reference images -After you set up a test class, you need to generate reference images for each -preview. These reference images are used to identify changes later, after you -make code changes. To generate reference images for your composable preview -screenshot tests, follow the instructions in this section for the IDE -integration or for the Gradle tasks. +After you set up a test class, you need to generate reference images for each preview. These reference images are used to identify changes later, after you make code changes. To generate reference images for your composable preview screenshot tests, follow the instructions in this section for the IDE integration or for the Gradle tasks. ### In the IDE -Click the gutter icon next to a `@PreviewTest` function and select **Add/Update -Reference Images** . Select the previews in the dialog and click **Add**. +Click the gutter icon next to a `@PreviewTest` function and select **Add/Update Reference Images** . Select the previews in the dialog and click **Add**. ### With the Gradle tasks @@ -170,46 +146,36 @@ Run the following Gradle task: - Linux and macOS: `./gradlew updateDebugScreenshotTest` (`./gradlew :{module}:update{Variant}ScreenshotTest`) - Windows: `gradlew updateDebugScreenshotTest` (`gradlew :{module}:update{Variant}ScreenshotTest`) -After the task completes, find the reference images in -`app/src/screenshotTestDebug/reference` -(`{module}/src/screenshotTest{Variant}/reference`). +After the task completes, find the reference images in `app/src/screenshotTestDebug/reference` (`{module}/src/screenshotTest{Variant}/reference`). > [!NOTE] > **Note:** The reference images are named with a concatenation of the fully-qualified name of the test function and a hash of the preview parameters, for example `com.sample.screenshottests.test1_da39a3ee_c2200e98_0.png`. ## Generate a test report -Once the reference images exist, generate a test report by following the -instructions in this section for the IDE integration or for the Gradle tasks. +Once the reference images exist, generate a test report by following the instructions in this section for the IDE integration or for the Gradle tasks. ### In the IDE -Click the gutter icon next to a `@PreviewTest` function and select **Run -'ScreenshotTests'**. +Click the gutter icon next to a `@PreviewTest` function and select **Run 'ScreenshotTests'**. -If a test fails, click the test name in the **Run** panel. Select the -**Screenshot** tab to inspect the image diff using the integrated zoom and pan -controls. +If a test fails, click the test name in the **Run** panel. Select the **Screenshot** tab to inspect the image diff using the integrated zoom and pan controls. > [!NOTE] > **Note:** Renaming a function annotated with `@PreviewTest` breaks the association with existing reference images. In that case, you must [regenerate reference images](https://developer.android.com/studio/preview/compose-screenshot-testing#generate-reference-images) for the new function name. ### With the Gradle tasks -Run the validate task to take a new screenshot and compare it with the -reference image: +Run the validate task to take a new screenshot and compare it with the reference image: - Linux and macOS: `./gradlew validateDebugScreenshotTest` (`./gradlew :{module}:validate{Variant}ScreenshotTest`) - Windows: `gradlew validateDebugScreenshotTest` (`gradlew :{module}:validate{Variant}ScreenshotTest`) -The verification task creates an HTML report at -`{module}/build/reports/screenshotTest/preview/{variant}/index.html`. +The verification task creates an HTML report at `{module}/build/reports/screenshotTest/preview/{variant}/index.html`. ## Troubleshooting -Compose Preview Screenshot Testing runs host-side tests, which can be -memory-intensive. You can increase the maximum heap size for the test JVM by -adding the following property to your `gradle.properties` file: +Compose Preview Screenshot Testing runs host-side tests, which can be memory-intensive. You can increase the maximum heap size for the test JVM by adding the following property to your `gradle.properties` file: android.compose.screenshot.maxHeapSize=4g @@ -217,11 +183,8 @@ adding the following property to your `gradle.properties` file: - **Kotlin Multiplatform (KMP):** Both the IDE and the underlying plugin are engineered exclusively for Android projects. They don't support non-Android targets in KMP projects. -You can find the complete list of current known issues in the tool's -[issue tracker component](https://issuetracker.google.com/issues?q=status:open+componentid:1581441&s=created_time:desc). Report any other feedback and issues -through the [issue tracker](https://issuetracker.google.com/issues/new?component=192708&template=840533). +You can find the complete list of current known issues in the tool's [issue tracker component](https://issuetracker.google.com/issues?q=status:open+componentid:1581441&s=created_time:desc). Report any other feedback and issues through the [issue tracker](https://issuetracker.google.com/issues/new?component=192708&template=840533). ## Release updates -For a full list of release updates, see the -[release notes](https://developer.android.com/studio/preview/compose-screenshot-testing-release-notes). \ No newline at end of file +For a full list of release updates, see the [release notes](https://developer.android.com/studio/preview/compose-screenshot-testing-release-notes). \ No newline at end of file diff --git a/testing/testing-setup/references/android/training/dependency-injection/hilt-testing.md b/testing/testing-setup/references/android/training/dependency-injection/hilt-testing.md index 022bf07..e1fe4ac 100644 --- a/testing/testing-setup/references/android/training/dependency-injection/hilt-testing.md +++ b/testing/testing-setup/references/android/training/dependency-injection/hilt-testing.md @@ -1,12 +1,8 @@ -One of the benefits of using dependency injection frameworks like Hilt is that -it makes testing your code easier. +One of the benefits of using dependency injection frameworks like Hilt is that it makes testing your code easier. ## Unit tests -Hilt isn't necessary for unit tests, since when testing a class that uses -constructor injection, you don't need to use Hilt to instantiate that class. -Instead, you can directly call a class constructor by passing in fake or mock -dependencies, just as you would if the constructor weren't annotated: +Hilt isn't necessary for unit tests, since when testing a class that uses constructor injection, you don't need to use Hilt to instantiate that class. Instead, you can directly call a class constructor by passing in fake or mock dependencies, just as you would if the constructor weren't annotated: ```kotlin @ActivityScoped @@ -26,21 +22,15 @@ class AnalyticsAdapterTest { } ``` -The same applies to ViewModel classes obtained by calling `hiltViewModel()` in -your composables. In unit tests, construct the ViewModel directly with fakes. -For information on how state flows from a ViewModel into composables, see -[State and Jetpack Compose](https://developer.android.com/develop/ui/compose/state) and [Where to hoist state](https://developer.android.com/develop/ui/compose/state-hoisting). +The same applies to ViewModel classes obtained by calling `hiltViewModel()` in your composables. In unit tests, construct the ViewModel directly with fakes. For information on how state flows from a ViewModel into composables, see [State and Jetpack Compose](https://developer.android.com/develop/ui/compose/state) and [Where to hoist state](https://developer.android.com/develop/ui/compose/state-hoisting). ## End-to-end tests -For integration tests, Hilt injects dependencies as it would in your production -code. Testing with Hilt requires no maintenance because Hilt automatically -generates a new set of components for each test. +For integration tests, Hilt injects dependencies as it would in your production code. Testing with Hilt requires no maintenance because Hilt automatically generates a new set of components for each test. ### Adding testing dependencies -To use Hilt in your tests, include the `hilt-android-testing` dependency in your -project: +To use Hilt in your tests, include the `hilt-android-testing` dependency in your project: ```kotlin dependencies { @@ -64,11 +54,9 @@ dependencies { ### UI test setup -You must annotate any UI test that uses Hilt with `@HiltAndroidTest`. This -annotation is responsible for generating the Hilt components for each test. +You must annotate any UI test that uses Hilt with `@HiltAndroidTest`. This annotation is responsible for generating the Hilt components for each test. -Also, you need to add the `HiltAndroidRule` to the test class. It manages the -components' state and is used to perform injection on your test: +Also, you need to add the `HiltAndroidRule` to the test class. It manages the components' state and is used to perform injection on your test: ```kotlin @HiltAndroidTest @@ -85,36 +73,21 @@ class SettingsScreenTest { ``` > [!NOTE] -> **Note:** If you have other rules in your test, see [Multiple TestRule objects in -> your instrumented test](https://developer.android.com/training/dependency-injection/hilt-testing#multiple-testrules). +> **Note:** If you have other rules in your test, see [Multiple TestRule objects in your instrumented test](https://developer.android.com/training/dependency-injection/hilt-testing#multiple-testrules). -Next, your test needs to know about the `Application` class that Hilt -automatically generates for you. +Next, your test needs to know about the `Application` class that Hilt automatically generates for you. -To let Hilt inject dependencies, you must create an empty activity named -`HiltTestActivity` in your `androidTest` source set and annotate it with -`@AndroidEntryPoint`. `createAndroidComposeRule` then uses this activity as the -host for your composable content. +To let Hilt inject dependencies, you must create an empty activity named `HiltTestActivity` in your `androidTest` source set and annotate it with `@AndroidEntryPoint`. `createAndroidComposeRule` then uses this activity as the host for your composable content. #### Test application -You must execute instrumented tests that use Hilt in an `Application` object -that supports Hilt. The library provides `HiltTestApplication` for use in tests. -If your tests need a different base application, see [Custom application for -tests](https://developer.android.com/training/dependency-injection/hilt-testing#custom-application). +You must execute instrumented tests that use Hilt in an `Application` object that supports Hilt. The library provides `HiltTestApplication` for use in tests. If your tests need a different base application, see [Custom application for tests](https://developer.android.com/training/dependency-injection/hilt-testing#custom-application). -You must set your test application to run in your [instrumented -tests](https://developer.android.com/training/testing/ui-testing) or [Robolectric -tests](http://robolectric.org/). The following instructions aren't -specific to Hilt, but are general guidelines on how to specify a custom -application to run in tests. +You must set your test application to run in your [instrumented tests](https://developer.android.com/training/testing/ui-testing) or [Robolectric tests](http://robolectric.org/). The following instructions aren't specific to Hilt, but are general guidelines on how to specify a custom application to run in tests. ##### Set the test application in instrumented tests -To use the Hilt test application in [instrumented -tests](https://developer.android.com/training/testing/ui-testing), you need to configure a new test runner. -This makes Hilt work for all of the instrumented tests in your project. Perform -the following steps: +To use the Hilt test application in [instrumented tests](https://developer.android.com/training/testing/ui-testing), you need to configure a new test runner. This makes Hilt work for all of the instrumented tests in your project. Perform the following steps: 1. Create a custom class that extends [`AndroidJUnitRunner`](https://developer.android.com/reference/kotlin/androidx/test/runner/AndroidJUnitRunner) in the `androidTest` folder. 2. Override the `newApplication` function and pass in the name of the generated Hilt test application. @@ -129,10 +102,7 @@ class CustomTestRunner : AndroidJUnitRunner() { } ``` -Next, configure this test runner in your Gradle file as described in the -[instrumented unit test -guide](https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests#setup). Make sure -you use the full classpath: +Next, configure this test runner in your Gradle file as described in the [instrumented unit test guide](https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests#setup). Make sure you use the full classpath: ```kotlin android { @@ -145,13 +115,11 @@ android { ##### Set the test application in Robolectric tests -If you use Robolectric to test your UI layer, you can specify which application -to use in the `robolectric.properties` file: +If you use Robolectric to test your UI layer, you can specify which application to use in the `robolectric.properties` file: `application = dagger.hilt.android.testing.HiltTestApplication` -Alternatively, you can configure the application on each test individually by -using Robolectric's `@Config` annotation: +Alternatively, you can configure the application on each test individually by using Robolectric's `@Config` annotation: ```kotlin @HiltAndroidTest @@ -167,13 +135,11 @@ class SettingsScreenTest { ### Testing features -Once Hilt is ready to use in your tests, you can use several features to -customize the testing process. +Once Hilt is ready to use in your tests, you can use several features to customize the testing process. #### Inject types in tests -To inject types into a test, use `@Inject` for field injection. To tell Hilt to -populate the `@Inject` fields, call `hiltRule.inject()`. +To inject types into a test, use `@Inject` for field injection. To tell Hilt to populate the `@Inject` fields, call `hiltRule.inject()`. See the following example of an instrumented test: @@ -208,14 +174,9 @@ class SettingsScreenTest { #### Replace a binding -If you need to inject a fake or mock instance of a dependency, you need to tell -Hilt not to use the binding that it used in production code and to use a -different one instead. To replace a binding, you need to replace the module that -contains the binding with a test module that contains the bindings that you want -to use in the test. +If you need to inject a fake or mock instance of a dependency, you need to tell Hilt not to use the binding that it used in production code and to use a different one instead. To replace a binding, you need to replace the module that contains the binding with a test module that contains the bindings that you want to use in the test. -For example, suppose your production code declares a binding for -`AnalyticsService` as follows: +For example, suppose your production code declares a binding for `AnalyticsService` as follows: ```kotlin @Module @@ -230,10 +191,7 @@ abstract class AnalyticsModule { } ``` -To replace the `AnalyticsService` binding in tests, create a new Hilt module in -the `test` or `androidTest` folder with the fake dependency and annotate it -with `@TestInstallIn`. All the tests in that folder are injected with the fake -dependency instead. +To replace the `AnalyticsService` binding in tests, create a new Hilt module in the `test` or `androidTest` folder with the fake dependency and annotate it with `@TestInstallIn`. All the tests in that folder are injected with the fake dependency instead. ```kotlin @Module @@ -251,19 +209,13 @@ abstract class FakeAnalyticsModule { } ``` -Because composables typically consume these dependencies indirectly through a -ViewModel obtained with `hiltViewModel()`, replacing the binding in Hilt is -enough. The composable under test picks up the fake automatically. +Because composables typically consume these dependencies indirectly through a ViewModel obtained with `hiltViewModel()`, replacing the binding in Hilt is enough. The composable under test picks up the fake automatically. #### Replace a binding in a single test -To replace a binding in a single test instead of all tests, uninstall a Hilt -module from a test using the `@UninstallModules` annotation and create a new -test module inside the test. +To replace a binding in a single test instead of all tests, uninstall a Hilt module from a test using the `@UninstallModules` annotation and create a new test module inside the test. -Following the `AnalyticsService` example from the previous version, begin by -telling Hilt to ignore the production module by using the `@UninstallModules` -annotation in the test class: +Following the `AnalyticsService` example from the previous version, begin by telling Hilt to ignore the production module by using the `@UninstallModules` annotation in the test class: ```kotlin @UninstallModules(AnalyticsModule::class) @@ -271,8 +223,7 @@ annotation in the test class: class SettingsScreenTest { ... } ``` -Next, you must replace the binding. Create a new module within the test class -that defines the test binding: +Next, you must replace the binding. Create a new module within the test class that defines the test binding: ```kotlin @UninstallModules(AnalyticsModule::class) @@ -294,11 +245,7 @@ class SettingsScreenTest { } ``` -This only replaces the binding for a single test class. If you want to replace -the binding for all test classes, use the `@TestInstallIn` annotation from the -section above. Alternatively, you can put the test binding in the `test` module -for Robolectric tests, or in the `androidTest` module for instrumented tests. -The recommendation is to use `@TestInstallIn` whenever possible. +This only replaces the binding for a single test class. If you want to replace the binding for all test classes, use the `@TestInstallIn` annotation from the section above. Alternatively, you can put the test binding in the `test` module for Robolectric tests, or in the `androidTest` module for instrumented tests. The recommendation is to use `@TestInstallIn` whenever possible. > [!WARNING] > **Warning:** You cannot uninstall modules that are not annotated with `@InstallIn`. Attempting to do so causes a compilation error. @@ -311,12 +258,9 @@ The recommendation is to use `@TestInstallIn` whenever possible. #### Binding new values -Use the `@BindValue` annotation to easily bind fields in your test into the Hilt -dependency graph. Annotate a field with `@BindValue` and it will be bound under -the declared field type with any qualifiers that are present for that field. +Use the `@BindValue` annotation to easily bind fields in your test into the Hilt dependency graph. Annotate a field with `@BindValue` and it will be bound under the declared field type with any qualifiers that are present for that field. -In the `AnalyticsService` example, you can replace `AnalyticsService` with a -fake by using `@BindValue`: +In the `AnalyticsService` example, you can replace `AnalyticsService` with a fake by using `@BindValue`: ```kotlin @UninstallModules(AnalyticsModule::class) @@ -330,13 +274,9 @@ class SettingsScreenTest { } ``` -This simplifies both replacing a binding and referencing a binding in your test -by allowing you to do both at the same time. +This simplifies both replacing a binding and referencing a binding in your test by allowing you to do both at the same time. -`@BindValue` works with qualifiers and other testing annotations. For example, -if you use testing libraries such as -[Mockito](https://site.mockito.org/), you could use it in a -Robolectric test as follows: +`@BindValue` works with qualifiers and other testing annotations. For example, if you use testing libraries such as [Mockito](https://site.mockito.org/), you could use it in a Robolectric test as follows: ```kotlin ... @@ -350,10 +290,7 @@ class SettingsScreenTest { } ``` -If you need to add a [multibinding](https://dagger.dev/dev-guide/multibindings), -you can use the `@BindValueIntoSet` and `@BindValueIntoMap` annotations in place -of `@BindValue`. `@BindValueIntoMap` requires you to also annotate the field -with a map key annotation. +If you need to add a [multibinding](https://dagger.dev/dev-guide/multibindings), you can use the `@BindValueIntoSet` and `@BindValueIntoMap` annotations in place of `@BindValue`. `@BindValueIntoMap` requires you to also annotate the field with a map key annotation. ## Special cases @@ -361,36 +298,23 @@ Hilt also provides features to support nonstandard use cases. ### Custom application for tests -If you cannot use `HiltTestApplication` because your test application needs to -extend another application, annotate a new class or interface with -`@CustomTestApplication`, passing in the value of the base class you want the -generated Hilt application to extend. +If you cannot use `HiltTestApplication` because your test application needs to extend another application, annotate a new class or interface with `@CustomTestApplication`, passing in the value of the base class you want the generated Hilt application to extend. -`@CustomTestApplication` will generate an `Application` class ready for testing -with Hilt that extends the application you passed as a parameter. +`@CustomTestApplication` will generate an `Application` class ready for testing with Hilt that extends the application you passed as a parameter. ```kotlin @CustomTestApplication(BaseApplication::class) interface HiltTestApplication ``` -In the example, Hilt generates an `Application` named -`HiltTestApplication_Application` that extends the `BaseApplication` class. In -general, the name of the generated application is the name of the annotated -class appended with `_Application`. You must set the generated Hilt test -application to run in your [instrumented tests](https://developer.android.com/training/testing/ui-testing) or -[Robolectric tests](http://robolectric.org/) as described in [Test -application](https://developer.android.com/training/dependency-injection/hilt-testing#test-application). +In the example, Hilt generates an `Application` named `HiltTestApplication_Application` that extends the `BaseApplication` class. In general, the name of the generated application is the name of the annotated class appended with `_Application`. You must set the generated Hilt test application to run in your [instrumented tests](https://developer.android.com/training/testing/ui-testing) or [Robolectric tests](http://robolectric.org/) as described in [Test application](https://developer.android.com/training/dependency-injection/hilt-testing#test-application). > [!NOTE] > **Note:** Because `HiltTestApplication_Application` is code that Hilt generates at runtime, the IDE might highlight it in red until you run your tests. ### Multiple TestRule objects in your instrumented test -Compose UI tests already combine `HiltAndroidRule` with a Compose test rule -such as `createAndroidComposeRule`. If you have additional `TestRule` objects, -make sure `HiltAndroidRule` runs first. Declare the execution order with the -`order` attribute on `@Rule`: +Compose UI tests already combine `HiltAndroidRule` with a Compose test rule such as `createAndroidComposeRule`. If you have additional `TestRule` objects, make sure `HiltAndroidRule` runs first. Declare the execution order with the `order` attribute on `@Rule`: ```kotlin @HiltAndroidTest @@ -409,8 +333,7 @@ class SettingsScreenTest { } ``` -Alternatively, you can wrap the rules with `RuleChain`, placing -`HiltAndroidRule` as the outer rule. +Alternatively, you can wrap the rules with `RuleChain`, placing `HiltAndroidRule` as the outer rule. ```kotlin @HiltAndroidTest @@ -426,12 +349,9 @@ class SettingsScreenTest { ### Use an entry point before the singleton component is available -The `@EarlyEntryPoint` annotation provides an escape hatch when a Hilt entry -point needs to be created before the singleton component is available in a -Hilt test. +The `@EarlyEntryPoint` annotation provides an escape hatch when a Hilt entry point needs to be created before the singleton component is available in a Hilt test. -More information about `@EarlyEntryPoint` in the -[Hilt documentation](https://dagger.dev/hilt/early-entry-point). +More information about `@EarlyEntryPoint` in the [Hilt documentation](https://dagger.dev/hilt/early-entry-point). ## Additional resources diff --git a/tv/leanback-to-compose-tv-migration/SKILL.md b/tv/leanback-to-compose-tv-migration/SKILL.md new file mode 100644 index 0000000..0c46918 --- /dev/null +++ b/tv/leanback-to-compose-tv-migration/SKILL.md @@ -0,0 +1,692 @@ +--- +name: leanback-to-compose-tv-migration +description: Provides instructions and architectural patterns for migrating Android + TV applications from legacy Leanback UI Toolkit, Android Views, or Support Fragments + to Jetpack Compose for TV (androidx.tv). Use this skill for Leanback to Compose + migrations, including browse screen, settings screen, authentication screen, login + screen, or video playback screen migrations, or when replacing BrowseSupportFragment, + LeanbackSettingsFragment, PreferenceFragment, BaseLeanbackPreferenceFragmentCompat, + VideoSupportFragment, GuidedStepSupportFragment, SearchSupportFragment, VerticalGridSupportFragment, + Presenter, ArrayObjectAdapter, or CursorMapper with modern Compose equivalents, + implementing immersive carousels with focus memory, Media3 video playback with PlayerSurface, + or custom 10-foot hero layouts. +license: Complete terms in LICENSE.txt +metadata: + author: Google LLC + last-updated: '2026-08-06' + keywords: + - Android TV + - Jetpack Compose + - Leanback + - migration + - androidx.tv + - Carousel + - 10-foot UI + - PlayerSurface + - Media3 + - focusRestorer + - FocusRequester + - TV development + - Android Views + - LeanbackSettingsFragment + - PreferenceFragment + - BrowseSupportFragment +--- + +## The 10-foot UI + +A "10-foot UI" is a design paradigm for televisions that tailors an interface for viewing from approximately 3 meters (10 feet) away. When designing for this experience, account for these key characteristics: + +- **Viewing distance**: Viewers are sitting far from the screen, "leaning back". Screen layouts are uncluttered, with text and UI elements that are large enough to be comfortably readable from a distance, without dense blocks of text. +- **Color contrast**: To avoid washed out colors on TV displays with low contrast ratios, the design uses high-contrast palettes and distinct visual indicators so focused states remain visible across different TV panels. +- **D-pad navigation** : Interaction relies on a directional remote control with limited 4-way navigation (`Up`, `Down`, `Left`, `Right`) with components organized into clear spatial grids and carousels without focus traps. + +## Core architecture and library selection + +When migrating an Android TV application to Jetpack Compose, you must use `androidx.tv` libraries and follow these 10-foot UI patterns: + +- **UI modernization**: Focus on custom, cinematic layouts over legacy direct 1:1 templates. You must use Jetpack Compose for TV features like dynamic gradient hero backdrops, custom focus animations, custom navigation drawers, and custom layouts. +- **Primary design system** : You must always use `androidx.tv.material3.*` (`androidx.tv:tv-material`) over mobile `androidx.compose.material3.*`. TV Material 3 provides built-in D-Pad focus handling, focus zoom scaling, and TV-optimized typography and shapes. To set up Compose for TV dependencies, follow [Compose for TV setup](references/android/training/tv/playback/compose/index.md). +- **Focus zoom animation** : For interactive cards, you must use `CompactCard`, `ClassicCard`, or `WideCardContainer` with `scale = CardDefaults.scale(focusedScale = 1.1f)` to provide standard TV focus animation. +- **Coil image loading** : To use declarative `AsyncImage(model, contentDescription, ...)` without passing an explicit `ImageLoader` parameter, you must include `io.coil-kt:coil-compose` in your Gradle dependencies. +- **Explicit imports** : You must always import TV Material 3 classes explicitly (for example, `import androidx.tv.material3.Surface`, `import androidx.tv.material3.ListItem`) instead of using wildcard imports (`import androidx.tv.material3.*`). +- **File naming conventions** : You must name Composable screen files after the screen (for example, name `BrowseScreen` as `BrowseScreen.kt`, `PlaybackScreen` as `PlaybackScreen.kt`, and `AuthenticationScreen` as `AuthenticationScreen.kt`). Don't use generic prefixes like `Main`. +- **Overscan and bezels** : You must apply horizontal padding (for example, `horizontal = 48.dp` or `32.dp`, `vertical = 24.dp`) to root containers, carousels, and top bars to prevent clipping. +- **Reading width constrainment** : You must constrain reading width using `Modifier.widthIn(max = 600.dp)` on text columns for long-form text. +- **Media3 Compose dependencies** : Include `androidx.media3:media3-ui-compose` in `app/build.gradle` when modernizing media playback screens. +- **Prohibition of legacy AndroidView wrappers** : Don't use legacy `AndroidView` wrappers to embed View-based components into Jetpack Compose screens. All migrated screens must use Compose components or Media3 Compose surfaces (`PlayerSurface`). + +## D-pad focus handling and navigation + +Jetpack Compose for TV (`androidx.tv.material3`) requires explicit focus management, as components don't receive initial focus automatically and navigation uses 2D spatial coordinates. To configure TV D-pad navigation, follow instructions in [TV Navigation guide](references/android/training/tv/get-started/navigation.md). + +### Initial focus + +You must assign initial focus to the primary interactive element on every screen (such as the first action button, card, or `ListItem`) using `FocusRequester` when entering a screen. Define `val focusRequester = remember { FocusRequester() }`, attach `Modifier.focusRequester(focusRequester)` to the primary element, and request focus inside `LaunchedEffect(Unit) { focusRequester.requestFocus() }`: + +
+ +```kotlin +val focusRequester = remember { FocusRequester() } +val focusManager = LocalFocusManager.current + +LaunchedEffect(Unit) { + focusRequester.requestFocus() +} + +``` + +
+ +*Note: For screens with dynamic state or pagers (like `OnboardingScreen` using `HorizontalPager`), you must pass the state key to `LaunchedEffect` (for example `LaunchedEffect(pagerState.currentPage)`) so that focus is re-applied when the page changes.* + +### Bidirectional focus routing and avoiding focus traps + +When interactive elements sit on opposite sides of the display, standard 2D spatial navigation fails to find targets across them. This creates focus traps where users are unable to navigate out of an area using the D-pad. + +For symmetrical, bidirectional D-pad navigation without focus traps, you must rely on Compose's 2D spatial focus engine whenever possible. When connecting adjacent UI elements across scrollable containers (like `LazyColumn` or `LazyRow`), don't set directional overrides (`up = ...`, `down = ...`) targeting individual items inside lazy lists. When an item scrolls off-screen during vertical navigation, its `FocusRequester` becomes uninitialized, throwing `IllegalStateException` during focus searches: + +
+ +```kotlin +Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 48.dp, vertical = 16.dp), + horizontalArrangement = Arrangement.End +) { + Button( + onClick = { /* Search */ }, + modifier = Modifier.focusRequester(topBarFocusRequester) + ) { Text("Search") } +} + +``` + +
+ +### Row focus recollection (`Modifier.focusRestorer`) + +When navigating vertically between horizontal carousels (`LazyRow`), Compose's default 2D spatial focus engine searches along the X coordinate of the focused item. If a user scrolls right in Row 1 (for example to Item 4 at X=800dp) and presses DOWN to navigate to Row 2, spatial routing focuses whatever item sits at X=800dp in Row 2. + +To make every row maintain its own recollection of card focus (restoring focus to the previously visited item when revisited), you must attach **`Modifier.focusRestorer`** (with no arguments) directly to the `LazyRow`. Don't pass custom fallback `FocusRequester` lambdas in lazy containers, as calling `requestFocus` on an unattached or off-screen item during rapid D-pad scrolling throws `IllegalStateException`. + +
+ +```kotlin +LazyRow( + modifier = Modifier.focusRestorer(), + contentPadding = PaddingValues(horizontal = 48.dp), + horizontalArrangement = Arrangement.spacedBy(16.dp) +) { + itemsIndexed(videos) { vidIndex, video -> + CompactCard( + onClick = { onVideoClick(video) }, + image = { + AsyncImage( + model = video.cardImageUrl, + contentDescription = video.title, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize() + ) + }, + title = { Text(video.title) }, + modifier = Modifier + .then( + if (catIndex == 0 && vidIndex == 0) { + Modifier.focusRequester(firstCardFocusRequester) + } else { + Modifier + } + ) + .onFocusChanged { focusState -> + if (focusState.isFocused) { + focusedVideo = video + focusedCategoryIndex = catIndex + } + } + ) + } +} + +``` + +
+ +### Text input, hardware keyboard enter interception, and IME focus chaining + +When migrating search bars or login forms from Leanback (`SearchSupportFragment`, `GuidedStepSupportFragment`), don't use bare `BasicTextField` containers or empty `Surface(onClick = {})` wrappers, as they prevent D-pad CENTER from attaching the virtual keyboard (IME). + +1. **Clickable TV surface wrapper with Back-key interception (`onPreviewKeyEvent`)** : Wrap standard M3 `TextField` inside a focusable TV `Surface(onClick = { focusRequester.requestFocus() }, scale = ClickableSurfaceDefaults.scale(focusedScale = 1.01f), border = ClickableSurfaceDefaults.border(focusedBorder = Border(BorderStroke(2.dp, Color.White))))` to provide a focused border outline and D-pad focus scaling. You must attach `Modifier.onPreviewKeyEvent` on the text field or wrapper to intercept `Key.Back` and `Key.Escape` so the user's able to remove focus from the input field without exiting the screen. +2. **Why Back-key interception is mandatory** : When editing a text field on Android TV, pressing the D-pad **Back** button normally navigates back and exits the screen. By intercepting `Key.Back` and `Key.Escape` on `KeyUp` in `onPreviewKeyEvent` to stop editing (clearing focus), the user's able to return to D-pad form navigation without being trapped in the text field or accidentally exiting the screen. +3. **IME focus chaining** : For multi-field forms (such as Username and Password in authentication screens), attach `KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) })` with `ImeAction.Next` on top fields to route focus down to the next input box, and `ImeAction.Done` on the bottom field to route focus directly to the submit button: + +
+ +```kotlin +Surface( + onClick = { focusRequester.requestFocus() }, + border = ClickableSurfaceDefaults.border(focusedBorder = Border(border = BorderStroke(2.dp, Color.White))), + modifier = Modifier + .fillMaxWidth() + .focusRequester(focusRequester) +) { + OutlinedTextField( + value = username, + onValueChange = { username = it }, + label = { Text("Username") }, + singleLine = true, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next), + keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) }), + modifier = Modifier + .fillMaxWidth() + .onPreviewKeyEvent { event -> + if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) { + focusManager.moveFocus(FocusDirection.Down) + true + } else false + } + ) +} + +Surface( + onClick = {}, + border = ClickableSurfaceDefaults.border(focusedBorder = Border(border = BorderStroke(2.dp, Color.White))), + modifier = Modifier.fillMaxWidth() +) { + OutlinedTextField( + value = password, + onValueChange = { password = it }, + label = { Text("Password") }, + singleLine = true, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { onLoginSuccess() }), + modifier = Modifier + .fillMaxWidth() + .onPreviewKeyEvent { event -> + if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) { + onLoginSuccess() + true + } else false + } + ) +} + +``` + +
+ +## Lazy containers + +When implementing scrollable lists or grids in Jetpack Compose for TV, you must use standard `LazyColumn`, `LazyRow`, and `LazyVerticalGrid` from `androidx.compose.foundation.lazy` and `androidx.compose.foundation.lazy.grid`. For catalog browsing layouts, follow instructions in [Catalog Browser guide](references/android/training/tv/playback/compose/browse.md). + +1. **Pivot scrolling with `BringIntoViewSpec`** : When defining a custom pivot scroll line for catalog rows using `BringIntoViewSpec` and `CompositionLocalProvider(LocalBringIntoViewSpec provides ...)`, you must ensure your project compiles against Compose Foundation 1.7.0+ by adding `implementation platform('androidx.compose:compose-bom:2024.06.00')` (or newer) or `implementation 'androidx.compose.foundation:foundation:1.7.0'` in `app/build.gradle`. Without Compose Foundation 1.7.0+, `import androidx.compose.foundation.gestures.LocalBringIntoViewSpec` will fail with `Unresolved reference: LocalBringIntoViewSpec`. +2. **Row focus recollection (`Modifier.focusRestorer`)** : Annotate your composable with `@OptIn(ExperimentalFocusRestorerApi::class, ExperimentalComposeUiApi::class)` and attach `Modifier.focusRestorer` on every category `LazyRow` to remember and restore the last focused card when navigating vertically across catalog rows. + +When populated with focusable TV Material 3 components (`CompactCard`, `ListItem`, `Button`), standard Compose lazy containers handle 2D D-Pad focus routing, focus memory, and edge scrolling automatically: + +
+ +```kotlin +@Composable +fun CatalogBrowser( + featuredContentList: List, + sectionList: List
, + modifier: Modifier = Modifier, + onItemSelected: (Movie) -> Unit = {}, +) { + LazyColumn( + modifier = modifier.fillMaxSize(), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + items(sectionList.size) { index -> + val section = sectionList[index] + SectionRow(section, onItemSelected = onItemSelected) + } + } +} + +``` + +
+ +## Media3 video playback and transport controls + +When migrating legacy Leanback video playback (`VideoSupportFragment` / `PlaybackGlue`), use Compose Media3 `PlayerSurface` (`androidx.media3.ui.compose.PlayerSurface`) combined with a translucent transport controls overlay: + +1. **Mandatory Media3 transport control buttons (`PlayPauseButton`)** : Over the `PlayerSurface`, you must layer a translucent bottom controls bar (`Box(modifier = Modifier.align(Alignment.BottomCenter))`) containing explicit Media3 UI Compose buttons: at minimum `PlayPauseButton`, `SeekBackButton`, and `SeekForwardButton`. Never leave the transport controls overlay empty. To use these composables, you must add `implementation 'androidx.media3:media3-ui-compose-material3:1.6.0'` alongside `androidx.media3:media3-ui-compose` in your `app/build.gradle` dependencies. +2. **D-pad directional seeking (`onPreviewKeyEvent`)** : To support seeking backward and forward with the remote control D-pad, attach `Modifier.onPreviewKeyEvent` on the container or controls overlay and intercept Compose `Key.DirectionLeft` and `Key.DirectionRight` (for example, `keyEvent.key == Key.DirectionLeft`) to seek backward and forward by 10 seconds (`exoPlayer.seekTo(exoPlayer.currentPosition - 10000)`). Never use legacy Android View keycodes (`KeyEvent.KEYCODE_DPAD_LEFT` or `nativeKeyEvent.keyCode`). +3. **Prohibition of legacy AndroidView wrappers** : Don't wrap legacy `PlayerView` or `StyledPlayerView` in `AndroidView { ... }`. You must use `PlayerSurface` (`androidx.media3.ui.compose.PlayerSurface`) with `ExoPlayer` for video rendering in Compose for TV. + +## Phased migration strategy + +To migrate an app cleanly without breaking compilation or introducing circular dependencies, execute in five distinct phases: + +- **Phase 1**: Foundation and design system +- **Phase 2**: Leaf and standalone screens +- **Phase 3**: Core browsing and discovery screens +- **Phase 4**: Details and media playback +- **Phase 5**: Final unification and cleanup + +### Phase 1: Foundation and design system + +- Create `TvTheme.kt` wrapping `TvMaterialTheme` with custom `ColorScheme`, `Typography`, and `Shapes`. +- Build atomic reusable components: `MovieCard`, `SectionHeader`, `LoadingIndicator`, `ErrorState`. + +### Phase 2: Leaf and standalone screens + +- Migrate screens with no outbound navigation first, such as error messages, onboarding screens, or settings screens, by replacing them with `ErrorDialog`, `OnboardingScreen`, and `SettingsScreen`. +- Replace anything using `BaseLeanbackPreferenceFragmentCompat`, `BaseLeanbackPreferenceFragment`, or `LeanbackSettingsFragment` to use Compose, for example by using `ListItem` + `Switch` bound directly to `SharedPreferences` and replacing the `findPreference` implementation. +- Ensure screens receive initial D-pad focus on the first or main component of that screen using `FocusRequester`, for example on the first `ListItem`. +- Replace legacy `Fragment` classes with activities of type `ComponentActivity` that declaratively use components in Compose. +- Clean up legacy style and theme references in `res/values/styles.xml` and `res/values/themes.xml` (such as removing `preferenceTheme` that points to `@style/PreferenceThemeOverlay.v14.Leanback`) that aren't supported once leanback dependencies are removed: + +
+ +```kotlin +@Composable +fun TvSettingsScreen( + modifier: Modifier = Modifier +) { + var autoPlayNext by remember { mutableStateOf(true) } + var highQualityAudio by remember { mutableStateOf(false) } + + Column( + modifier = modifier + .fillMaxSize() + .padding(48.dp) + ) { + Text( + text = "Settings", + style = MaterialTheme.typography.headlineMedium, + modifier = Modifier.padding(bottom = 24.dp) + ) + + LazyColumn( + verticalArrangement = Arrangement.spacedBy(12.dp), + contentPadding = PaddingValues(vertical = 8.dp) + ) { + item { + ListItem( + selected = false, + onClick = { autoPlayNext = !autoPlayNext }, + headlineContent = { Text("Autoplay Next Video") }, + supportingContent = { Text("Automatically start playing next item in queue") }, + trailingContent = { + Switch( + checked = autoPlayNext, + onCheckedChange = null + ) + } + ) + } + + item { + ListItem( + selected = false, + onClick = { highQualityAudio = !highQualityAudio }, + headlineContent = { Text("High Quality Audio") }, + supportingContent = { Text("Use spatial audio and multi-channel output when available") }, + trailingContent = { + Switch( + checked = highQualityAudio, + onCheckedChange = null + ) + } + ) + } + } + } +} + +``` + +
+ +### Phase 3: Core browsing and discovery screens + +- Migrate `VerticalGridScreen` (`LazyVerticalGrid`), `SearchScreen` (`BasicTextField` with live list filtering), and `BrowseScreen` (`LazyColumn` of `LazyRow`s). +- Eradicate legacy `ArrayObjectAdapter`, `ListRowPresenter`, `CardPresenter`, and `HeaderItem` classes. + +### Phase 4: Details and media playback + +- Migrate `VideoDetailsScreen` and `GuidedStepScreen`. +- Migrate `PlaybackScreen` using Compose Media3 `PlayerSurface` (`androidx.media3.ui.compose.PlayerSurface`) paired with a translucent bottom overlay containing Media3 Compose transport controls (such as `PlayPauseButton`, `SeekBackButton`, `SeekForwardButton`). + +### Phase 5: Final unification and cleanup + +- Remove all remaining legacy `.java` activities, fragments, presenters, and XML layout files. +- Ensure all activities extend `ComponentActivity` or `FragmentActivity` calling `setContent { ... }`. +- Completely remove legacy Leanback themes and style declarations from `res/values/styles.xml` and `res/values/themes.xml` (for example, any styles inheriting from `Theme.Leanback` or referencing `lb_` styles). + +## Component and class mapping guide + +| Legacy Leanback / View Class | Modern Jetpack Compose Equivalent | +|---|---| +| `BrowseSupportFragment` / `MainFragment` | `BrowseScreen` (`LazyColumn` containing categorized `LazyRow`s + Hero Banner) | +| `DetailsSupportFragment` | `VideoDetailsScreen` (Poster image, text column, action buttons, related `LazyRow`) | +| `VideoSupportFragment` / `PlaybackGlue` | `PlaybackScreen` (Media3 `ExoPlayer` + Compose `PlayerSurface`) | +| `GuidedStepSupportFragment` | `GuidedStepScreen` (Split-screen layout: 40% left guidance pane, 60% right actions pane) | +| `SearchSupportFragment` | `SearchScreen` (`BasicTextField` + live filtering + `LazyVerticalGrid`) | +| `VerticalGridSupportFragment` | `VerticalGridScreen` (`LazyVerticalGrid(columns = GridCells.Fixed(5))`) | +| `ArrayObjectAdapter` / `Presenter` | Declarative `@Composable` functions observing immutable `State>` | +| `CursorMapper` / `LoaderManager` / `CursorLoader` | Kotlin Coroutines / `withContext(Dispatchers.IO)` in a Repository object | +| `OnboardingSupportFragment` | `OnboardingScreen` (`HorizontalPager` + D-Pad navigation buttons) | +| `LeanbackSettingsFragment` / `PreferenceFragment` | `SettingsScreen` (`FocusRequester` on first `ListItem` + trailing `Switch` bound to `SharedPreferences`) | + +## Reference implementations and battle-tested patterns + +### Modern TV immersive list architecture (`BrowseScreen`) + +When building a 10-foot TV browse screen or Immersive List, don't place a hero banner before or outside a scrolling list, and don't fight Compose's automatic `BringIntoView` system with programmatic `animateScrollToItem` calls. + +Instead, use `BringIntoViewSpec` with `LocalBringIntoViewSpec` from Compose Foundation to define exact TV pivot scrolling (for example, pivoting active rows at 35% from the top edge of the display). Combine this with a reshaping immersive row: when lower rows are focused (`focusedCategoryIndex > 0`), hide the hero text and display a normal section header on Row 0: + +
+ +```kotlin +@Composable +fun ImmersiveBrowseScreen( + categories: Map>, + onVideoClick: (Video) -> Unit +) { + var focusedVideo by remember { mutableStateOf(null) } + var focusedCategoryIndex by remember { mutableStateOf(0) } + val listState = rememberLazyListState() + val topBarFocusRequester = remember { FocusRequester() } + val firstCardFocusRequester = remember { FocusRequester() } + + Box(modifier = Modifier.fillMaxSize()) { + AsyncImage( + model = focusedVideo?.bgImageUrl, + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize() + ) + + PositionFocusedItemInLazyLayout(parentFraction = 0.35f, childFraction = 0.5f) { + LazyColumn( + state = listState, + contentPadding = PaddingValues(top = 36.dp, bottom = 64.dp), + verticalArrangement = Arrangement.spacedBy(28.dp), + modifier = Modifier.fillMaxSize() + ) { + item { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 48.dp, vertical = 16.dp), + horizontalArrangement = Arrangement.End + ) { + Button( + onClick = { /* Search */ }, + modifier = Modifier.focusRequester(topBarFocusRequester) + ) { Text("Search") } + } + } + + itemsIndexed(categories.entries.toList()) { catIndex, (categoryName, videos) -> + Column { + if (catIndex == 0 && focusedCategoryIndex == 0) { + Column( + modifier = Modifier + .heightIn(min = 200.dp) + .padding(horizontal = 48.dp) + ) { + Text( + text = focusedVideo?.title ?: "", + style = MaterialTheme.typography.displayMedium + ) + Text( + text = focusedVideo?.description ?: "", + style = MaterialTheme.typography.bodyLarge + ) + } + } else { + Text( + text = categoryName, + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.padding(horizontal = 48.dp, vertical = 8.dp) + ) + } + + LazyRow( + modifier = Modifier.focusRestorer(), + contentPadding = PaddingValues(horizontal = 48.dp), + horizontalArrangement = Arrangement.spacedBy(16.dp) + ) { + itemsIndexed(videos) { vidIndex, video -> + CompactCard( + onClick = { onVideoClick(video) }, + image = { + AsyncImage( + model = video.cardImageUrl, + contentDescription = video.title, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize() + ) + }, + title = { Text(video.title) }, + modifier = Modifier + .then( + if (catIndex == 0 && vidIndex == 0) { + Modifier.focusRequester(firstCardFocusRequester) + } else { + Modifier + } + ) + .onFocusChanged { focusState -> + if (focusState.isFocused) { + focusedVideo = video + focusedCategoryIndex = catIndex + } + } + ) + } + } + } + } + } + } + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun PositionFocusedItemInLazyLayout( + parentFraction: Float = 0.35f, + childFraction: Float = 0.5f, + content: @Composable () -> Unit, +) { + val bringIntoViewSpec = remember(parentFraction, childFraction) { + object : BringIntoViewSpec { + override fun calculateScrollDistance( + offset: Float, + size: Float, + containerSize: Float + ): Float { + if (offset >= 0f && offset <= containerSize * 0.45f) { + return 0f + } + val initialTargetForLeadingEdge = parentFraction * containerSize - (childFraction * size) + val targetForLeadingEdge = if (size <= containerSize && (containerSize - initialTargetForLeadingEdge) < size) { + containerSize - size + } else { + initialTargetForLeadingEdge + } + return offset - targetForLeadingEdge + } + } + } + CompositionLocalProvider(LocalBringIntoViewSpec provides bringIntoViewSpec, content = content) +} + +``` + +
+ +### Media3 playback in Compose TV (`PlaybackScreen`) + +Implement a custom playback screen using `androidx.media3.ui.compose.PlayerSurface` as the video rendering canvas. Layer Material3 transport controls (`SeekBackButton`, `PlayPauseButton`, `SeekForwardButton` from `androidx.media3:media3-ui-compose-material3`) over the surface in a translucent bottom overlay, and handle D-pad remote key events with an auto-hide timeout: + +
+ +```kotlin +@OptIn(UnstableApi::class) +@Composable +fun Media3PlaybackScreen( + video: Video, + onFinish: () -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val exoPlayer = remember(context) { ExoPlayer.Builder(context).build() } + var showControls by remember { mutableStateOf(true) } + val focusRequester = remember { FocusRequester() } + val coroutineScope = rememberCoroutineScope() + var autoHideJob by remember { mutableStateOf(null) } + + fun scheduleAutoHide() { + autoHideJob?.cancel() + autoHideJob = coroutineScope.launch { + delay(5000) + showControls = false + } + } + + DisposableEffect(exoPlayer) { + val listener = object : Player.Listener { + override fun onPlaybackStateChanged(playbackState: Int) { + if (playbackState == Player.STATE_ENDED) { + onFinish() + } + } + } + exoPlayer.addListener(listener) + onDispose { + autoHideJob?.cancel() + exoPlayer.removeListener(listener) + exoPlayer.release() + } + } + + LaunchedEffect(video) { + focusRequester.requestFocus() + scheduleAutoHide() + + val mediaItem = MediaItem.fromUri(video.videoUrl) + exoPlayer.setMediaItem(mediaItem) + exoPlayer.prepare() + exoPlayer.playWhenReady = true + } + + Box( + modifier = modifier + .fillMaxSize() + .background(Color.Black) + .focusRequester(focusRequester) + .focusable() + .onPreviewKeyEvent { event -> + if (event.type == KeyEventType.KeyDown) { + when (event.key) { + Key.DirectionCenter, Key.Enter, Key.NumPadEnter, Key.MediaPlayPause, Key.Spacebar -> { + if (exoPlayer.isPlaying) exoPlayer.pause() else exoPlayer.play() + showControls = true + scheduleAutoHide() + true + } + Key.DirectionLeft, Key.MediaRewind -> { + val newPos = (exoPlayer.currentPosition - 10_000L).coerceAtLeast(0L) + exoPlayer.seekTo(newPos) + showControls = true + scheduleAutoHide() + true + } + Key.DirectionRight, Key.MediaFastForward -> { + val duration = exoPlayer.duration.coerceAtLeast(0L) + val newPos = (exoPlayer.currentPosition + 10_000L).coerceAtMost(duration) + exoPlayer.seekTo(newPos) + showControls = true + scheduleAutoHide() + true + } + Key.DirectionUp, Key.DirectionDown -> { + showControls = !showControls + if (showControls) scheduleAutoHide() else autoHideJob?.cancel() + true + } + else -> false + } + } else false + }, + contentAlignment = Alignment.Center + ) { + PlayerSurface( + player = exoPlayer, + modifier = Modifier.fillMaxSize() + ) + + if (showControls) { + Box( + modifier = Modifier + .fillMaxSize() + .background(Color(0x80000000)) + .padding(48.dp), + contentAlignment = Alignment.BottomCenter + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(24.dp), + verticalAlignment = Alignment.CenterVertically + ) { + SeekBackButton(player = exoPlayer) + PlayPauseButton(player = exoPlayer) + SeekForwardButton(player = exoPlayer) + } + } + } + } +} + +``` + +
+ +### Replacing CursorLoader with reactive coroutine flow + +Replace legacy `LoaderManager.LoaderCallbacks` and `CursorObjectAdapter` with a repository returning a `Flow` that observes database changes and triggers asynchronous fetching when empty: + +
+ +```kotlin +object VideoFlowRepository { + fun getVideosFlow(context: Context, contentUri: Uri): Flow> = callbackFlow { + val contentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean) { + trySend(queryVideos(context, contentUri)) + } + } + + context.contentResolver.registerContentObserver( + contentUri, + true, + contentObserver + ) + + val initialVideos = queryVideos(context, contentUri) + trySend(initialVideos) + + awaitClose { + context.contentResolver.unregisterContentObserver(contentObserver) + } + }.flowOn(Dispatchers.IO) + + private fun queryVideos(context: Context, uri: Uri): List