This guide covers loading an anchored adaptive banner ad into an Android app.
Prerequisites
- Complete the Get started guide.
Always test with test ads
When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.
The easiest way to load test ads is to use our dedicated test ad unit ID for Android banners:
/21775744923/example/adaptive-banner
It's been specially configured to return test ads for every request, and you can use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.
For more information about how the Google Mobile Ads SDK's test ads work, see Enable test ads.
Define the ad view
XML Layout
Add a view to your layout XML file to serve as the container for your anchored adaptive banner ad:
<!-- Ad view container that fills the width of the screen and adjusts its
height to the content of the ad. -->
<FrameLayout
android:id="@+id/ad_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true" />
Jetpack Compose
Step one, include the JetpackComposeDemo/compose-util module. This module includes helpers for composing the
AdView
object and assets.Step two, compose a
BannerAd
class using thecompose-util
module:
// Place the ad view at the bottom of the screen.
Column(modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) {
Box(modifier = modifier.fillMaxWidth()) { AdManagerBannerAd(adView, modifier) }
}
Load an ad
- Create a
BannerAdRequest
object with an ad unit ID and an anchored adaptive ad size. - Call
BannerAd.load()
. - Add
BannerAd.getView()
to the view hierarchy.
Kotlin
import com.google.android.libraries.ads.mobile.sdk.banner.AdSize
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAd
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdEventCallback
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRefreshCallback
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.LoadAdError
class MainActivity : Activity() {
private var bannerAd: BannerAd? = null
private lateinit var binding: ActivityMainBinding
private lateinit var adSize: AdSize
private lateinit var bannerViewContainer: FrameLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// 320 is a placeholder value. Replace 320 with your banner container width.
adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 320)
// Give the banner container a placeholder height to avoid a sudden layout
// shifts when the ad loads.
bannerViewContainer = binding.bannerViewContainer
val bannerLayoutParams = bannerViewContainer.layoutParams
bannerLayoutParams.height = adSize.getHeightInPixels(requireContext())
bannerViewContainer.layoutParams = bannerLayoutParams
// Step 1 - Create a BannerAdRequest object with ad unit ID and size.
val adRequest = BannerAdRequest.Builder("/21775744923/example/adaptive-banner", adSize).build()
// Step 2 - Load the ad.
BannerAd.load(
adRequest,
object : AdLoadCallback<BannerAd> {
override fun onAdLoaded(ad: BannerAd) {
// Assign the loaded ad to the BannerAd object.
bannerAd = ad
// Step 3 - Call BannerAd.getView() to get the View and add it
// to view hierarchy on the UI thread.
activity?.runOnUiThread {
binding.bannerViewContainer.addView(ad.getView(requireActivity()))
}
}
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
bannerAd = null
}
},
)
}
}
Java
import com.google.android.libraries.ads.mobile.sdk.banner.AdSize;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAd;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdEventCallback;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRefreshCallback;
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.LoadAdError;
public class MainActivity extends AppCompatActivity {
private BannerAd bannerAd;
private ActivityMainBinding binding;
private AdSize adSize;
private FrameLayout bannerViewContainer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 320 is a placeholder value. Replace 320 with your banner container width.
adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 320);
// Give the banner container a placeholder height to avoid a sudden layout
// shifts when the ad loads.
bannerViewContainer = binding.bannerViewContainer;
LayoutParams bannerLayoutParams = bannerViewContainer.getLayoutParams();
bannerLayoutParams.height = adSize.getHeightInPixels(this);
bannerViewContainer.setLayoutParams(bannerLayoutParams);
// Step 1 - Create a BannerAdRequest object with ad unit ID and size.
BannerAdRequest adRequest = new BannerAdRequest.Builder("/21775744923/example/adaptive-banner",
adSize).build();
// Step 2 - Load the ad.
BannerAd.load(
adRequest,
new AdLoadCallback<BannerAd>() {
@Override
public void onAdLoaded(@NonNull BannerAd ad) {
// Assign the loaded ad to the BannerAd object.
bannerAd = ad;
// Step 3 - Call BannerAd.getView() to get the View and add it
// to view hierarchy on the UI thread.
runOnUiThread(
() -> binding.bannerViewContainer.addView(ad.getView(MainActivity.this)));
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError adError) {
bannerAd = null;
}
});
}
}
Jetpack Compose
private suspend fun loadAdaptiveBannerAd(isPreviewMode: Boolean): BannerAd? =
suspendCoroutine { continuation ->
// Prevent loading the AdView if the app is in preview mode.
if (isPreviewMode) {
continuation.resume(null)
return@suspendCoroutine
}
// Request an anchored adaptive banner with a width of 360.
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(requireContext(), 360)
BannerAd.load(
BannerAdRequest.Builder(AD_UNIT_ID, adSize).build(),
object : AdLoadCallback<BannerAd> {
override fun onAdLoaded(ad: BannerAd) {
// Set an AdListener to receive callbacks for various ad events.
ad.adEventCallback =
object : BannerAdEventCallback {
override fun onAdImpression() {
Log.d(Constant.TAG, "Banner ad recorded an impression.")
}
override fun onAdClicked() {
Log.d(Constant.TAG, "Banner ad recorded a click.")
}
}
ad.bannerAdRefreshCallback =
object : BannerAdRefreshCallback {
override fun onAdRefreshed() {
showToast("Banner ad refreshed.")
Log.d(Constant.TAG, "Banner ad refreshed.")
}
override fun onAdFailedToRefresh(adError: LoadAdError) {
showToast("Banner ad failed to refresh.")
Log.w(Constant.TAG, "Banner ad failed to refresh: $adError")
}
}
showToast("Banner ad loaded.")
Log.d(Constant.TAG, "Banner ad loaded.")
continuation.resume(ad)
}
override fun onAdFailedToLoad(adError: LoadAdError) {
showToast("Banner failed to load.")
Log.w(Constant.TAG, "Banner ad failed to load: $adError")
continuation.resume(null)
}
},
)
}
Refresh an ad
If you configured your ad unit to refresh, you don't need to request another ad when the ad fails to load. The Google Mobile Ads SDK respects any refresh rate you specified in the Ad Manager UI. If you haven't enabled refresh, issue a new request. For more details on ad unit refresh, such as setting a refresh rate, see Refresh rate for ads in mobile apps.
Release an ad resource
When you are finished using a banner ad, you can release the banner ad's resources.
To release the ad's resource, you remove the ad from the view hierarchy and drop all its references:
Kotlin
// Remove banner from view hierarchy.
val parentView = adView?.parent
if (parentView is ViewGroup) {
parentView.removeView(adView)
}
// Destroy the banner ad resources.
adView?.destroy()
// Drop reference to the banner ad.
adView = null
Java
// Remove banner from view hierarchy.
if (adView.getParent() instanceof ViewGroup) {
((ViewGroup) adView.getParent()).removeView(adView);
}
// Destroy the banner ad resources.
adView.destroy();
// Drop reference to the banner ad.
adView = null;
Jetpack Compose
// Destroy the ad when the screen is disposed.
DisposableEffect(Unit) {
onDispose {
bannerAdState?.destroy()
}
}
Ad events
You can listen for a number of events in the ad's lifecycle, including ad impression and click, as well as ad opening and closing. It is recommended to set the callback before showing the banner.Kotlin
BannerAd.load(
BannerAdRequest.Builder("/21775744923/example/adaptive-banner", adSize).build(),
object : AdLoadCallback<BannerAd> {
override fun onAdLoaded(ad: BannerAd) {
ad.adEventCallback =
object : BannerAdEventCallback {
override fun onAdImpression() {
// Banner ad recorded an impression.
}
override fun onAdClicked() {
// Banner ad recorded a click.
}
override fun onAdShowedFullScreenContent() {
// Banner ad showed.
}
override fun onAdDismissedFullScreenContent() {
// Banner ad dismissed.
}
override fun onAdFailedToShowFullScreenContent(
fullScreenContentError: FullScreenContentError
) {
// Banner ad failed to show.
}
}
}
// ...
}
)
Java
BannerAd.load(
new BannerAdRequest.Builder("/21775744923/example/adaptive-banner", adSize).build(),
new AdLoadCallback<BannerAd>() {
@Override
public void onAdLoaded(@NonNull BannerAd ad) {
ad.setAdEventCallback(new BannerAdEventCallback() {
@Override
public void onAdImpression() {
// Banner ad recorded an impression.
}
@Override
public void onAdClicked() {
// Banner ad recorded a click.
}
@Override
public void onAdShowedFullScreenContent() {
// Banner ad showed.
}
@Override
public void onAdDismissedFullScreenContent() {
// Banner ad dismissed.
}
@Override
public void onAdFailedToShowFullScreenContent(
@NonNull FullScreenContentError fullScreenContentError) {
// Banner ad failed to show.
}
});
// ...
}
});
Ad refresh callback
The BannerAdRefreshCallback
handles ad refreshing events if you use automatic refresh
for banner ads. Make sure to set the callback before the you add the ad view to
your view hierarchy. For details on ad refreshing, see
Refresh an ad.
Kotlin
BannerAd.load(
BannerAdRequest.Builder("/21775744923/example/adaptive-banner", adSize).build(),
object : AdLoadCallback<BannerAd> {
override fun onAdLoaded(ad: BannerAd) {
ad.bannerAdRefreshCallback =
object : BannerAdRefreshCallback {
// Set the ad refresh callbacks.
override fun onAdRefreshed() {
// Called when the ad refreshes.
}
override fun onAdFailedToRefresh(loadAdError: LoadAdError) {
// Called when the ad fails to refresh.
}
}
// ...
}
}
)
Java
BannerAd.load(
new BannerAdRequest.Builder("/21775744923/example/adaptive-banner", adSize).build(),
new AdLoadCallback<BannerAd>() {
@Override
public void onAdLoaded(@NonNull BannerAd ad) {
ad.setBannerAdRefreshCallback(
// Set the ad refresh callbacks.
new BannerAdRefreshCallback() {
@Override
public void onAdRefreshed() {
// Called when the ad refreshes.
}
@Override
public void onAdFailedToRefresh(@NonNull LoadAdError adError) {
// Called when the ad fails to refresh.
}
});
// ...
}
});
Hardware acceleration for video ads
In order for video ads to show successfully in your banner ad views, hardware acceleration must be enabled.
Hardware acceleration is enabled by default, but some apps may choose to disable
it. If this applies to your app, we recommend enabling hardware acceleration for
Activity
classes that use ads.
Enabling hardware acceleration
If your app does not behave properly with hardware acceleration turned on
globally, you can control it for individual activities as well. To enable or
disable hardware acceleration, you can use the android:hardwareAccelerated
attribute for the
<application>
and
<activity>
elements in your AndroidManifest.xml
. The following example enables hardware
acceleration for the entire app but disables it for one activity:
<application android:hardwareAccelerated="true">
<!-- For activities that use ads, hardwareAcceleration should be true. -->
<activity android:hardwareAccelerated="true" />
<!-- For activities that don't use ads, hardwareAcceleration can be false. -->
<activity android:hardwareAccelerated="false" />
</application>
See the Hardware acceleration guide for more information about options for controlling hardware acceleration. Note that individual ad views cannot be enabled for hardware acceleration if the activity is disabled, so the activity itself must have hardware acceleration enabled.
Download and run the example app that demonstrates the use of the Next Gen Google Mobile Ads SDK.