Google Mobile Ads SDK

DoubleClick For Publishers (DFP) Banner Ads

This document provides instructions for using the Google Mobile Ads SDK to display banner ads. After downloading and installing the SDK to your development environment, select your platform in the next section to begin.

Sample projects with code examples from this document are available for download:

Android (Google Play)
  1. Adding a PublisherAdView
  2. Creating your banner in XML
  3. Custom ad size
  4. Multiple ad sizes
  5. Custom targeting
  6. Location targeting
  1. Setting publisher provided identifiers
  2. Setting a content URL
  3. App events
  4. Manual impression counting
  5. com.google.android.gms.ads.AdListener
  6. Getting support

Adding a PublisherAdView

Android apps are composed of View objects, which are Java instances the user sees as text areas, buttons and other controls. PublisherAdView is simply another View subclass displaying small HTML5 ads that respond to user touch.

Like any View, a PublisherAdView may be created either purely in code or largely in XML.

Here are the five steps to add a banner:

  • Import com.google.android.gms.ads.* and com.google.android.gms.ads.doubleclick.*
  • Declare a PublisherAdView instance
  • Set the DFP ad unit ID and ad size(s)
  • Add the view to the UI
  • Load it with an ad

The easiest place to do all this is in your app's Activity.

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

public class BannerExample extends Activity {
  private PublisherAdView adView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Create the adView
    adView = new PublisherAdView(this);
    adView.setAdUnitId(MY_AD_UNIT_ID);
    adView.setAdSizes(AdSize.BANNER);

    // Lookup your LinearLayout assuming it's been given
    // the attribute android:id="@+id/mainLayout"
    LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);

    // Add the adView to it
    layout.addView(adView);

    // Initiate a generic request to load it with an ad
    adView.loadAd(new PublisherAdRequest.Builder().build());
  }

  @Override
  public void onPause() {
    adView.pause();
    super.onPause();
  }

  @Override
  public void onResume() {
    super.onResume();
    adView.resume();
  }

  @Override
  public void onDestroy() {
    adView.destroy();
    super.onDestroy();
  }
}

The result

When you run your app you should see a banner on the screen:

Custom ad size

In addition to the standard AdMob ad units, DFP allows you to serve any sized ad unit into an application. Note that the ad size (width, height) defined for an ad request should match the dimensions of the ad view displayed on the application (i.e. PublisherAdView).

Example:

// Define custom AdSize of 250x250 for PublisherAdView

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

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(new AdSize(250, 250), AdSize.BANNER);

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

Custom targeting

You can pass custom key-value pairs to target DFP campaigns (line items). Out of respect for user privacy, Google asks that you only specify location and demographic data if that information is already used by your app.

Example:

// Example: Pass custom targeting "Age=25", "Color=Blue,Green,Red"
private PublisherAdRequest createRequest() {
  Bundle bundle = new Bundle();
  bundle.putString("Age", "25");
  bundle.putString("Color", "Blue,Green,Red");
  return  new PublisherAdRequest.Builder()
      .addNetworkExtras(new AdMobExtras(bundle))
      .build();
}

Location targeting

DFP can use precise location to improve geotargeting. The location is set using setLocation() method.

Note: This feature needs to be enabled for each network individually. Publishers should contact their customer representative to have this feature enabled.

Here's an example of how to set location before loading the ad request:

Location location = new Location("");
// New York
location.setLatitude(40.764316);
location.setLongitude(-73.977245);
location.setAccuracy(100);
PublisherAdRequest request = new PublisherAdRequest.Builder()
    .setLocation(location)
    .build();
adView.loadAd(request);

Setting publisher provided identifiers

You can set a publisher provided identifier (PPID) for use in frequency capping, audience segmentation and targeting, sequential ad rotation, and other audience-based ad delivery controls across devices.

Note: This feature is not available to all publishers. See this article for details.

Here's an example of setting the PPID:

PublisherAdRequest request = new PublisherAdRequest.Builder()
    .setPublisherProvidedId("AB123456789")
    .build();

Setting a content URL

To provide a URL for content related to your app, you can call PublisherAdRequest.Builder.setContentUrl when building a PublisherAdRequest:

