In this codelab, you'll learn how to create beautiful native ads for your Android app with Doubleclick for Publishers and the Google Mobile Ads SDK.

What you'll learn

What you'll need

What's your level of experience with DFP?

I have never used DFP before I have access to a DFP SB account I have access to a DFP Premium account

How would rate your experience with building Android apps?

Novice Intermediate Proficient

What you'll need

Create a DFP Small Business account

To create a DFP Small Business network, you need a Google Adsense account. If you don't already have one, you can sign up for one here:

Sign up for Google AdSense

If you already have a Google Adsense account, signing up for DFP Small Business is a piece of cake.

  1. In a Chrome browser, login to your Google Adsense Account and navigate to http://www.google.cn/dfp/. Follow the prompts to verify your Google Account.
  2. Select your display language.
  3. Select your country or region, time zone, and default currency.
  4. Confirm your local settings and accept the terms. Local settings are permanent once you've accepted the terms. Make sure you enter the right country or region, time zone, and currency.
  5. Choose whether you'd like to receive periodic alerts and notifications from DFP Small Business. You can change this setting later.

That's it! Now let's start creating your first native ad.

Overview

Custom (user-defined) native ad formats allow you to define your own variables for native ads that will be direct sold.

A native ad format is a set of variables and styles that comprises a native ad:

Create your template

To create your first template, you need to go to the Delivery tab, and then in the left column select Creatives -> Native Styles. Then, click the New native style button:

Since you are creating a new format from scratch, in the following pop-up window, select Create new format:

In the next screen, we'll call this template Native Codelab and we'll add the following variables:

There's no need to add a click-through URL, it's in the template by default. Once we save it, the native format should look like this:

Take note of the ID highlighted above (the ID of your newly created template might differ from this), you'll need it later in Step 9.

There's no more work to be done in the template for now, so proceed to the next section.

Imagine printing a hard copy of your home page and cutting out all of the ads. Each empty space is an opportunity to advertise. DFP defines each space, or similar spaces appearing throughout your website, as an ad unit.

In this section, you will create an ad unit called codelab. This ad unit represents the physical space in the screen that will show your native ads, so you can target campaigns to it.

Create your ad unit

To create your ad unit, navigate to the Inventory tab. In the Ad Units section, click the New ad unit button.

Then, fill in the required fields for the ad unit as follows:

Click Save. Everything else can be left with its default value:

And that's it! Your ad unit is ready. From now on, no more work is needed in the Inventory section, unless new ad units need to be created.

Once you've set up your inventory (as described in the previous section), you can start selling it by creating an order. In DFP, an order is an agreement between you and an advertiser that includes an invoice number (optional), start and end dates, and contact information.

Each order includes one or more line items. A line item specifies the advertiser's commitment to purchase a specific number of impressions (cost per thousand impressions, or CPM), clicks (cost per click, or CPC), or time (cost per day, or CPD) on certain dates at a certain price. Each line item also includes where an advertiser's ads will appear and, optionally, which times of the week and to whom.

In turn, each line item contains one or more creatives, which contain the actual ad content that is delivered to your users. DFP can serve a wide variety of creative types, including rich media, video, and mobile creatives.

Create your Order and Line Item

To create your first order, go to the Delivery tab and click the New order button:

In the Order section, fill in the order details. For this example, use "Custom Rendering Codelab" as the order name, and "Google" as the advertiser. If the advertiser doesn't exist, create it by clicking "Add a new company" in the Advertiser dropdown as shown below:

Next, we'll create a Line Item for the order.

In the Delivery settings, select a Sponsorship type of Line Item. This will ensure that our ad is served every time it is requested, which is ideal for testing.

Lastly, tell DFP to only serve this ad when a request is being made to the codelab ad unit by selecting the ad unit in the targeting section. Leave everything else with their default values for now:

Finally, click the "Save and... Upload creatives" button. Now you're ready to upload the test creative to DFP in the following section. You're almost there!

