Imagine you’ve just finished creating a line item targeting mobile devices in DFP, and your manager comes to you and says, “Bad news! Our Android developer was just eaten by a bear, so now it’s your job to get that line item into our new app.” Don’t worry! Displaying DFP ads in Android applications is surprisingly easy.
First, check your configuration
Retrieve your ad unit ID and size
To display your new line item, you’ll need to retrieve its ad unit ID from DFP. Log into your account, locate the ad unit that targets the new line item, and look for a “Generate tags” button to the right of its name. Clicking that button will display a dialog with some options for the type of tag to generate:
Select “Mobile applications” in the Tag Type dropdown, and you’ll see the correct ad unit ID and ad unit size for your line item. Armed with those two pieces of info, you’re ready to start coding.
Place a PublisherAdView
DFP banner ads are displayed with the PublisherAdView class. It’s possible to create instances on the fly and add them to a layout programmatically, but the better practice is to define them in your XML layout files. Here’s an example element:
<com.google.android.gms.ads.doubleclick.PublisherAdView android:id="@+id/banner_ad" android:layout_width="wrap_content" android:layout_height="wrap_content" ads:adSize="320x50" ads:adUnitId="/1234567890/DemoAccount/BearRepellent"/>
Note the adSize and adUnitId attributes. These should be set to match the ad unit ID and size shown in the Generate Tags dialog. See our banner guide for more information about setting custom or multiple sizes.
Request an ad
With the PublisherAdView defined in your layout file, you just need to add a few lines of code to its corresponding Java class:
PublisherAdView adView = (PublisherAdView)findViewById(R.id.banner_ad); PublisherAdRequest request = new PublisherAdRequest.Builder().build(); adView.loadAd(request);
PublisherAdRequest.Builder is a factory class that builds PublisherAdRequest objects. This example uses a simple, unmodified request, but there are a number of ways to add custom targeting, network extras, and test device information when building your own. See the targeting section of our banner guide for details.
Enjoy your line item
With the layout updated and request code in place, your app is ready to show an ad!
Feel free to use the code from this example in your own applications, and if you have any questions, come and see us on our forum.