PublisherAdRequest requestWithContent = new PublisherAdRequest.Builder()
    .setContentUrl("http://googleadsdeveloper.blogspot.com/2014/03/monetizing-unity-mobile-apps-just-got.html")
    .build();

App events

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

public interface AppEventListener {
  void onAppEvent(String name, String info);
}
void onAppEvent(String name, String info)
 
Called when an app event occurs in an ad.

This interface may be implemented by your activity or any other object:

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

public class BannerExample extends Activity implements AppEventListener {
}

and then passed to the PublisherAdView:

adView.setAppEventListener(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:

@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.
    }
  }
}

Manual impression counting

You can manually send impression pings to DFP if you have special conditions for when an impression should be recorded. This can be done by first enabling a PublisherAdRequest for manual impressions prior to loading an ad:

PublisherAdRequest request = new PublisherAdRequest.Builder()
    .setManualImpressionsEnabled(true)
    .build();

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

adView.recordManualImpression();

Note: Impressions are automatically fired when the onAdLoaded() callback is invoked. You should only consider using this feature if you want to record impressions at a different point in time.

com.google.android.gms.ads.AdListener

You may optionally track ad lifecycle events like request failures or "click-through" by passing an object to PublisherAdView.setAdListener that extends com.google.android.gms.ads.AdListener.

public abstract class AdListener {
  public void onAdLoaded();
  public void onAdFailedToLoad(int errorCode);
  public void onAdOpened();
  public void onAdClosed();
  public void onAdLeftApplication();
}

A separate class extending AdListener may be defined, or you may choose to inline an AdListener object:

adView.setAdListener(new AdListener() {
  @Override
  public void onAdOpened() {
    // Save app state before going to the ad overlay.
  }
});

AdListener provides a default empty implementation for all of its ad lifecycle events. You only need to override the ad events you wish to implement.

public void onAdLoaded()
Called when an ad is received.
public void onAdFailedToLoad(int errorCode)
Called when an ad request failed. The error code is usually one of the following:
  1. AdRequest.ERROR_CODE_INTERNAL_ERROR
  2. AdRequest.ERROR_CODE_INVALID_REQUEST
  3. AdRequest.ERROR_CODE_NETWORK_ERROR
  4. AdRequest.ERROR_CODE_NO_FILL
public void onAdOpened()
Called when an ad opens an overlay that covers the screen.
public void onAdClosed()
Called when the user is about to return to the application after clicking on an ad.
public void onAdLeftApplication()
Called when an ad leaves the application (e.g., to go to the browser).
Android (6.4.1 and earlier SDKs)
  1. Adding a DfpAdView
  2. Creating your banner in XML
  3. Custom ad size
  4. Multiple ad sizes
  5. Swipeable banners
  1. Custom targeting
  2. Location targeting
  3. App events
  4. Manual impression counting
  5. com.google.ads.AdListener
  6. Getting support

Adding a DfpAdView

Android apps are composed of View objects, which are Java instances the user sees as text areas, buttons and other controls. DfpAdView is simply another View subclass displaying small HTML5 ads that respond to user touch.

Like any View, a DfpAdView may be created either purely in code or largely in XML.

Here are the five steps to add a banner:

  • Import com.google.ads.* and com.google.ads.doubleclick.*
  • Declare a DfpAdView instance
  • Create it, specifying a DFP ad unit ID
  • Add the view to the UI
  • Load it with an ad

The easiest place to do all this is in your app's Activity.

import com.google.ads.*;
import com.google.ads.doubleclick.*;

public class BannerExample extends Activity {
  private DfpAdView adView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Create the adView
    adView = new DfpAdView(this, AdSize.BANNER, MY_AD_UNIT_ID);

    // Lookup your LinearLayout assuming it’s been given
    // the attribute android:id="@+id/mainLayout"
    LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);

    // Add the adView to it
    layout.addView(adView);

    // Initiate a generic request to load it with an ad
    adView.loadAd(new AdRequest());
  }

  @Override
  public void onDestroy() {
    if (adView != null) {
      adView.destroy();
    }
    super.onDestroy();
  }
}

Tip: The format for the DFP ad unit ID is: /networkCode/adUnitName. You can generate the ad unit ID in DFP. On the Inventory tab, navigate to the ad unit, and click Generate tags. Alternatively, you can find the network code for your account on the Admin tab under Network Settings. Here's an example ad that will always serve:

