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 final String TAG = NativeAdActivity.class.getSimpleName();
private NativeAd nativeAd;

private void loadNativeAd() {
  // Instantiate a NativeAd object. 
  // NOTE: the placement ID will eventually identify this as your App, you can ignore it for
  // now, while you are testing and replace it later when you have signed up.
  // While you are using this temporary code you will only get test ads and if you release
  // your code like this to the Google Play your users will not receive ads (you will get a no fill error).
  nativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
  nativeAd.setAdListener(new NativeAdListener() {
      @Override
      public void onMediaDownloaded(Ad ad) {
          // Native ad finished downloading all assets
          Log.e(TAG, "Native ad finished downloading all assets.");
      }

      @Override
      public void onError(Ad ad, AdError adError) {
          // Native ad failed to load
          Log.e(TAG, "Native ad failed to load: " + adError.getErrorMessage());
      }

      @Override
      public void onAdLoaded(Ad ad) {
          // Native ad is loaded and ready to be displayed
          Log.d(TAG, "Native ad is loaded and ready to be displayed!");
      }

      @Override
      public void onAdClicked(Ad ad) {
          // Native ad clicked
          Log.d(TAG, "Native ad clicked!");
      }

      @Override
      public void onLoggingImpression(Ad ad) {
          // Native ad impression
          Log.d(TAG, "Native ad impression logged!");
      }
  });

  // 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 activity_main.xml, 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">
    ...
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="50dp">

        <LinearLayout
            android:id="@+id/native_ad_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>
    ...
</RelativeLayout>

Create a custom layout native_ad_layout.xml 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/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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingBottom="10dp"
        android:paddingTop="10dp">

        <com.facebook.ads.AdIconView
            android:id="@+id/native_ad_icon"
            android:layout_width="35dp"
            android:layout_height="35dp" />

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

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

            <TextView
                android:id="@+id/native_ad_sponsored_label"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:lines="1"
                android:textColor="@android:color/darker_gray"
                android:textSize="12sp" />

        </LinearLayout>

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

    </LinearLayout>

    <com.facebook.ads.MediaView
        android:id="@+id/native_ad_media"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        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">

            <TextView
                android:id="@+id/native_ad_social_context"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:lines="1"
                android:textColor="@android:color/darker_gray"
                android:textSize="12sp" />

            <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="12sp" />

        </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:paddingLeft="3dp"
            android:paddingRight="3dp"
            android:textColor="@android:color/white"
            android:textSize="12sp"
            android:visibility="gone" />

    </LinearLayout>

</LinearLayout>

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

Scenario 1: Immediately display the ad once it is loaded successfully. Modify the onAdLoaded() method above to retrieve the Native Ad's properties and display it as follows:

private LinearLayout nativeAdContainer;
private LinearLayout adView;
private NativeAd nativeAd;

private void loadNativeAd() {
    // Instantiate a NativeAd object. 
    // NOTE: the placement ID will eventually identify this as your App, you can ignore it for
    // now, while you are testing and replace it later when you have signed up.
    // While you are using this temporary code you will only get test ads and if you release
    // your code like this to the Google Play your users will not receive ads (you will get a no fill error).
    nativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
    nativeAd.setAdListener(new NativeAdListener() {
        ...
        @Override
        public void onAdLoaded(Ad ad) {
            // Race condition, load() called again before last ad was displayed
            if (nativeAd == null || nativeAd != ad) {
                return;
            }
            // Inflate Native Ad into Container
            inflateAd(nativeAd);
        }
        ...
    });
    // Request an ad
    nativeAd.loadAd();
}

private void inflateAd(NativeAd nativeAd) {

    nativeAd.unregisterView();

    // Add the Ad view into the ad container.
    nativeAdContainer = findViewById(R.id.native_ad_container);
    LayoutInflater inflater = LayoutInflater.from(NativeAdActivity.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_1, nativeAdContainer, false);
    nativeAdContainer.addView(adView);

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

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

    // Set the Text.
    nativeAdTitle.setText(nativeAd.getAdvertiserName());
    nativeAdBody.setText(nativeAd.getAdBodyText());
    nativeAdSocialContext.setText(nativeAd.getAdSocialContext());
    nativeAdCallToAction.setVisibility(nativeAd.hasCallToAction() ? View.VISIBLE : View.INVISIBLE);
    nativeAdCallToAction.setText(nativeAd.getAdCallToAction());
    sponsoredLabel.setText(nativeAd.getSponsoredTranslation());

    // Create a list of clickable views
    List<View> clickableViews = new ArrayList<>();
    clickableViews.add(nativeAdTitle);
    clickableViews.add(nativeAdCallToAction);

    // Register the Title and CTA button to listen for clicks.
    nativeAd.registerViewForInteraction(
            adView,
            nativeAdMedia,
            nativeAdIcon,
            clickableViews);
}

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 all ad elements of the view clickable register it using:

registerViewForInteraction(View view, MediaView adMediaView, AdIconView adIconView)

Scenario 2: Display the ad in a few seconds or minutes after it is successfully loaded. You should check whether the ad has been invalidated before displaying it.

In case of not showing the ad immediately after the ad has been loaded, the developer is responsible for checking whether or not the ad has been invalidated. Once the ad is successfully loaded, the ad will be valid for 60 mins. You will not get paid if you are showing an invalidated ad.

You should follow the idea below, but please do not copy the code into your project since it is just an example:

private NativeAd nativeAd;

private void loadNativeAd() {
    // Instantiate a NativeAd object. 
    // NOTE: the placement ID will eventually identify this as your App, you can ignore it for
    // now, while you are testing and replace it later when you have signed up.
    // While you are using this temporary code you will only get test ads and if you release
    // your code like this to the Google Play your users will not receive ads (you will get a no fill error).
    nativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
    nativeAd.setAdListener(new NativeAdListener() {
        ...
    });
    // Request an ad
    nativeAd.loadAd();
    // Here is just an example for displaying the ad with delay
    // Please call this method at appropriate timing in your project
    showNativeAdWithDelay();
}

private void showNativeAdWithDelay() {
    /**
     * Here is an example for displaying the ad with delay;
     * Please do not copy the Handler into your project
     */
    // Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            // Check if nativeAd has been loaded successfully
            if(nativeAd == null || !nativeAd.isAdLoaded()) {
                return;
            }
            // Check if ad is already expired or invalidated, and do not show ad if that is the case. You will not get paid to show an invalidated ad.
            if(nativeAd.isAdInvalidated()) {
                return;
            }
            inflateAd(nativeAd); // Inflate Native Ad into Container same as previous code example
        }
    }, 1000 * 60 * 15); // Show the ad after 15 minutes
}

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. Please refer to Audience Network SDK Policy page for more details about white space unclickable enforcement.

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

@Override
public void onAdLoaded(Ad ad) {
  ...
  // Create a list of clickable views
    List<View> clickableViews = new ArrayList<>();
    clickableViews.add(nativeAdTitle);
    clickableViews.add(nativeAdCallToAction);

    // Register the Title and CTA button to listen for clicks.
    nativeAd.registerViewForInteraction(
            adView,
            nativeAdMedia,
            nativeAdIcon,
            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 all pre-cached when loading native ads, which enables the MediaView to play videos immediately after nativeAd finishes loading.

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

Also, you can explicitly specify NativeAd.MediaCacheFlag.ALL when loading native ads.

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

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

Cache Constants Description

ALL

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

NONE

No pre-caching

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 1 hour. 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