Banner Ads

Banner ads are rectangular image or text ads that occupy a spot within an app's layout. 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 DFP into an Android app. In addition to code snippets and instructions, it also includes information about sizing banners properly and links to additional resources.


Add PublisherAdView to the layout

The first step toward displaying a banner is to place PublisherAdView 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 PublisherAdView at the bottom of an Activity:


<RelativeLayout xmlns:android=""

        <TextView android:text="@string/hello_world"
            android:layout_height="wrap_content" />



Note the following required attributes:

  • ads:adSize - Set this to the ad size you'd like to use (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 PublisherAdView programmatically:

PublisherAdView adView = new PublisherAdView(this);
// TODO: Add adView to your view hierarchy.

Always test with test ads

The sample code above contains an ad unit ID and you're free to request ads with it. It's been specially configured to return test ads rather than production ads for every request, which makes it safe to use.

Testing with real ads (even if you never tap on them) is against DFP policy and can cause your account to be suspended. See Test Ads for information on how you can make sure you always get test ads when developing.

Load an ad

Once the PublisherAdView is in place, the next step is to load an ad. That's done with the loadAd() method in the PublisherAdView class. It takes an PublisherAdRequest 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: (excerpt)

package ...

import ...

public class MainActivity extends AppCompatActivity {
    private PublisherAdView mPublisherAdView;

    protected void onCreate(Bundle savedInstanceState) {

        mPublisherAdView = (PublisherAdView) findViewById(;
        PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();

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 PublisherAdView, simply call the setAdListener() method:

mPublisherAdView.setAdListener(new AdListener() {
    public void onAdLoaded() {
        // Code to be executed when an ad finishes loading.
        Log.i("Ads", "onAdLoaded");

    public void onAdFailedToLoad(int errorCode) {
        // Code to be executed when an ad request fails.
        Log.i("Ads", "onAdFailedToLoad");

    public void onAdOpened() {
        // Code to be executed when an ad opens an overlay that
        // covers the screen.
        Log.i("Ads", "onAdOpened");

    public void onAdLeftApplication() {
        // Code to be executed when the user has left the app.
        Log.i("Ads", "onAdLeftApplication");

    public void onAdClosed() {
        // Code to be executed when when the user is about to return
        // to the app after tapping on an ad.
        Log.i("Ads", "onAdClosed");

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

Overridable methods
onAdLoaded() The onAdLoaded() method is executed when an ad has finished loading. If you want to delay adding the PublisherAdView to your activity or fragment until you're sure an ad will be loaded, for example, you can do so here. If you're using a third-party analytics package to track impressions, this is also where you can place the call to record them.
onAdFailedToLoad() The onAdFailedToLoad() method is the only one that includes a parameter. The errorCode parameter indicates what type of failure occurred. The possible values are defined as constants in the PublisherAdRequest class:
  • ERROR_CODE_INTERNAL_ERROR - Something happened internally; for instance, an invalid response was received from the ad server.
  • ERROR_CODE_INVALID_REQUEST - The ad request was invalid; for instance, the ad unit ID was incorrect.
  • ERROR_CODE_NETWORK_ERROR - The ad request was unsuccessful due to network connectivity.
  • ERROR_CODE_NO_FILL - The ad request was successful, but no ad was returned due to lack of ad inventory.
onAdOpened() This method is invoked when the user taps on an ad. If you're using an analytics package to track clickthroughs, this is a good place to record one.
onAdLeftApplication() This method is invoked after onAdOpened(), when a user click opens another app (such as the Google Play), backgrounding the current app.
onAdClosed() When a user returns to the app after viewing an ad's destination URL, this method is invoked. Your app can use it to resume suspended activities or perform any other work necessary to make itself ready for interaction.

The following banner sizes are supported:

Size (WxH) Description Availability AdSize constant
320x50 Standard 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
Screen width x 32|50|90 Smart Banner Phones and Tablets SMART_BANNER

Smart Banners

Smart Banners are ad units that render screen-width banner ads on any screen size across different devices in either orientation. Smart Banners help deal with increasing screen fragmentation across different devices by "smartly" detecting the width of the device in its current orientation and making the ad view that size.

Three ad heights are implemented in smart banners:

Ad height Screen height
32dp ≤ 400dp
50dp > 400dp and ≤ 720dp
90dp > 720dp

Typically, Smart Banners on phones have a height of 50dp in portrait and 32dp in landscape. On tablets, height is normally 90dp in both orientations.

When an image ad isn't large enough to take up the entire allotted space, the image will be centered, and the space on either side will be filled in.

To use Smart Banners in XML, specify the constant SMART_BANNER for the ad size and set the width of the AdView to match_parent. For example:


To create a Smart Banner programmatically, use AdSize.SMART_BANNER as the ad size:

PublisherAdView adView = new PublisherAdView(this);

Custom ad size

In addition to the standard ad units, DFP 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 (PublisherAdView in the following example) displayed on the application.


// Define custom AdSize of 250x250 for PublisherAdView

AdSize customAdSize = new AdSize(250, 250);
PublisherAdView adView = new PublisherAdView(this);

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

Multiple ad sizes

DFP allows you to specify multiple ad sizes which may be eligible to serve into a PublisherAdView. 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:

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

If PublisherAdView 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.

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

The PublisherAdView 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:

   ads:adUnitId="YOUR_AD_UNIT_ID" />

See the DFP 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 DFP if you have special conditions for when an impression should be recorded. To do this, enable a PublisherAdRequest for manual impressions before loading an ad:

PublisherAdRequest adRequest = new PublisherAdRequest.Builder()

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


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 DFP specific app events using AppEventListener. These events may occur at any time during the ad's lifecycle, even before onAdLoaded() is called.

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

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:


public class BannerExample extends Activity implements AppEventListener {

and then passed to the PublisherAdView:


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

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.

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

  <script src="//"></script>
    // Send a color=green event when ad loads."color", "green");

    handleClick = function() {
      // Send a color=blue event when ad is clicked."color", "blue");
    #ad {
      width: 320px;
      height: 50px;
      top: 0px;
      left: 0px;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
  <div id="ad" onClick="handleClick()">Carpe diem!</div>

See the DFP App Events example for an implementation of app events in the Android API Demo app.

Additional resources


Mobile Ads Garage video tutorials

Next steps

Send feedback about...

SDK for DFP Users on Android
Need help? Visit our support page.