# Android (320x50)
String MY_AD_UNIT_ID = "/6253334/dfp_example_ad";

The result

When you now run your app you should see a banner on the screen:

Custom ad size

In addition to the standard AdMob ad units, DFP allows you to serve any sized ad unit into an application. Note that the ad size (width, height) defined for an ad request should match the dimensions of the ad view displayed on the application (i.e. DfpAdView).

Example:

// Define custom AdSize of 250x250 for DfpAdView

AdSize customAdSize = new AdSize(250, 250);
adView = new DfpAdView(this, customAdSize, MY_AD_UNIT_ID);

Multiple ad sizes

DFP allows you to specify multiple ad sizes which may be eligible to serve into a DfpAdView. 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, create a DfpAdView using the constructor with multiple ad sizes.

AdSize[] adSizes = { AdSize.BANNER, new AdSize(120, 20), new AdSize(250, 250)};
adView = new DfpAdView(this, adSizes, MY_AD_UNIT_ID);

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

Supported ad sizes

You can use setSupportedAdSizes() if you need to change your supported ad sizes at any point in your application.

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

The AdSizes passed to setSupportedAdSizes() will overwrite the original ad sizes passed into the DfpAdView constructor.

Note: setSupportedAdSizes() cannot be used unless the DfpAdView was created with multiple ad sizes.

Swipeable banners

SwipeableDfpAdView

SwipeableDfpAdView is a subclass of DfpAdView that has the ability to be moved via a swipe event. You can define one the same way you would an AdView, using a pre-defined ad size:

adView = new SwipeableDfpAdView(this, AdSize.IAB_MRECT, MY_AD_UNIT_ID);
or with a custom ad size:
adView = new SwipeableDfpAdView(this, new AdSize(320, 480), MY_AD_UNIT_ID);

Custom targeting

You can pass custom key-value pairs to target DFP campaigns (line items). Out of respect for user privacy, Google asks that you only specify location and demographic data if that information is already used by your app.

Example:

// Example: Pass custom targeting "Age=25", "Color=Blue,Green,Red"

private AdRequest createRequest() {
 AdRequest request = new AdRequest();
 DfpExtras extras = new DfpExtras();
 extras.addExtra("Age", "25");
 extras.addExtra("Color", "Blue,Green,Red");
 request.setNetworkExtras(extras);
 return request;
}

Location targeting

DFP can use precise location to improve geotargeting. The location is set using setLocation() method.

Note: This feature needs to be enabled for each network individually. Publishers should contact their customer representative to have this feature enabled.

Here's an example of how to set location before loading the ad request.

Location location = new Location("");
// New York
location.setLatitude(40.764316);
location.setLongitude(-73.977245);
location.setAccuracy(100);
adRequest.setLocation(location);
adView.loadAd(adRequest);

App events

You may optionally listen for DFP specific app events using AppEventListener. These events may occur at any time during the ad's lifecycle, even before AdListener's onReceiveAd() is called.

public interface AppEventListener {
  void onAppEvent(Ad ad, String name, String info);
}
void onAppEvent(Ad ad, String name, String info)
 
Called when an app event occurs in an ad.

This interface may be implemented by your activity or any other object:

import com.google.ads.doubleclick.*;

public class BannerExample extends Activity implements AppEventListener {
}

and then passed to the DfpAdView:

adView.setAppEventListener(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:

@Override
  public void onAppEvent(Ad ad, 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.
      }
    }
  }

Manual impression counting

You can manually send impression pings to DFP if you have special conditions for when an impression should be recorded. This can be done by first enabling a DfpAdView for manual impressions prior to loading an ad:

adView.enableManualImpressions(true);

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

adView.recordImpression();

Note: Impressions are automatically fired when the onReceiveAd() callback is invoked. You should only consider using this feature if you want to record impressions at a different point in time.

com.google.ads.AdListener

You may optionally track ad lifecycle events like request failures or "click-through" by implementing com.google.ads.AdListener in an object you pass to AdView.setAdListener.

