Banner Ads

Banner ads occupy a spot within an app's layout, either at the top or bottom of the device screen. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. If you're new to mobile advertising, they're a great place to start.

This guide shows you how to integrate banner ads from Ad Manager into an Android app. In addition to code snippets and instructions, it also includes information about sizing banners properly and links to additional resources.

Prerequisites

Add AdManagerAdView to the layout

The first step toward displaying a banner is to place AdManagerAdView in the layout for the Activity or Fragment in which you'd like to display it. The easiest way to do this is to add one to the corresponding XML layout file. Here's an example that shows an activity's AdManagerAdView:

# main_activity.xml
...
  <com.google.android.gms.ads.admanager.AdManagerAdView
      xmlns:ads="http://schemas.android.com/apk/res-auto"
      android:id="@+id/adManagerAdView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_alignParentBottom="true"
      ads:adSize="BANNER"
      ads:adUnitId="/6499/example/banner">
  </com.google.android.gms.ads.admanager.AdManagerAdView>
...

Note the following required attributes:

  • ads:adSize - Set this to the ad size you'd like to use. If you don't want to use the standard size defined by the constant, you can set a custom size instead. See the banner size section below for details.
  • ads:adUnitId - Set this to the unique identifier given to the ad unit in your app where ads are to be displayed. If you show banner ads in different activities, each would require an ad unit.

You can alternatively create AdManagerAdView programmatically:

Java

AdManagerAdView adView = new AdManagerAdView(this);

adView.setAdSizes(AdSize.BANNER);

adView.setAdUnitId("/6499/example/banner");
// TODO: Add adView to your view hierarchy.

Kotlin

val adView = AdManagerAdView(this)

adView.adSizes = AdSize.BANNER

adView.adUnitId = "/6499/example/banner"
// TODO: Add adView to your view hierarchy.

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:

/6499/example/banner

It's been specially configured to return test ads for every request, and you're free to 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.

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 in the onCreate() method of an Activity:

MainActivity (excerpt)

Java

package ...

import ...
import com.google.android.gms.ads.admanager.AdManagerAdRequest;
import com.google.android.gms.ads.admanager.AdManagerAdView;

public class MainActivity extends AppCompatActivity {
    private AdManagerAdView mAdManagerAdView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAdManagerAdView = findViewById(R.id.adManagerAdView);
        AdManagerAdRequest adRequest = new AdManagerAdRequest.Builder().build();
        mAdManagerAdView.loadAd(adRequest);
    }
}

Kotlin

package ...

import ...
import com.google.android.gms.ads.admanager.AdManagerAdRequest
import com.google.android.gms.ads.admanager.AdManagerAdView

class MainActivity : AppCompatActivity() {

    lateinit var mAdManagerAdView : AdManagerAdView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mAdManagerAdView = findViewById(R.id.adManagerAdView)
        val adRequest = AdManagerAdRequest.Builder().build()
        mAdManagerAdView.loadAd(adRequest)
    }
}

That's it! Your app is now ready to display banner ads.

Ad events

To further customize the behavior of your ad, you can hook onto a number of events in the ad's lifecycle: loading, opening, closing, and so on. You can listen for these events through the AdListener class.

To use an AdListener with AdManagerAdView, call the setAdListener() method:

Java

mAdManagerAdView.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

mAdManagerAdView.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.

The table below lists the standard banner sizes.

Size in dp (WxH) Description Availability AdSize constant
320x50 Banner Phones and Tablets BANNER
320x100 Large Banner Phones and Tablets LARGE_BANNER
300x250 IAB Medium Rectangle Phones and Tablets MEDIUM_RECTANGLE
468x60 IAB Full-Size Banner Tablets FULL_BANNER
728x90 IAB Leaderboard Tablets LEADERBOARD
Provided width x Adaptive height Adaptive banner Phones and Tablets N/A
Screen width x 32|50|90 Smart banner Phones and Tablets SMART_BANNER
Learn more about Adaptive Banners, intended to replace Smart Banners.

To define a custom banner size, set your desired AdSize, as shown here:

Java

AdSize adSize = new AdSize(300, 50);

Kotlin

val adSize = AdSize(300, 50)

Custom ad size

In addition to the standard ad units, Google Ad Manager allows you to serve any sized ad unit into an application. The ad size (width, height) defined for an ad request should match the dimensions of the ad view (AdManagerAdView in the following example) displayed on the application.

Example:

Java

// Define custom AdSize of 250x250 for AdManagerAdView

AdSize customAdSize = new AdSize(250, 250);
AdManagerAdView adView = new AdManagerAdView(this);
adView.setAdSizes(customAdSize);

Kotlin

// Define custom AdSize of 250x250 for AdManagerAdView

val customAdSize = AdSize(250, 250)
val adView = AdManagerAdView(this)
adView.setAdSizes(customAdSize)

See the Ad Manager Multiple Ad Sizes example for an implementation of custom ad size in the Android API Demo app.

Multiple ad sizes

Ad Manager allows you to specify multiple ad sizes which may be eligible to serve into a AdManagerAdView. Before implementing this feature in the SDK, create a line item targeting the same ad unit which is associated with different size creatives.

In your application, simply pass multiple AdSize parameters into setAdSizes:

Java

AdManagerAdView adView = new AdManagerAdView(this);
adView.setAdSizes(AdSize.BANNER, new AdSize(120, 20), new AdSize(250, 250));

Kotlin

val adView = AdManagerAdView(this)
adView.setAdSizes(AdSize.BANNER, AdSize(120, 20), AdSize(250, 250))

If AdManagerAdView changes size at refresh time, your layout should be able to automatically adapt to the new size.

If you need to change your supported ad sizes at any point in your application, simply call setAdSizes with the new list of sizes.

Java

// Drop support for 120x20 ad size.
adView.setAdSizes(AdSize.BANNER, new AdSize(250, 250));

Kotlin

// Drop support for 120x20 ad size.
adView.setAdSizes(AdSize.BANNER, AdSize(250, 250))

The AdManagerAdView will default to the size passed in the first parameter until the next ad returns.

You can also specify multiple ad sizes using the ads:adSizes attribute in your XML layout file:

<com.google.android.gms.ads.admanager.AdManagerAdView
   android:id="@+id/multiple_ad_sizes_view"
   android:layout_width="wrap_parent"
   android:layout_height="wrap_content"
   android:layout_alignParentBottom="true"
   android:layout_centerHorizontal="true"
   ads:adSizes="BANNER,120x20,250x250"
   ads:adUnitId="ad unit ID" />

See the Ad Manager Multiple Ad Sizes example for an implementation of multiple ad sizes in the Android API Demo app.

Manual impression counting

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 a 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

mAdManagerAdView.recordManualImpression();

Kotlin

mAdManagerAdView.recordManualImpression()

App events

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

You can listen for Ad Manager specific app events using AppEventListener. These events may 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 may 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

mAdManagerAdView.setAppEventListener(this);

Kotlin

mAdManagerAdView.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 Android API Demo app.

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 HW 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.

Additional resources

Examples on GitHub

Mobile Ads Garage video tutorials

Next steps

Learn more about user privacy.