AI Integration Agent Instructions for Android Banner Ads
Required Imports
Use the following imports to implement a banner ad:
import com.google.android.libraries.ads.mobile.sdk.banner.AdSize
import com.google.android.libraries.ads.mobile.sdk.banner.AdView
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAd
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRequest
import com.google.android.libraries.ads.mobile.sdk.common.AdLoadCallback
import com.google.android.libraries.ads.mobile.sdk.common.LoadAdErrorMethod Signatures
Use the following method signatures to implement banner ads:
The BannerAdRequest object takes the ad unit ID and AdSize:
BannerAdRequest.Builder(adUnitId: String, adSize: AdSize).build()The method signature to load a banner ad from AdView:
fun loadAd(
adRequest: BannerAdRequest,
adLoadCallback: AdLoadCallback<BannerAd>
): UnitThe AdLoadCallback interface is defined as:
interface AdLoadCallback<T> {
fun onAdLoaded(ad: T): Unit
fun onAdFailedToLoad(adError: LoadAdError): Unit
}Gotchas
UI Threading: MANDATORY: Callbacks in GMA-Next Gen SDK are invoked on a
background thread. ALL UI-RELATED OPERATIONS (e.g., Toasts, View updates,
Fragment transactions) MUST be wrapped in runOnUiThread {} or
Dispatchers.Main.launch {} within GMA SDK callbacks. SKIPPING THIS STEP WILL
CAUSE THE APPLICATION TO CRASH.
Banner Ad workflow
Define the ad view
- Use
AdViewfor defining GMA Next-Gen SDK banners instead of the deprecatedBannerAd.
- Use
Set the ad size:
- Set the
widthyou use forAdSizeto360for testing purposes. Mention using the device width is also a common approach. - Use the appropriate
AdSizemethod and test ad unit ID (ca-app-pub-3940256099942544/9214589741) based on the ad type:- For a large anchored adaptive banner: Use
AdSize.getLargeAnchoredAdaptiveBannerAdSize(context, width).- If given feedback that large anchored adaptive banners are too
tall, use
AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(context, width).
- If given feedback that large anchored adaptive banners are too
tall, use
- For an inline adaptive banner: Use
AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(context, width).
- For a large anchored adaptive banner: Use
- Pass the
AdSizeand ad unit ID to theBannerAdRequest.Builder, not directly on theAdView.
- Set the
Register for ad load events:
- Pass the
AdLoadCallbackimplementation in theloadAd()method, not directly on theAdView.
- Pass the
Load the banner ad:
Verify the implementation: Check the build to ensure there are no compile errors:
- Run
gradle build -x testto confirm a successful clean build. Resolve any GMA SDK related compile errors.
- Run
Links
Additional documentation: