Banner ads

Banner ads are rectangular ads that occupy a portion of an app's layout. They stay on screen while users are interacting with the app, either anchored at the top or bottom of the screen or inline with content as the user scrolls. Banner ads can refresh automatically after a certain period of time. See Overview of banner ads for more information.

This guide shows you how to get started with anchored adaptive banner ads, which maximizes performance by optimizing the ad size for each device using an ad width you specify.

Anchored adaptive banner ads are fixed aspect ratio ads rather than the regular fixed size ads. The aspect ratio is similar to 320x50 industry standard. Once you specify the full width available, it will return you an ad with optimal height for that width. The optimal height doesn't change across requests from the same device, and the surrounding views don't need to move when the ad refreshes.

Prerequisites

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 Mobile Ads SDK's test ads work, see Test Ads.

Add AdManagerAdView to the layout

You create a banner by determining the ad size. Complete the following steps:

  1. Create a full-width anchored adaptive ad size:

    Java

    // Get the ad size with screen width.
    public AdSize getAdSize() {
      DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
      int adWidthPixels = displayMetrics.widthPixels;
    
      if (VERSION.SDK_INT >= VERSION_CODES.R) {
        WindowMetrics windowMetrics = this.getWindowManager().getCurrentWindowMetrics();
        adWidthPixels = windowMetrics.getBounds().width();
      }
    
      float density = displayMetrics.density;
      int adWidth = (int) (adWidthPixels / density);
      return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth);
    }
    

    Kotlin

    // Get the ad size with screen width.
    private val adSize: AdSize
      get() {
        val displayMetrics = resources.displayMetrics
        val adWidthPixels =
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val windowMetrics: WindowMetrics = this.windowManager.currentWindowMetrics
            windowMetrics.bounds.width()
          } else {
            displayMetrics.widthPixels
          }
        val density = displayMetrics.density
        val adWidth = (adWidthPixels / density).toInt()
        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth)
      }
    
    
  2. Create an AdManagerAdView using the ad size and add it to your app's layout:

    Java

    // Create a new ad view.
    adView = new AdManagerAdView(this);
    adView.setAdUnitId(AD_UNIT);
    adView.setAdSize(getAdSize());
    
    // Replace ad container with new ad view.
    adContainerView.removeAllViews();
    adContainerView.addView(adView);
    

    Kotlin

    // Create a new ad view.
    val adView = AdManagerAdView(this)
    adView.adUnitId = AD_UNIT_ID
    adView.setAdSize(adSize)
    this.adView = adView
    
    // Replace ad container with new ad view.
    binding.adViewContainer.removeAllViews()
    binding.adViewContainer.addView(adView)
    

Load an ad

Once the AdManagerAdView is in place, the next step is to load an ad. That's done with the loadAd() method in the AdManagerAdView class. It takes an AdManagerAdRequest parameter, which holds runtime information, such as targeting info, about a single ad request.

Here's an example that shows how to load an ad:

Java

// Start loading the ad in the background.
AdManagerAdRequest adRequest = new AdManagerAdRequest.Builder().build();
adView.loadAd(adRequest);

Kotlin

// Start loading the ad in the background.
val adRequest = AdManagerAdRequest.Builder().build()
adView.loadAd(adRequest)

If successful, your app is ready to display banner ads.

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.

Ad events

You can listen for a number of events in the ad's lifecycle, including loading, ad impression and click, as well as ad open and close events. It is recommended to set the callback before loading the banner.

Java

adView.setAdListener(new AdListener() {
    @Override
    public void onAdClicked() {
      // Code to be executed when the user clicks on an ad.
    }

    @Override
    public void onAdClosed() {
      // Code to be executed when the user is about to return
      // to the app after tapping on an ad.
    }

    @Override
    public void onAdFailedToLoad(LoadAdError adError) {
      // Code to be executed when an ad request fails.
    }

    @Override
    public void onAdImpression() {
      // Code to be executed when an impression is recorded
      // for an ad.
    }

    @Override
    public void onAdLoaded() {
      // Code to be executed when an ad finishes loading.
    }

    @Override
    public void onAdOpened() {
      // Code to be executed when an ad opens an overlay that
      // covers the screen.
    }
});

Kotlin

adView.adListener = object: AdListener() {
    override fun onAdClicked() {
      // Code to be executed when the user clicks on an ad.
    }

    override fun onAdClosed() {
      // Code to be executed when the user is about to return
      // to the app after tapping on an ad.
    }

    override fun onAdFailedToLoad(adError : LoadAdError) {
      // Code to be executed when an ad request fails.
    }

    override fun onAdImpression() {
      // Code to be executed when an impression is recorded
      // for an ad.
    }

    override fun onAdLoaded() {
      // Code to be executed when an ad finishes loading.
    }

    override fun onAdOpened() {
      // Code to be executed when an ad opens an overlay that
      // covers the screen.
    }
}

Each of the overridable methods in AdListener corresponds to an event in the lifecycle of an ad.

Overridable methods
onAdClicked() The onAdClicked() method is invoked when a click is recorded for an ad.
onAdClosed() The onAdClosed() method is invoked when a user returns to the app after viewing an ad's destination URL. Your app can use it to resume suspended activities or perform any other work necessary to make itself ready for interaction.
onAdFailedToLoad() The onAdFailedToLoad() method is the only one that includes a parameter. The error parameter of type LoadAdError describes what error occurred. For more information, refer to the Debugging Ad Load Errors documentation.
onAdImpression() The onAdImpression() method is invoked when an impression is recorded for an ad.
onAdLoaded() The onAdLoaded() method is executed when an ad has finished loading. If you want to delay adding the AdManagerAdView to your activity or fragment until you're sure an ad will be loaded, for example, you can do so here.
onAdOpened() The onAdOpened() method is invoked when an ad opens an overlay that covers the screen.

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.

Manual impression counting

Manual impression counting is compatible only with direct-sold and house campaigns with creatives trafficked directly in Ad Manager. It shouldn't be used for backfill or third-party networks ads. For more details, see Counting impressions and clicks.

You can manually send impression pings to Ad Manager if you have special conditions for when an impression should be recorded. To do this, enable an AdManagerAdRequest for manual impressions before loading an ad:

Java

AdManagerAdRequest adRequest = new AdManagerAdRequest.Builder()
    .setManualImpressionsEnabled(true)
    .build();

Kotlin

val adRequest = AdManagerAdRequest.Builder()
    .setManualImpressionsEnabled(true)
    .build()

When you determine that an ad has been successfully returned and is on-screen, you can manually record an impression:

Java

AdManagerAdView.recordManualImpression();

Kotlin

AdManagerAdView.recordManualImpression()

App events

App events let you create ads that can send messages to their app code. The app can then take actions based on these messages.

You can listen for Ad Manager specific app events using AppEventListener. These events can occur at any time during the ad's lifecycle, even before onAdLoaded() is called.

Java

public interface AppEventListener {
  void onAppEvent(String name, String info);
}

Kotlin

interface AppEventListener {
    fun onAppEvent(name: String, info: String)
}

void onAppEvent(String name, String info) is called when an app event occurs in an ad. This interface can be implemented by your activity or any other object:

Java

import com.google.android.gms.ads.admanager.*;

public class BannerExample extends Activity implements AppEventListener {
}

Kotlin

import com.google.android.gms.ads.admanager.*

class BannerExample : Activity(), AppEventListener {
}

and then passed to the AdManagerAdView:

Java

AdManagerAdView.setAppEventListener(this);

Kotlin

AdManagerAdView.appEventListener = this

Here is an example showing how to change the background color of your app depending on an app event with a name of color:

Java

@Override
public void onAppEvent(String name, String info) {
  if ("color".equals(name)) {
    if ("green".equals(info)) {
      // Set background color to green.
    } else if ("blue".equals(info)) {
      // Set background color to blue.
    } else {
      // Set background color to black.
    }
  }
}

Kotlin

override fun onAppEvent(name: String?, info: String?) {
    if (name == "color") {
        when (info) {
            "green" -> {
                // Set background color to green.
            }
            "blue" -> {
                // Set background color to blue.
            }
            else -> {
                // Set background color to black.
            }
        }
    }
}

And, here is the corresponding creative that sends color app event messages to the Listener:

<html>
<head>
  <script src="//www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      // Send a color=green event when ad loads.
      admob.events.dispatchAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.dispatchAppEvent("color", "blue");
      });
    });
  </script>
  <style>
    #ad {
      width: 320px;
      height: 50px;
      top: 0px;
      left: 0px;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="ad">Carpe diem!</div>
</body>
</html>

See the Ad Manager App Events example for an implementation of app events in the API Demo app.

Java Kotlin

Additional resources

Examples on GitHub

  • Anchored adaptive banner ads example: Java | Kotlin

Next steps

Collapsible banners

Collapsible banner ads are banner ads that are initially presented as a larger overlay, with a button to collapse the ad to a smaller size. Consider using it to further optimize your performance. See collapsible banner ads for more details.

Inline adaptive banners

Inline adaptive banners are larger, taller banners compared to anchored adaptive banners. They are of variable height, and can be as tall as the device screen. Inline adaptive banners are recommended over anchored adaptive banner ads for apps that place banner ads in scrollable content. See inline adaptive banners for more details.

Explore other topics