Here is where you will upload the creative asset that will be served by this campaign. DFP can deliver more than one creative. The first step is to locate our Native Codelab template, and click Continue:

Finally, define and upload the assets to be served by our native ad.

Click Save.

Almost there! The last step is to approve the order:

If your Line Item is in status Ready then congratulations! Your first DFP campaign is ready to serve.

The next step is to integrate the Google Mobile Ads SDK into a brand new app and use it to display our previously defined Custom Native Template ad.

Prerequisites

In order to complete the Get Started guide, you need to have Android Studio installed on your development machine. If you don't already have it installed, see the Android Studio site for instructions on how to download everything you need to get up and running.

Create a new project

In this step, you will create a brand new project in Android Studio to use for our example. If you don't already have Studio running, go ahead and open it now.

Start the new project wizard

If you see the above welcome screen, select New Project. Otherwise, select File > New Project from the menu. This brings up the new project wizard:

Name your project

Enter "CustomRenderingCodelab" as the app name, and whatever company domain you use for your apps. Android Studio automatically determines a good project location, but feel free to change it if you like.

Set the required SDK version

On the next screen, select Phone and Tablet for the form factor and a minimum platform SDK version of 9. That's the minimum version supported by the Google Mobile Ads SDK.

Add your main activity

We're keeping it simple for this example, so on this screen select Empty Activity.

Name your activity

On this screen you have the option of choosing names for the app's activity and its related resources. Use the default names for this example, and click the Finish button.

Compile your new project

After clicking Finish, you have a working project with a single activity. Try compiling and running it (select Run 'app' from the Run menu). You should see a "Hello world!" message on an otherwise empty gray screen. Don't worry, you'll add some more content in the next steps.

Configure Gradle

To use the Mobile Ads SDK in your project, you first need to reference it as a dependency in your app's build.gradle file. Open CustomRenderingCodelab/app/build.gradle and look for the dependencies section near the bottom.

build.gradle (excerpt)

...
dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:22.2.0'
        compile 'com.google.android.gms:play-services-ads:8.4.0'
    }
...

Add a line to it like the last one above. This instructs gradle to include code from the play-services-ads artifact, which is found in the Google Repository.

You may see a warning message across the top of the Android Studio window indicating that gradle needs to perform a sync. If that's the case, click Sync Now to do so. Gradle will refresh your project's libraries to include the dependency you just added.

If this is your first time using the Google Repository, you may also see a message asking you to install it. If this happens, just agree to the install and Android Studio will take care of the download for you.

Once your build.gradle file is modified and everything has synced, try rebuilding your project (Run 'app' in the Run menu) to make sure it compiles correctly. You won't see any changes, but including Google Play services is the first step toward getting ads into your app.

Configure your Ad Unit ID and Custom Template ID

An Ad Unit ID is a unique identifier given to the places in your app where ads are displayed. For example, if you have an app with two activities with banner ads, each activity will need an ad unit and unique ID.

In order for your new app to display an ad, it needs to include an Ad Unit ID. Open your app's string resource file, which is found at CustomRenderingCodelab/app/src/main/res/values/strings.xml.

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">CustomRenderingCodelab</string>
    <string name="native_ad_unit_id">/{YOUR_NETWORK_CODE}/codelab</string>
    <string name="native_template_id">{YOUR_TEMPLATE_ID}</string>
</resources>

The codelab ad unit name is the one we previously created in this codelab.

You need to modify your main activity's layout to include and define your native ad. Open CustomRenderingCodelab/app/src/main/res/layout/activity_main.xml in the editor, and specify where we'll include our native ad layout (we'll use this RelativeLayout to inflate the ad inside it).

activity_main.xml

...
   <RelativeLayout
   android:id="@+id/adView"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_centerVertical="true"></RelativeLayout>
...

Your native ad layout can be defined in the file above, but it's good practice to keep it separate. Thus, you''ll create CustomRenderingCodelab/app/src/main/res/layout/custom_template_ad.xml and define the layout there. This is where you'll define the look and feel of the ad, including size, font, colors, etc.

custom_template_ad.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/native_ad"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:padding="10dp"
   android:background="#dfdfdf"
   android:layout_centerVertical="true"
   android:layout_centerHorizontal="true">

   <ImageView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:clickable="true"
       android:minWidth="200dp"
       android:minHeight="200dp"
       android:background="#ffffff"
       android:id="@+id/mainImage"
       android:layout_gravity="left|top"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true" />

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textAppearance="?android:attr/textAppearanceLarge"
       android:layout_marginTop="5dp"
       android:text="Headline"
       android:id="@+id/headline"
       android:layout_gravity="left|center_vertical"
       android:layout_below="@+id/mainImage"
       android:layout_alignLeft="@+id/mainImage"
       android:layout_alignStart="@+id/mainImage" />

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textAppearance="?android:attr/textAppearanceMedium"
       android:text="Caption"
       android:id="@+id/caption"
       android:layout_gravity="left|bottom"
       android:layout_below="@+id/headline"
       android:layout_alignLeft="@+id/headline"
       android:layout_alignStart="@+id/headline" />

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:padding="5dp"
       android:textAppearance="?android:attr/textAppearanceSmall"
       android:text="Sponsored"
       android:id="@+id/textView"
       android:textColor="#000000"
       android:layout_alignTop="@+id/mainImage"
       android:layout_alignRight="@+id/mainImage"
       android:layout_alignEnd="@+id/mainImage" />

</RelativeLayout>

The final step: loading your ad. First, you need to create the adLoader object, for example in the onCreate() method inside the MainActivity:

MainActivity.java

...
AdLoader adLoader = new AdLoader.Builder(getApplicationContext(),
       getString(R.string.native_ad_unit_id))
       .forCustomTemplateAd(getString(R.string.native_template_id),
               new NativeCustomTemplateAd.OnCustomTemplateAdLoadedListener() {
                   @Override
                   public void onCustomTemplateAdLoaded(NativeCustomTemplateAd ad) {
                       // Display ad and record impression
                       ViewGroup adView = (ViewGroup) findViewById(R.id.adView);
                       displayCustomTemplateAd(adView, ad);
                   }
               },
               null)
       .build();

adLoader.loadAd(new PublisherAdRequest.Builder().build());

...

The example below will inflate the ad layout, and fill it with the ad response assets.

private void displayCustomTemplateAd (ViewGroup parent, NativeCustomTemplateAd ad) {
   // Inflate a layout and add it to the parent ViewGroup.
   LayoutInflater inflater = (LayoutInflater) parent.getContext()
           .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View adView = inflater.inflate(R.layout.custom_template_ad, parent);

   // Show the custom template
   TextView headline = (TextView) findViewById(R.id.headline);
   TextView caption = (TextView) findViewById(R.id.caption);
   ImageView mainImage = (ImageView) findViewById(R.id.mainImage);
   headline.setText(ad.getText("Headline"));
   caption.setText(ad.getText("Caption"));
   mainImage.setImageDrawable(ad.getImage("MainImage").getDrawable());

   // Record an impression
   ad.recordImpression();

   // Handle clicks on image
   mainImage.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          ad.performClick("MainImage");
      }
   });

}

And that's it! Your first native ad is ready:

Now it's time for you to start creating your own custom ads!

Did you have issues with the codelab? Don't worry, you can always download and try the sample app by yourself.

Clone the GitHub repository from the command line:

$ git clone https://github.com/googlecodelabs/drx-custom-rendering-android.git

Or download a zip file:

Download Zip

Once the code is downloaded, the following instructions describe how to open the completed sample app:

  1. Open Android Studio
  2. Open the CustomRenderingCodelab directory from the sample code folder (Select the Open an existing Android Studio project option on the welcome screen, or File > Open).
  3. Plug in your Android device (or use an emulator) and click the Run button. You should see the home screen of the sample app appear after a few seconds.

Want to learn more about DFP? The Publisher University and DFP Help Center are great resources.