I am integrating Admob's banners in my app, this app runs both in AndroidTV and Android, where it's running in mobile the dimensions must be 320x50(BANNER)
which is part of the standard sizes in the docs, but it turns of nowhere to 468x60(FULL_BANNER)
, this behavior happens oftentimes when you run the app. I am using Jetpack Compose for this, and the add is placed inside a LazyColumn which is the equivalent to a recycler view
My code for the banner is like this:
enum class BannerSize {
NORMAL,
RECTANGLE;
internal fun map(): AdSize = when (this) {
NORMAL -> AdSize.BANNER
RECTANGLE -> AdSize.MEDIUM_RECTANGLE
}
}
/*
This Composable goes inside a lazy column with other composable where I have a
when statement, where I look if the index is 0 or 5 which are the specific
indexes I want to place the ads.
*/
@Composable
internal fun BannerAd(
modifier: Modifier = Modifier,
size: BannerSize = BannerSize.NORMAL,
id: String = "TODO",
pos: String = "TODO",
adId: String,
) {
val isInEditMode = LocalInspectionMode.current
if (!isInEditMode) {
Box(
modifier = modifier
.fillMaxWidth()
.padding(20.dp),
contentAlignment = Alignment.Center
) {
AndroidView(
modifier = modifier
.height(size.map().height.dp)
.width(size.map().width.dp),
factory = { context ->
Napier.d(
tag = "Ads",
message = "Creating Ad, id: $id, adId: $adId, pos: $pos, size: $size"
)
AdView(context).apply {
adListener = object : AdListener() {
override fun onAdFailedToLoad(p0: LoadAdError) {
Napier.e(tag = "Ads", message = p0.message)
}
}
adSize = size.map()
adUnitId = adId
loadAd(
AdRequest.Builder()
.addNetworkExtrasBundle(
AdMobAdapter::class.java,
Bundle().also {
it.putString("pos", pos)
}
)
.build()
)
}
}
)
}
} else {
EditModeText()
}
}
Has someone encountered something like this while integrating ads with Compose? I've looking for some questions related to this, but I haven't found any
Well, after doing a lot research, turns out it was something related to Android view's lifecycle, to avoid this weird behaviour I did what is in this answer : AdManagerAdView not rendering ad image when off screen in LazyColumn
We must set the ad during on doOnLayout method, and It will fix this problem for now.