
Unified Google Mobile Ads and UMP consent SDK wrapper offering initialization and consent flows, native/interstitial/rewarded ad loading and rendering helpers, suspending show calls, and event flows.
Google Mobile Ads (AdMob) and the UMP consent SDK in Kotlin Multiplatform common code, on Android and iOS. It is
built on each platform's newest official SDK and calls it directly: the
GMA Next-Gen SDK on Android, which replaced play-services-ads,
and GoogleMobileAds 13 on iOS. On iOS that goes through Kotlin's SwiftPM import, the same mechanism as
firebase-multiplatform, so the app needs no Swift bridge. The
library calls no deprecated SDK API.
canRequestAds and reset, with the state as a
StateFlow.Flow (impression,
click, paid). Rendering stays native, with the platform ad, plus a few iOS view helpers.show that returns when the ad is closed (with the reward), and the
same events.What stays in the app: ad card layouts, caches of loaded ads, when to show a full-screen ad, and where revenue events go (RevenueCat, analytics).
// build.gradle.kts of the shared module
kotlin {
sourceSets {
commonMain.dependencies {
implementation("io.github.corneloaie:admob:0.1.0")
}
}
}The library has Android, iosArm64 and iosSimulatorArm64 targets only. If the shared module also targets the JVM, JS
or Wasm, add the dependency to a source set that only Android and iOS share (for example, a mobileMain source set
that androidMain and iosMain depend on).
The minimum SDK is 24. The library brings the GMA Next-Gen SDK
(com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk 1.6.0) and user-messaging-platform 4.0.0 as api
dependencies. The app must not depend on play-services-ads itself.
Add the AdMob app id to the app's manifest. UMP reads it there, and the library hands it to the Next-Gen SDK, which
takes it in code. Without it, AdMob.initialize() and the first ad load throw IllegalStateException:
<application>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy" />
</application>A small ContentProvider in the library's manifest (AdMobInitProvider, not exported) keeps the application
Context at startup. Starting the SDK and reading the consent state therefore need no Context.
Mediation adapters still depend on the legacy play-services-ads, which clashes with the Next-Gen SDK. As
Google's mediation guides say, exclude it from
every configuration of the app module:
configurations.configureEach {
exclude(group = "com.google.android.gms", module = "play-services-ads")
exclude(group = "com.google.android.gms", module = "play-services-ads-lite")
}The Next-Gen SDK works with AdMob mediation, not under a third-party mediation platform.
The Next-Gen SDK calls back on background threads. The library moves every callback to the main thread, and its suspending calls return there.
The library binds to the official GoogleMobileAds and UMP Swift packages without bundling them. Its Maven publication records both packages, and your app inherits them: GoogleMobileAds from 13.11.0 and UMP from 3.1.0, each up to the next major version. You don't add either package to Xcode yourself.
embedAndSignAppleFrameworkForXcode build phase, and build the shared framework as static
(binaries.framework { isStatic = true }). The Swift packages are static libraries, and a dynamic framework fails at
launch with dyld: Library not loaded.integrateEmbedAndSign and
integrateLinkagePackage tasks against your Xcode project; commit the project change it makes. An app that already
consumes firebase-multiplatform has done this once, and the same package now carries the ads SDKs too. Kotlin's
CocoaPods to SwiftPM migration guide and
firebase-multiplatform's
iOS linking notes
explain the mechanism.GADApplicationIdentifier (your AdMob app id) and the SKAdNetworkItems that Google lists in
its iOS quick start.from: 13.4.0, leaves
SwiftPM a version both accept; an exact pin below 13.11.0 doesn't.build/kotlin/swiftPMXcodeDumps in the root
project.Every call that shows something takes an AdHost: the Activity on Android, the UIViewController on iOS. Every other
call needs none. In Compose Multiplatform:
// commonMain
@Composable
expect fun currentAdHost(): AdHost
// androidMain (androidx.activity:activity-compose)
@Composable
actual fun currentAdHost(): AdHost = checkNotNull(LocalActivity.current) { "not hosted in an Activity" }
// iosMain
@Composable
actual fun currentAdHost(): AdHost = LocalUIViewController.currentThe suspending calls switch to the main thread themselves. They throw AdMobException when the SDK reports an error;
its error.code is an AdErrorCode that is the same on both platforms (NO_FILL, NETWORK_ERROR, TIMEOUT, ...).
error.platformCode and error.domain keep the SDK's own values.
Google's order is: update the consent info at every launch, show the form if consent is required, then start the SDK once ads may be requested.
suspend fun startAds(host: AdHost) {
try {
AdConsent.requestInfoUpdate(host)
AdConsent.loadAndShowConsentFormIfRequired(host)
} catch (e: AdMobException) {
// Offline, for example. Consent given in an earlier session still counts: check canRequestAds.
}
if (AdConsent.canRequestAds) {
AdMob.requestConfiguration = RequestConfiguration(
ageRestrictedTreatment = null, // or CHILD / TEEN: the age treatment for your users
maxAdContentRating = MaxAdContentRating.PG,
)
val status = AdMob.initialize() // returns once the mediation adapters have started
}
}AdConsent.state is a StateFlow<ConsentState> (consentStatus, canRequestAds, privacyOptionsRequirementStatus).
It updates as soon as requestInfoUpdate is called, not only when the request completes, because UMP loads the consent
saved in an earlier session right away. A returning user's ads therefore don't wait for the network.
val canRequestAds: StateFlow<Boolean> =
AdConsent.state.map { it.canRequestAds }.stateIn(scope, SharingStarted.Eagerly, false)
// A privacy settings entry, shown when the user must be able to change their choices:
if (AdConsent.privacyOptionsRequirementStatus == PrivacyOptionsRequirementStatus.REQUIRED) {
AdConsent.showPrivacyOptionsForm(host)
}
// Consent syncing: the same id in each of your apps shares the user's choices between them.
AdConsent.requestInfoUpdate(host, ConsentRequestParameters(consentSyncId = userUuid))
// Testing: appear in the EEA, and forget this device's answer.
AdConsent.requestInfoUpdate(
host,
ConsentRequestParameters(debugSettings = ConsentDebugSettings(DebugGeography.EEA, listOf("<hashed device id>"))),
)
AdConsent.reset()AdMob.initialize() starts the SDK once; later and concurrent calls wait for the same result. Set
AdMob.requestConfiguration before it. An ad load without it starts the SDK too, without waiting for the mediation
adapters, so with mediation call it first. To use the Ad Inspector, add the device to testDeviceIds and call
AdMob.openAdInspector(host).
val loader = NativeAdLoader(
adUnitId,
NativeAdOptions(
mediaAspectRatio = MediaAspectRatio.LANDSCAPE,
adChoicesPlacement = AdChoicesPlacement.TOP_RIGHT,
startMuted = true,
),
)
val ad: NativeAd = loader.load() // throws AdMobException, e.g. AdErrorCode.NO_FILL
ad.headline; ad.body; ad.callToAction; ad.icon; ad.mediaContent?.aspectRatio; ad.responseInfo?.responseId
scope.launch {
ad.events.collect { event ->
when (event) {
AdEvent.Impression -> {}
AdEvent.Click -> {}
is AdEvent.Paid -> event.value.let { it.valueMicros; it.currencyCode; it.precision }
else -> {}
}
}
}
ad.destroy() // once it is off screen for good; completes ad.eventsThe library wires the SDK's listeners when the ad loads, before load returns. Every collector of events receives
every event from the start, however late it starts collecting. The paid event, which the SDK only delivers to a
listener that was in place at impression time, is never lost. Each load is a request of its own; caching ads and
deciding when to load one stay in the app.
Rendering stays native, with the platform ad.
On Android, register ad.android (a com.google.android.libraries.ads.mobile.sdk.nativead.NativeAd) with the Next-Gen
SDK's NativeAdView:
// androidMain, e.g. in an AndroidView's update block; headline and mediaView (the Next-Gen SDK's MediaView) are
// children of nativeAdView
nativeAdView.headlineView = headline
headline.text = ad.headline
nativeAdView.registerNativeAd(ad.android, mediaView)On iOS, ad.ios is the GADNativeAd. The library adds three helpers for a card built in Kotlin:
// iosMain
val card = AttachRegisteringNativeAdView()
val headline = UILabel().apply { text = ad.headline }
val media = GADMediaView()
val badge = AdBadgeLabel().apply { text = "Ad" }
// The asset outlets are weak: add each view to the card first, then register it (Auto Layout constraints omitted).
listOf(headline, media, badge).forEach(card::addSubview)
card.headlineView = headline
card.mediaView = media
card.registerWhenAttached(ad) // sets nativeAd once the card is in a window and laid out
val height = preferredHeight(card, width = 360.0) // to frame its Compose UIKitViewAttachRegisteringNativeAdView sets its nativeAd only once it is in a window and laid out. A card set before then
(as Compose's UIKitView builds it) measures 0×0, and the SDK's ad validator reports its asset views as missing.AdBadgeLabel never gets smaller than the 15pt the validator requires for the "Ad" attribution.preferredHeight returns the card's Auto Layout height at a given width. The media view follows the creative's aspect
ratio, so every card has a different height.val interstitial = InterstitialAd.load(interstitialUnitId)
interstitial.show(host) // returns when the user closes it
val rewarded = RewardedAd.load(rewardedUnitId)
rewarded.rewardItem // what the ad unit grants, e.g. RewardItem("coins", 10)
val reward: RewardItem? = rewarded.show(host) // null if they closed it before earning the rewardA full-screen ad shows once. Its events run from Shown to Dismissed (or FailedToShow), with Impression,
Click, Paid and, for a rewarded ad, RewardEarned in between. The flow then completes. show throws
AdMobException when the ad can't be shown, for example AdErrorCode.ALREADY_USED or NOT_READY.
RewardedAd.setServerSideVerificationOptions sets the data for AdMob's server-side verification callback.
Every ad carries what an ad revenue tracker such as RevenueCat's needs. responseInfo.responseId is the per-fill id,
responseInfo.loadedAdapterResponseInfo?.adSourceName (or mediationAdapterClassName) is the network that filled the
ad, and AdEvent.Paid carries the value in micros, the currency and the precision. Impression-level ad revenue must be
on in the AdMob account settings for the SDK to report paid events.
NativeAd, InterstitialAd and RewardedAd have an android or ios property holding the SDK's own ad, readable in
that platform's source set, for anything common code doesn't reach.
./gradlew :admob:testAndroidHostTest # common and Android tests on the JVM
ANDROID_SERIAL=emulator-5554 ./gradlew :admob:connectedAndroidDeviceTest # the Next-Gen SDK on a device or emulator
./gradlew :admob:iosSimulatorArm64Test # common and iOS tests on a simulator, against the real SDKs
./gradlew -Padmob.pinIosSdkFloor :admob:iosSimulatorArm64Test # the same, against GoogleMobileAds 13.11.0 and UMP 3.1.0 exactly
./gradlew :admob:checkKotlinAbi # the public API against api/ (updateKotlinAbi rewrites it)
./gradlew :admob:publishToMavenLocalNETWORK_ERROR (connection refused). They run on every
connected device unless ANDROID_SERIAL names one, and CI doesn't run them.TIMEOUT. The tests therefore check that every call
reports back through the library, with a fill or an error. A filled ad needs an app.rm -rf .swiftpm-locks build admob/build. SwiftPM keeps a locked version its range still allows, Gradle doesn't
relink when only the resolved SDK changes, and stale Xcode dumps fail the build (KT-88106).MAINTAINING.md covers releases.
Apache License 2.0, see LICENSE. The library binds to, but doesn't include, the Google Mobile Ads and User Messaging Platform SDKs, which are Google's and licensed under their own terms.
Google Mobile Ads (AdMob) and the UMP consent SDK in Kotlin Multiplatform common code, on Android and iOS. It is
built on each platform's newest official SDK and calls it directly: the
GMA Next-Gen SDK on Android, which replaced play-services-ads,
and GoogleMobileAds 13 on iOS. On iOS that goes through Kotlin's SwiftPM import, the same mechanism as
firebase-multiplatform, so the app needs no Swift bridge. The
library calls no deprecated SDK API.
canRequestAds and reset, with the state as a
StateFlow.Flow (impression,
click, paid). Rendering stays native, with the platform ad, plus a few iOS view helpers.show that returns when the ad is closed (with the reward), and the
same events.What stays in the app: ad card layouts, caches of loaded ads, when to show a full-screen ad, and where revenue events go (RevenueCat, analytics).
// build.gradle.kts of the shared module
kotlin {
sourceSets {
commonMain.dependencies {
implementation("io.github.corneloaie:admob:0.1.0")
}
}
}The library has Android, iosArm64 and iosSimulatorArm64 targets only. If the shared module also targets the JVM, JS
or Wasm, add the dependency to a source set that only Android and iOS share (for example, a mobileMain source set
that androidMain and iosMain depend on).
The minimum SDK is 24. The library brings the GMA Next-Gen SDK
(com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk 1.6.0) and user-messaging-platform 4.0.0 as api
dependencies. The app must not depend on play-services-ads itself.
Add the AdMob app id to the app's manifest. UMP reads it there, and the library hands it to the Next-Gen SDK, which
takes it in code. Without it, AdMob.initialize() and the first ad load throw IllegalStateException:
<application>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy" />
</application>A small ContentProvider in the library's manifest (AdMobInitProvider, not exported) keeps the application
Context at startup. Starting the SDK and reading the consent state therefore need no Context.
Mediation adapters still depend on the legacy play-services-ads, which clashes with the Next-Gen SDK. As
Google's mediation guides say, exclude it from
every configuration of the app module:
configurations.configureEach {
exclude(group = "com.google.android.gms", module = "play-services-ads")
exclude(group = "com.google.android.gms", module = "play-services-ads-lite")
}The Next-Gen SDK works with AdMob mediation, not under a third-party mediation platform.
The Next-Gen SDK calls back on background threads. The library moves every callback to the main thread, and its suspending calls return there.
The library binds to the official GoogleMobileAds and UMP Swift packages without bundling them. Its Maven publication records both packages, and your app inherits them: GoogleMobileAds from 13.11.0 and UMP from 3.1.0, each up to the next major version. You don't add either package to Xcode yourself.
embedAndSignAppleFrameworkForXcode build phase, and build the shared framework as static
(binaries.framework { isStatic = true }). The Swift packages are static libraries, and a dynamic framework fails at
launch with dyld: Library not loaded.integrateEmbedAndSign and
integrateLinkagePackage tasks against your Xcode project; commit the project change it makes. An app that already
consumes firebase-multiplatform has done this once, and the same package now carries the ads SDKs too. Kotlin's
CocoaPods to SwiftPM migration guide and
firebase-multiplatform's
iOS linking notes
explain the mechanism.GADApplicationIdentifier (your AdMob app id) and the SKAdNetworkItems that Google lists in
its iOS quick start.from: 13.4.0, leaves
SwiftPM a version both accept; an exact pin below 13.11.0 doesn't.build/kotlin/swiftPMXcodeDumps in the root
project.Every call that shows something takes an AdHost: the Activity on Android, the UIViewController on iOS. Every other
call needs none. In Compose Multiplatform:
// commonMain
@Composable
expect fun currentAdHost(): AdHost
// androidMain (androidx.activity:activity-compose)
@Composable
actual fun currentAdHost(): AdHost = checkNotNull(LocalActivity.current) { "not hosted in an Activity" }
// iosMain
@Composable
actual fun currentAdHost(): AdHost = LocalUIViewController.currentThe suspending calls switch to the main thread themselves. They throw AdMobException when the SDK reports an error;
its error.code is an AdErrorCode that is the same on both platforms (NO_FILL, NETWORK_ERROR, TIMEOUT, ...).
error.platformCode and error.domain keep the SDK's own values.
Google's order is: update the consent info at every launch, show the form if consent is required, then start the SDK once ads may be requested.
suspend fun startAds(host: AdHost) {
try {
AdConsent.requestInfoUpdate(host)
AdConsent.loadAndShowConsentFormIfRequired(host)
} catch (e: AdMobException) {
// Offline, for example. Consent given in an earlier session still counts: check canRequestAds.
}
if (AdConsent.canRequestAds) {
AdMob.requestConfiguration = RequestConfiguration(
ageRestrictedTreatment = null, // or CHILD / TEEN: the age treatment for your users
maxAdContentRating = MaxAdContentRating.PG,
)
val status = AdMob.initialize() // returns once the mediation adapters have started
}
}AdConsent.state is a StateFlow<ConsentState> (consentStatus, canRequestAds, privacyOptionsRequirementStatus).
It updates as soon as requestInfoUpdate is called, not only when the request completes, because UMP loads the consent
saved in an earlier session right away. A returning user's ads therefore don't wait for the network.
val canRequestAds: StateFlow<Boolean> =
AdConsent.state.map { it.canRequestAds }.stateIn(scope, SharingStarted.Eagerly, false)
// A privacy settings entry, shown when the user must be able to change their choices:
if (AdConsent.privacyOptionsRequirementStatus == PrivacyOptionsRequirementStatus.REQUIRED) {
AdConsent.showPrivacyOptionsForm(host)
}
// Consent syncing: the same id in each of your apps shares the user's choices between them.
AdConsent.requestInfoUpdate(host, ConsentRequestParameters(consentSyncId = userUuid))
// Testing: appear in the EEA, and forget this device's answer.
AdConsent.requestInfoUpdate(
host,
ConsentRequestParameters(debugSettings = ConsentDebugSettings(DebugGeography.EEA, listOf("<hashed device id>"))),
)
AdConsent.reset()AdMob.initialize() starts the SDK once; later and concurrent calls wait for the same result. Set
AdMob.requestConfiguration before it. An ad load without it starts the SDK too, without waiting for the mediation
adapters, so with mediation call it first. To use the Ad Inspector, add the device to testDeviceIds and call
AdMob.openAdInspector(host).
val loader = NativeAdLoader(
adUnitId,
NativeAdOptions(
mediaAspectRatio = MediaAspectRatio.LANDSCAPE,
adChoicesPlacement = AdChoicesPlacement.TOP_RIGHT,
startMuted = true,
),
)
val ad: NativeAd = loader.load() // throws AdMobException, e.g. AdErrorCode.NO_FILL
ad.headline; ad.body; ad.callToAction; ad.icon; ad.mediaContent?.aspectRatio; ad.responseInfo?.responseId
scope.launch {
ad.events.collect { event ->
when (event) {
AdEvent.Impression -> {}
AdEvent.Click -> {}
is AdEvent.Paid -> event.value.let { it.valueMicros; it.currencyCode; it.precision }
else -> {}
}
}
}
ad.destroy() // once it is off screen for good; completes ad.eventsThe library wires the SDK's listeners when the ad loads, before load returns. Every collector of events receives
every event from the start, however late it starts collecting. The paid event, which the SDK only delivers to a
listener that was in place at impression time, is never lost. Each load is a request of its own; caching ads and
deciding when to load one stay in the app.
Rendering stays native, with the platform ad.
On Android, register ad.android (a com.google.android.libraries.ads.mobile.sdk.nativead.NativeAd) with the Next-Gen
SDK's NativeAdView:
// androidMain, e.g. in an AndroidView's update block; headline and mediaView (the Next-Gen SDK's MediaView) are
// children of nativeAdView
nativeAdView.headlineView = headline
headline.text = ad.headline
nativeAdView.registerNativeAd(ad.android, mediaView)On iOS, ad.ios is the GADNativeAd. The library adds three helpers for a card built in Kotlin:
// iosMain
val card = AttachRegisteringNativeAdView()
val headline = UILabel().apply { text = ad.headline }
val media = GADMediaView()
val badge = AdBadgeLabel().apply { text = "Ad" }
// The asset outlets are weak: add each view to the card first, then register it (Auto Layout constraints omitted).
listOf(headline, media, badge).forEach(card::addSubview)
card.headlineView = headline
card.mediaView = media
card.registerWhenAttached(ad) // sets nativeAd once the card is in a window and laid out
val height = preferredHeight(card, width = 360.0) // to frame its Compose UIKitViewAttachRegisteringNativeAdView sets its nativeAd only once it is in a window and laid out. A card set before then
(as Compose's UIKitView builds it) measures 0×0, and the SDK's ad validator reports its asset views as missing.AdBadgeLabel never gets smaller than the 15pt the validator requires for the "Ad" attribution.preferredHeight returns the card's Auto Layout height at a given width. The media view follows the creative's aspect
ratio, so every card has a different height.val interstitial = InterstitialAd.load(interstitialUnitId)
interstitial.show(host) // returns when the user closes it
val rewarded = RewardedAd.load(rewardedUnitId)
rewarded.rewardItem // what the ad unit grants, e.g. RewardItem("coins", 10)
val reward: RewardItem? = rewarded.show(host) // null if they closed it before earning the rewardA full-screen ad shows once. Its events run from Shown to Dismissed (or FailedToShow), with Impression,
Click, Paid and, for a rewarded ad, RewardEarned in between. The flow then completes. show throws
AdMobException when the ad can't be shown, for example AdErrorCode.ALREADY_USED or NOT_READY.
RewardedAd.setServerSideVerificationOptions sets the data for AdMob's server-side verification callback.
Every ad carries what an ad revenue tracker such as RevenueCat's needs. responseInfo.responseId is the per-fill id,
responseInfo.loadedAdapterResponseInfo?.adSourceName (or mediationAdapterClassName) is the network that filled the
ad, and AdEvent.Paid carries the value in micros, the currency and the precision. Impression-level ad revenue must be
on in the AdMob account settings for the SDK to report paid events.
NativeAd, InterstitialAd and RewardedAd have an android or ios property holding the SDK's own ad, readable in
that platform's source set, for anything common code doesn't reach.
./gradlew :admob:testAndroidHostTest # common and Android tests on the JVM
ANDROID_SERIAL=emulator-5554 ./gradlew :admob:connectedAndroidDeviceTest # the Next-Gen SDK on a device or emulator
./gradlew :admob:iosSimulatorArm64Test # common and iOS tests on a simulator, against the real SDKs
./gradlew -Padmob.pinIosSdkFloor :admob:iosSimulatorArm64Test # the same, against GoogleMobileAds 13.11.0 and UMP 3.1.0 exactly
./gradlew :admob:checkKotlinAbi # the public API against api/ (updateKotlinAbi rewrites it)
./gradlew :admob:publishToMavenLocalNETWORK_ERROR (connection refused). They run on every
connected device unless ANDROID_SERIAL names one, and CI doesn't run them.TIMEOUT. The tests therefore check that every call
reports back through the library, with a fill or an error. A filled ad needs an app.rm -rf .swiftpm-locks build admob/build. SwiftPM keeps a locked version its range still allows, Gradle doesn't
relink when only the resolved SDK changes, and stale Xcode dumps fail the build (KT-88106).MAINTAINING.md covers releases.
Apache License 2.0, see LICENSE. The library binds to, but doesn't include, the Google Mobile Ads and User Messaging Platform SDKs, which are Google's and licensed under their own terms.