Using the Native Ad API in Android

The Native Ad API allows you to build a customized experience for the ads you show in your app. When using the Native Ad API, instead of receiving an ad ready to be displayed, you will receive a group of ad properties such as a title, an image, a call to action, and you will have to use them to construct a custom view where the ad is shown.

Ensure you have completed the Audience Network Getting Started and Android Getting Started guides before you proceed.

In this guide we will implement the following native ad placement. You will create a native ad with the following components:

View #1: Ad Icon

View #2: Ad Title

View #3: Sponsored Label

View #4: AdChoices Icon

View #5: MediaView

View #6: Social Context

View #7: Ad Body

View #8: Call to Action button




Native Ad Steps

Step 1: Requesting a Native Ad

Step 2: Creating your Native Ad Layout

Step 3: Populating your Layout Using the Ad's Metadata

Step 4: Using MediaView

Step 1: Requesting a Native Ad

Add the following code at the top of your Activity to import the Facebook Ads SDK:

import com.facebook.ads.*;

Then, instantiate a NativeAd object, set an AdListener, and call loadAd():

private NativeAd nativeAd;

private void showNativeAd() {
  nativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
  nativeAd.setAdListener(new AdListener() {
      
    @Override
    public void onError(Ad ad, AdError error) {
      // Ad error callback
    }
      
    @Override
    public void onAdLoaded(Ad ad) {
      // Ad loaded callback
    }
      
    @Override
    public void onAdClicked(Ad ad) {
      // Ad clicked callback    
    }

    @Override
    public void onLoggingImpression(Ad ad) {
      // Ad impression logged callback
    }
  });

  // Request an ad
  nativeAd.loadAd();
}

We will be coming back later to add code to the onAdLoaded() method.

Step 2: Creating your Native Ad Layout

The next step is to extract the ad metadata and use its properties to build your customized native UI. You can either create your custom view in a layout .xml, or you can add elements in code.

Please consult our guidelines for native ads when designing native ads in your app.

In your Activity's layout, add a container for your Native Ad.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:paddingTop="50dp">
    ...
    <LinearLayout
        android:id="@+id/native_ad_container"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"/>
    ...
</RelativeLayout>

Create a custom layout for your Native Ad:



Below is an example custom layout for your Native Ad:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/native_ad_unit"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="@android:color/white"
              android:orientation="vertical"
              android:paddingLeft="10dp"
              android:paddingRight="10dp">

    <LinearLayout
        android:id="@+id/ll_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingBottom="10dp"
        android:paddingTop="10dp">

        <ImageView
            android:id="@+id/native_ad_icon"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_gravity="center_vertical"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="5dp">

            <TextView
                android:id="@+id/native_ad_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="2"
                android:textColor="@android:color/black"
                android:textSize="15sp"/>

            <TextView
                android:id="@+id/sponsored_label"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:lines="1"
                android:text="Sponsored"
                android:textColor="@android:color/darker_gray"
                android:textSize="10sp"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ad_choices_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal"/>
    </LinearLayout>

    <com.facebook.ads.MediaView
        android:id="@+id/native_ad_media"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:gravity="center"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:orientation="vertical"
            android:paddingRight="10dp">

            <TextView
                android:id="@+id/native_ad_social_context"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:lines="2"
                android:paddingRight="5dp"
                android:textColor="@android:color/darker_gray"
                android:textSize="10sp"/>

            <TextView
                android:id="@+id/native_ad_body"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:lines="2"
                android:textColor="@android:color/black"
                android:textSize="10sp"/>
        </LinearLayout>

        <Button
            android:id="@+id/native_ad_call_to_action"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:background="#4286F4"
            android:gravity="center"
            android:paddingLeft="3dp"
            android:paddingRight="3dp"
            android:textColor="@android:color/white"
            android:textSize="11sp"/>
    </LinearLayout>
</LinearLayout>

Step 3: Populating your Layout Using the Ad's Metadata

Modify the onAdLoaded() method above to retrieve the Native Ad's properties and display it:

...
private LinearLayout  nativeAdContainer;
private LinearLayout  adView;
...
  private void showNativeAd() {
    ...
    @Override
    public void onAdLoaded(Ad ad) {

      if (nativeAd != null) {
        nativeAd.unregisterView();
      }

      // Add the Ad view into the ad container.
      nativeAdContainer = (LinearLayout) findViewById(R.id.native_ad_container);
      LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
      // Inflate the Ad view.  The layout referenced should be the one you created in the last step.
      adView = (LinearLayout) inflater.inflate(R.layout.native_ad_layout, nativeAdContainer, false);
      nativeAdContainer.addView(adView);

      // Create native UI using the ad metadata.
      ImageView nativeAdIcon = (ImageView) adView.findViewById(R.id.native_ad_icon);
      TextView nativeAdTitle = (TextView) adView.findViewById(R.id.native_ad_title);
      MediaView nativeAdMedia = (MediaView) adView.findViewById(R.id.native_ad_media);
      TextView nativeAdSocialContext = (TextView) adView.findViewById(R.id.native_ad_social_context);
      TextView nativeAdBody = (TextView) adView.findViewById(R.id.native_ad_body);
      Button nativeAdCallToAction = (Button) adView.findViewById(R.id.native_ad_call_to_action);

      // Set the Text.
      nativeAdTitle.setText(nativeAd.getAdTitle());
      nativeAdSocialContext.setText(nativeAd.getAdSocialContext());
      nativeAdBody.setText(nativeAd.getAdBody());
      nativeAdCallToAction.setText(nativeAd.getAdCallToAction());

      // Download and display the ad icon.
      NativeAd.Image adIcon = nativeAd.getAdIcon();
      NativeAd.downloadAndDisplayImage(adIcon, nativeAdIcon);

      // Download and display the cover image.
      nativeAdMedia.setNativeAd(nativeAd);

      // Add the AdChoices icon
      LinearLayout adChoicesContainer = (LinearLayout) findViewById(R.id.ad_choices_container);
      AdChoicesView adChoicesView = new AdChoicesView(MainActivity.this, nativeAd, true);
      adChoicesContainer.addView(adChoicesView);

      // Register the Title and CTA button to listen for clicks.
      List<View> clickableViews = new ArrayList<>();
      clickableViews.add(nativeAdTitle);
      clickableViews.add(nativeAdCallToAction);
      nativeAd.registerViewForInteraction(nativeAdContainer,clickableViews);
    }
    ...
    // Request an ad
    nativeAd.loadAd();
  }

The SDK will log the impression and handle the click automatically. Please note that you must register the ad's view with the NativeAd instance to enable that. To make the whole view clickable register the view using:

registerViewForInteraction(View view)

Controlling Clickable Area

For a better user experience and better results, you should always consider controlling the clickable area of your ad to avoid unintentional clicks.

For finer control of what is clickable, you can use the registerViewForInteraction(View view, List<View> clickableViews) to register a list of views that can be clicked. For example if we only want to make the ad image and the call to action button clickable in the previous example, we can write like this:

@Override
public void onAdLoaded(Ad ad) {
  ...
  List<View> clickableViews = new ArrayList<>();
  clickableViews.add(nativeAdMedia);
  clickableViews.add(nativeAdCallToAction);
  nativeAd.registerViewForInteraction(nativeAdContainer, clickableViews);
  ...
}

In cases where you reuse the view to show different ads over time, make sure to call unregisterView() before registering the same view with a different instance of NativeAd.

Run the code and you should see a Native Ad:

Step 4: Using MediaView

For displaying the native ad cover image, it is recommended to use the Facebook Audience Network MediaView which can display both image and video assets. You can review our design guidelines for native video ad units here.

By default, image and video assets are not pre-cached when loading native ads.

private void showNativeAd() {
  ...
  nativeAd.loadAd();
}

Audience Network supports pre-caching video or image assets which enables the MediaView to play videos immediately after nativeAd finishes loading.

private void showNativeAd() {
  ...
  nativeAd.loadAd(NativeAd.MediaCacheFlag.ALL);
}

Audience Network supports five cache options in native ads as defined in the NativeAd.MediaCacheFlag enum:

Cache Constants Description

NONE

No pre-caching, default

ICON

Pre-cache ad icon

IMAGE

Pre-cache ad images

VIDEO

Pre-cache ad video

ALL

Pre-cache all (icon, images, and video)

When an ad is loaded, the following properties will include some value: title, icon, coverImage and callToAction. Other properties might be null or empty. Make sure your code is robust enough to handle these cases.


When there is no ad to show, onError will be called with an error.code. If you use your own custom reporting or mediation layer you might want to check the code value and detect this case. You can fallback to another ad network in this case, but do not re-request an ad immediately after.


Ad metadata that you receive can be cached and re-used for up to 3 hours. If you plan to use the metadata after this time period, make a call to load a new ad.

Hardware Acceleration for Video Ads

Videos ads in Audience Network requires the hardware accelerated rendering to be enabled, otherwise you might experience a black screen in the video views. This applies to

  • Videos creatives in Native Ads
  • Videos creatives in Interstitials
  • In-stream Video ads
  • Rewarded Videos

Hardware acceleration is enabled by default if your Target API level is >=14 (Ice Cream Sandwich, Android 4.0.1), but you can also explicitly enable this feature at the application level or activity level.

Application Level

In your Android manifest file, add the following attribute to the <application> tag to enable hardware acceleration for your entire application:

<application android:hardwareAccelerated="true" ...>

Activity Level

If you only want to enable the feature for specific activities in your application, in your Android manifest file, you can add the following feature to the <activity> tag. The following example will enable the hardware acceleration for the AudienceNetworkActivity which is used for rendering interstitial ads and rewarded videos:

<activity android:name="com.facebook.ads.AudienceNetworkActivity" android:hardwareAccelerated="true" .../>

Next Steps

  • See the Native Ad Template guide to add native ads in your app.

  • Explore our code samples which demonstrate how to use native ads. The NativeAdSample is available as part of the SDK and can be found under the AudienceNetwork/samples folder. Import the project to your IDE and run it either on a device or the emulator.

More Resources

Getting Started Guide

Technical guide to get started with Audience Network

Native Ads Manager

Deliver the most relevant ads at the right time

API Reference

Facebook SDK for Android Reference

Horizontal Scroll

Implement a horizontal scroll unit to maximize ad space