public interface AdListener {
  public void onReceiveAd(Ad ad);
  public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error);
  public void onPresentScreen(Ad ad);
  public void onDismissScreen(Ad ad);
  public void onLeaveApplication(Ad ad);
}

This interface may be implemented by your activity or any other object:

import com.google.ads.*;

public class BannerExample extends Activity implements AdListener {
}

and then passed to the Ad:

adView.setAdListener(this);
public void onReceiveAd(Ad ad)
Sent when DfpAdView.loadAd has succeeded.
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error)
Sent when loadAd has failed, typically because of network failure, an application configuration error, or a lack of ad inventory. You may wish to log these events for debugging:
@Override
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode errorCode) {
  Log.d(MY_LOG_TAG, "failed to receive ad (" + errorCode + ")");
}
public void onPresentScreen(Ad ad)
Called when an Activity is created in front of your app, presenting the user with a full-screen ad UI in response to their touching ad.
public void onDismissScreen(Ad ad)
Called when the full-screen Activity presented with onPresentScreen has been dismissed and control is returning to your app.
public void onLeaveApplication(Ad ad)
Called when an Ad touch will launch a new application.

For a sample application that demonstrates some of the creative types available in DFP Mobile, check out the DFP Showcase.

iOS
  1. Adding a DFPBannerView
  2. Serving AdMob ads through DFP
  3. Custom ad size
  4. Multiple ad sizes
  5. Swipeable banners
  1. Custom targeting
  2. Location targeting
  3. Setting publisher provided identifiers
  4. App events
  5. Manual impression counting
  6. GADBannerViewDelegate
  7. Getting support

Adding a DFPBannerView

iOS apps are composed of DFPBannerView objects, Objective-C instances the user sees as text areas, buttons and other controls. DFPBannerView is simply a UIView subclass displaying small HTML5 ads that respond to user touch.

Note: Users who have already implemented AdMob ads using GADBannerView can easily swap out the AdMob Ad Unit ID for DFP Ad Unit ID to serve DFP ads. However, note that GADBannerView does not include extended capabilities available with DFPBannerView, including the ability to set multiple ad sizes in the ad request or to listen for app events.

Like any UIView, a DFPBannerView is easy to create in code.

The seven lines of code it takes to add a banner:

  • Import DFPBannerView.h
  • Declare a DFPBannerView instance in your app’s UIViewController
  • Create it
  • Set the ad’s DFP ad unit ID
  • Set the "root view controller"
  • Add the view to the UI
  • Load it with an ad

The best place to do all this is in your app's UIViewController.

// BannerExampleViewController.h

// Import DFPBannerView’s definition from the SDK
#import "DFPBannerView.h"

@interface BannerExampleViewController : UIViewController {
  // Declare one as an instance variable
  DFPBannerView *bannerView_;
}

@end

The following performs banner setup in the view controller's viewDidLoad initialization hook.

// BannerExampleViewController.m

#import "BannerExampleViewController.h"

@implementation BannerExampleViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Create a view of the standard size at the top of the screen.
  // Available AdSize constants are explained in GADAdSize.h.
  bannerView_ = [[DFPBannerView alloc] initWithAdSize:kGADAdSizeBanner];

  // Specify the ad's "unit identifier." This is your DFP ad unit ID.
  bannerView_.adUnitID = MY_AD_UNIT_ID;

  // Let the runtime know which UIViewController to restore after taking
  // the user wherever the ad goes and add it to the view hierarchy.
  bannerView_.rootViewController = self;
  [self.view addSubview:bannerView_];

  // Initiate a generic request to load it with an ad.
  [bannerView_ loadRequest:[GADRequest request]];
}

- (void)dealloc {

  // Don't release the bannerView_ if you are using ARC in your project
  [bannerView_ release];
  [super dealloc];
}

@end

Tip: The format for the DFP ad unit ID is: /networkCode/adUnitName. You can generate the ad unit ID in DFP. On the Inventory tab, navigate to the ad unit, and click Generate tags. Alternatively, you can find the network code for your account on the Admin tab under Network Settings. Here's an example ad that will always serve:

// iOS (320x50)
define MY_AD_UNIT_ID = @"/6253334/dfp_example_ad";

The result

The outcome should be a banner at the top of your app:

Serving AdMob ads through DFP

You can send ad impressions from your mobile application to AdMob by creating a DFP line item with an AdMob creative.

Note: AdMob line items don't use dynamic allocation in the same way that AdSense line items do. If the AdMob line item type is trafficked as "Price Priority" with a CPM estimate, it competes on price. If no CPM estimate is entered, it doesn't compete on price.

To traffic AdMob backfill, refer to the article Traffic AdMob backfill for mobile applications.

AdMob ads only: All new iPad and iPhone apps created after October 14, 2011 will require an SDK that was released on or after March 15, 2011. This corresponds to version 4.0.2+ for iOS. If you downloaded the library from our official download site, then you're already set. Otherwise you may have an old version of the SDK that was released prior to March 15, 2011, and your new app will not receive any ad impressions until you update your SDK.

Custom ad size

In addition to the standard AdMob ad units, DFP allows you to serve any sized ad unit into an application. Note that the ad size (width, height) defined for an ad request should match the dimensions of the ad view displayed on the application (i.e. DFPBannerView).

Example:

// Define custom GADAdSize of 250x250 for DFPBannerView

GADAdSize customAdSize = GADAdSizeFromCGSize(CGSizeMake(250, 250));

// Don't use autorelease if you are using ARC in your project
self.adBanner = [[[DFPBannerView alloc] initWithAdSize:customAdSize] autorelease];

Multiple ad sizes

DFP allows you to specify multiple ad sizes which may be eligible to serve into a DFPBannerView. There are three steps needed in order to use this feature:

  1. In the DFP UI, create a line item targeting the same ad unit that is associated with different size creatives.
  2. In your application, set the validAdSizes property on DFPBannerView:
    // Define an optional array of GADAdSize to specify all valid sizes that are appropriate
    // for this slot. Never create your own GADAdSize directly. Use one of the
    // predefined standard ad sizes (such as kGADAdSizeBanner), or create one using
    // the GADAdSizeFromCGSize method.
    //
    // Note: Ensure that the allocated DFPBannerView is defined with an ad size. Also note
    // that all desired sizes should be included in the validAdSizes array.  
    
    GADAdSize size1 = GADAdSizeFromCGSize(CGSizeMake(120, 20));
    GADAdSize size2 = GADAdSizeFromCGSize(CGSizeMake(250, 250));
    GADAdSize size3 = GADAdSizeFromCGSize(CGSizeMake(320, 50));
    NSMutableArray *validSizes = [NSMutableArray array];
    [validSizes addObject:[NSValue valueWithBytes:&size1 objCType:@encode(GADAdSize)]];
    [validSizes addObject:[NSValue valueWithBytes:&size2 objCType:@encode(GADAdSize)]];
    [validSizes addObject:[NSValue valueWithBytes:&size3 objCType:@encode(GADAdSize)]];
    bannerView_.validAdSizes = validSizes;
    
  3. Implement the GADAdSizeDelegate method to detect an ad size change.
    @protocol GADAdSizeDelegate <NSObject>
    - (void)adView:(DFPBannerView *)view willChangeAdSizeTo:(GADAdSize)size;
    @end
    
    Remember to set the delegate using the setAdSizeDelegate: before making the request for an ad.
    [bannerView_ setAdSizeDelegate:self];

Be sure to set the DFPBannerView's adSizeDelegate property to nil before releasing the view:

- (void)dealloc {
 bannerView_.adSizeDelegate = nil;

 // Don't release the bannerView_ if you are using ARC in your project
 [bannerView_ release];
 [super dealloc];
}

Swipeable banners

DFPSwipeableBannerView

DFPSwipeableBannerView is a subclass of DFPBannerView that has the ability to be moved via a swipe event. You can define one the same way you would a DFPBannerView, using a pre-defined ad size:

bannerView_ = [[DFPSwipeableBannerView alloc] initWithAdSize:kGADAdSizeMediumRectangle];
or with a custom ad frame:
bannerView_ = [[DFPSwipeableBannerView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

Custom targeting

You can pass custom key-value pairs to target DFP campaigns (line items). Out of respect for user privacy, Google asks that you only specify location and demographic data if that information is already used by your app.

Example:

// Example: Pass custom targeting "Age=25", "Color=Blue,Green,Red"
#import "DFPExtras.h"

- (GADRequest *)createRequest {
  GADRequest *request = [GADRequest request];

  // Don't use autorelease if you are using ARC in your project
  DFPExtras *extras = [[[DFPExtras alloc] init] autorelease];
  extras.additionalParameters = [NSDictionary dictionaryWithObjectsAndKeys:
      @"25", @"Age",
      @"Blue,Green,Red", @"Color",
      nil];
  [request registerAdNetworkExtras:extras];
  return request;
}

Location targeting

DFP can use precise location to improve geotargeting. The location is set using the method

setLocationWithLatitude:(CGFloat)latitude longitude:(CGFloat)longitude accuracy:(CGFloat)accuracyInMeters

Note: This feature needs to be enabled for each network individually. Publishers should contact their customer representative to have this feature enabled.

Here's an example of how to set location before loading the ad request.

GADRequest *request = [GADRequest request];
[request setLocationWithLatitude:40.764316
                       longitude:-73.977245
                        accuracy:100];
[bannerView_ loadRequest:request];

Setting publisher provided identifiers

You can set a publisher provided identifier (PPID) for use in frequency capping, audience segmentation and targeting, sequential ad rotation, and other audience-based ad delivery controls across devices.

Note: This feature is not available to all publishers. See this article for details.

Setting the PPID is done through DFPExtras:

DFPExtras *extras = [[[DFPExtras alloc] init] autorelease];
extras.publisherProvidedID = "AB123456789";

App events

You may optionally listen for DFP specific app events using GADAppEventDelegate. These events may occur at any time during the ad's lifecycle, even before GADBannerViewDelegate's adViewDidReceiveAd: is called.

@protocol GADAppEventDelegate <NSObject>
 // Implement your app event within these methods. The delegate will be
 // notified when the SDK receives an app event message from the ad.
 @optional
 - (void)adView:(DFPBannerView *)banner
     didReceiveAppEvent:(NSString *)name
               withInfo:(NSString *)info;
 - (void)interstitial:(DFPInterstitial *)interstitial
     didReceiveAppEvent:(NSString *)name
               withInfo:(NSString *)info;
@end

Your app event methods can be implemented in a view controller:

#import "GADAppEventDelegate.h"

@interface NibExampleViewController : UIViewController <GADAppEventDelegate> {
}

@end

Remember to set the delegate using the setAppEventDelegate: before making the request for an ad.

[bannerView_ setAppEventDelegate:self];

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

- (void)adView:(DFPBannerView *)banner
   didReceiveAppEvent:(NSString *)name
             withInfo:(NSString *)info {
  if ([name isEqualToString:@"color"]) {
    if ([info isEqualToString:@"green"]) {
      // Set background color to green.
    } else if ([info isEqualToString:@"blue"]) {
      // Set background color to blue.
    } else {
      // Set background color to black.
    }
  }
}

Be sure to set the DFPBannerView's appEventDelegate property to nil before releasing the view.

- (void)dealloc {
  bannerView_.appEventDelegate = nil;

  // Don't release the bannerView_ if you are using ARC in your project
  [bannerView_ release];
  [super dealloc];
}

Manual impression counting

You can manually send impression pings to DFP if you have special conditions for when an impression should be recorded. This can be done by first enabling a DFPBannerView for manual impressions prior to loading an ad:

bannerView_.enableManualImpressions = YES;

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

[bannerView_ recordImpression];

Note: Impressions are automatically fired when the adViewDidReceiveAd callback is invoked. You should only consider using this feature if you want to record impressions at a different point in time.

GADBannerViewDelegate

You may optionally track ad lifecycle events like request failures or "click-through" by implementing all or part of GADBannerViewDelegate.

@protocol GADBannerViewDelegate <NSObject>
  @optional
  - (void)adViewDidReceiveAd:(DFPBannerView *)bannerView;
  - (void)adView:(DFPBannerView *)bannerView
      didFailToReceiveAdWithError:(GADRequestError *)error;

  - (void)adViewWillPresentScreen:(DFPBannerView *)bannerView;
  - (void)adViewDidDismissScreen:(DFPBannerView *)bannerView;
  - (void)adViewWillDismissScreen:(DFPBannerView *)bannerView;
  - (void)adViewWillLeaveApplication:(DFPBannerView *)bannerView;
@end

These methods may be implemented in either a separate object like a view controller:

#import "GADBannerViewDelegate.h"

@interface NibExampleViewController : UIViewController <GADBannerViewDelegate> {
}

@end

or as part of a DFPBannerView subclass:

#import "DFPBannerView.h"
#import "GADBannerViewDelegate.h"

@interface MyBannerView : DFPBannerView <GADBannerViewDelegate> {
}

@end

Remember to set the delegate using setDelegate: before making the request for an ad:

[bannerView_ setDelegate:self];
- (void)adViewDidReceiveAd:(DFPBannerView *)bannerView
Sent when loadRequest: has succeeded, this is a good opportunity to add the sender to the view hierarchy if it’s been hidden until now. To have a banner slide up on screen once loaded from your view controller, for example:
- (void)adViewDidReceiveAd:(DFPBannerView *)bannerView {
  [UIView beginAnimations:@"BannerSlide" context:nil];
  bannerView.frame = CGRectMake(0.0,
                                self.view.frame.size.height -
                                bannerView.frame.size.height,
                                bannerView.frame.size.width,
                                bannerView.frame.size.height);
  [UIView commitAnimations];
}
- (void)adView:(DFPBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error
Sent when loadRequest: has failed, typically because of network failure, an application configuration error, or a lack of ad inventory. You may wish to log these events for debugging:
- (void)adView:(DFPBannerView *)bannerView
    didFailToReceiveAdWithError:(GADRequestError *)error {
  NSLog(@”adView:didFailToReceiveAdWithError:%@”, [error localizedDescription]);
}
- (void)adViewWillPresentScreen:(DFPBannerView *)bannerView
Sent immediately before the user is presented with a full-screen ad UI in response to their touching the sender. At this point you should pause any animations, timers or other activities that assume user interaction and save app state, much like on UIApplicationDidEnterBackgroundNotification.

Typically the user simply browses the full-screen ad and dismisses it, generating adViewDidDismissScreen: and returning control to your app. If the banner's action was either Click-to-App-Store or Click-to-iTunes or the user presses Home within the ad, however, your app will be backgrounded and potentially terminated.

In these cases under iOS 4.0+ the next method invoked will be your root view controller's applicationWillResignActive: followed by adViewWillLeaveApplication:

- (void)adViewDidDismissScreen:(DFPBannerView *)bannerView
Sent when the user has exited the sender's full-screen UI
- (void)adViewWillDismissScreen:(DFPBannerView *)bannerView
Sent immediately before the sender's full-screen UI is dismissed, restoring your app and the root view controller. At this point you should restart any foreground activities paused as part of adViewWillPresentScreen:.
- (void)adViewWillLeaveApplication:(DFPBannerView *)bannerView
Sent just before the application gets backgrounded or terminated as a result of the user touching a Click-to-App-Store or Click-to-iTunes banner. The normal UIApplicationDelegate notifications like applicationDidEnterBackground: arrive immediately before this.

During these methods you may consult DFPBannerView.hasAutoRefreshed to determine if a refresh triggered the event.

Note that if you implement your delegate as a distinct object rather than a DFPBannerView subclass, you should set DFPBannerView's delegate property to nil before releasing the view.

- (void)dealloc {
  bannerView_.delegate = nil;

  // Don't release the bannerView_ if you are using ARC in your project
  [bannerView_ release];
  [super dealloc];
}

Objective-C delegates are not retained and may be messaged asynchronously before the delegating object is finally deallocated.

For a sample application that demonstrates some of the creative types available in DFP Mobile, check out the DFP Showcase.

Getting support

If you have DFP-specific questions, the best place to start is the DFP Help Center for your product:

Under the Mobile topic in these help centers are Getting Started Guides for mobile ad serving. The DFP Help forum is also a useful resource for discussions, and where you can post your own questions.

If you have any SDK-specific questions, the best place to start is to search for keywords related to your inquiry on the Google Mobile Ads Developers Forum. When submitting a question to the forum, be sure to include "DoubleClick" in the subject line to ensure a speedy response from the DFP support team.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.