Native Ads Integration

Idil Canal edited this page Dec 19, 2016 · 21 revisions

Native ads let you easily monetize your app in a way that’s consistent with its existing design. The MoPub SDK gives you access to an ad’s individual assets so you can lay them out the way you want to; that way, the ad looks and feels like the rest of your app. The SDK automatically handles image caching and metrics tracking so you can focus on how, when, and where to display ads.

The MoPub SDK provides a class, MoPubAdAdapter, that wraps your existing Adapter subclass to insert ads into a ListView, GridView, or other view that uses an implementation of Adapter (including CursorAdapter).

Adding native ads to your Android app takes three easy steps:

  1. Create an XML layout for your native ads
  2. Define where ads should be placed within your feed
  3. Create a MoPubAdAdapter to wrap your existing Adapter subclass and begin loading ads

Prerequisites

Before integrating native ads in your app, you’ll need to go through the steps in our Getting Started Guide to create an account on MoPub and integrate the SDK into your project.

Read the best practices article for guidelines on how native ads can be displayed in your app.

Privacy Information Icon

Your native ad must display the privacy information icon. Instructions for adding a privacy information icon into your ad are outlined below. The MoPub SDK automatically handles tap events on the privacy information icon.

Set up your Native Ad Layout

  1. Start by defining an XML layout for how an ad should look inside your app’s feed. This example layout contains two TextViews for a title and additional text, plus three ImageViews for an icon image, a main image, and a Privacy Information icon image. Choose the assets from the ad that will make it fit in most seamlessly in your app’s feed.

However, your ad must contain the Privacy Information icon. The recommended size for this is 40 dp with a 10dp padding on all sides (so the icon display area is only 20dp by 20dp, but the click area is a bit larger). This icon links to an important privacy notice, and is required for you to use MoPub's native ads.

For example: res/layout/native_ad_layout.xml

<RelativeLayout ...>
  <ImageView android:id="@+id/native_ad_main_image"
    ... />
  <ImageView android:id="@+id/native_ad_icon_image"
    ... />
  <TextView android:id="@+id/native_ad_title"
    ... />
  <TextView android:id="@+id/native_ad_text"
    ... />
  <ImageView android:id="@+id/native_ad_privacy_information_icon_image"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:padding="10dp"
    ... />
</RelativeLayout>

IMPORTANT You should set the background property on your ImageViews to null in order to handle PNG transparency gracefully:

<ImageView
 android:background="@null"
 ... />
  1. Next, create a ViewBinder object specifying the binding between your layout XML and the ad’s content.
ViewBinder viewBinder = new ViewBinder.Builder(R.layout.native_ad_layout)
    .mainImageId(R.id.native_ad_main_image)
    .iconImageId(R.id.native_ad_icon_image)
    .titleId(R.id.native_ad_title)
    .textId(R.id.native_ad_text)
    .privacyInformationIconImageId(R.id.native_ad_privacy_information_icon_image)
    .build();

Note: If you’re displaying direct-sold native ads, you may have additional subviews for text or images available. Extra fields may be added using:

new ViewBinder.Builder().addExtras(Map<String, Integer> resIds)

or

new ViewBinder.Builder().addExtra(String key, int resId)

Example: Let's say that in the MoPub Web UI you've added the custom fields "sponsoredtext" and "sponsoredimage":

  "sponsoredtext" : "Sponsored",
  "sponsoredimage" : "http://www.mopub.com/sponsored.jpg"

You would add these sponsored fields to your XML layout, then bind them to the view like this:

ViewBinder viewBinder = new ViewBinder.Builder(R.layout.native_ad_layout)
  .mainImageId(R.id.native_ad_main_image)
  .iconImageId(R.id.native_ad_icon_image)
  .titleId(R.id.native_ad_title)
  .textId(R.id.native_ad_text)
  .privacyInformationIconImageId(R.id.native_ad_privacy_information_icon_image)
  // Your custom fields are bound with the addExtra() call.
  .addExtra("sponsoredtext", R.id.sponsored_text)
  .addExtra("sponsoredimage", R.id.sponsored_image)
  .build();

Note: If you are adding an image to extras, the key must end with "image"

  1. The MoPubAdAdapter uses a class called MoPubStaticNativeAdRenderer to load ads within your feed. Create an instance with the ViewBinder:
MoPubStaticNativeAdRenderer adRenderer = new MoPubStaticNativeAdRenderer(viewBinder);

Place Ads in your Feed

Next, you’ll need to define where in your feed you’d like ads to appear using the MoPubNativeAdPositioning.MoPubServerPositioning object. You can specify positions in the feed where you always want to display ads and set the interval at which ads should appear in the MoPub native ad unit settings page.

Once you've updated your settings in the UI, set up the MoPubNativeAdPositioning.MoPubServerPositioning object:

MoPubNativeAdPositioning.MoPubServerPositioning adPositioning =
      MoPubNativeAdPositioning.serverPositioning();

Create a MoPubAdAdapter

The MoPubAdAdapter class places the ads according to the rules set in the MoPub UI and also handles ad caching.

Create an instance of MoPubAdAdapter using the current Context, your existing Adapter subclass, and the MoPubNativeAdPositioning object you created in the previous step. mAdAdapter = new MoPubAdAdapter(this, adapter, adPositioning);

Next, register the ad renderer (created from your ViewBinder in step 1) so that the adapter renders your ads according to the layout you created:

    mAdAdapter.registerAdRenderer(adRenderer);

Finally, set your old view’s adapter to be the new MoPubAdAdapter instance:

    myListView.setAdapter(mAdAdapter);

Begin Loading Ads

The MoPubAdAdapter is now ready to begin loading ads according to your specifications. To improve the relevance of the ads that get shown in your app, you can choose to pass up location or additional keyword data (see the data passing guide). You can also specify exactly which assets you want, to help conserve bandwidth.

 final EnumSet<NativeAdAsset> desiredAssets = EnumSet.of(
                      NativeAdAsset.TITLE,
                      NativeAdAsset.TEXT,
                      // Don't pull the ICON_IMAGE
                      // NativeAdAsset.ICON_IMAGE,
                      NativeAdAsset.MAIN_IMAGE,
                      NativeAdAsset.CALL_TO_ACTION_TEXT);

Then, create a new RequestParameters object using the Builder:

  mRequestParameters = new RequestParameters.Builder()
                      .location(location)
                      .keywords(keywords)
                      .desiredAssets(desiredAssets)
                      .build();

You're now ready to load ads, using the request parameters and the ad unit ID you created on the MoPub dashboard: mAdAdapter.loadAds(AD_UNIT_ID, mRequestParameters);

To load all-new ads into the stream you can call MoPubAdAdapter#refreshAds.

Sample code:

private ListView mListView;
private MoPubAdAdapter mAdAdapter;
private static final String MY_AD_UNIT_ID = "myAdUnitId";

@Override
public void onCreate(Bundle savedInstanceState) {
    // Set up your adapter as usual.
    Adapter myAdapter;

    // Set up a ViewBinder and MoPubStaticNativeAdRenderer as above.
    ViewBinder viewBinder = new ViewBinder.Builder(R.layout.native_ad_layout)
            .mainImageId(R.id.native_ad_main_image)
            .iconImageId(R.id.native_ad_icon_image)
            .titleId(R.id.native_ad_title)
            .textId(R.id.native_ad_text)
            .privacyInformationIconImageId(R.id.native_ad_privacy_information_icon_image)
            .addExtra("sponsoredText", R.id.sponsored_text)
            .addExtra("sponsoredImage", R.id.sponsored_image)
            .build();

    // Set up the positioning behavior your ads should have.
    MoPubNativeAdPositioning.MoPubServerPositioning adPositioning =
          MoPubNativeAdPositioning.serverPositioning();
    MoPubStaticNativeAdRenderer adRenderer = new MoPubStaticNativeAdRenderer(viewBinder);

    // Set up the MoPubAdAdapter
    mAdAdapter = new MoPubAdAdapter(this, myAdapter, myAdPositioning);
    mAdAdapter.registerAdRenderer(adRenderer);

    myListView.setAdapter(mAdAdapter);
}

@Override
public void onResume() {
    // Set up your request parameters
    myRequestParameters = RequestParameters.Builder()
            .keyWords("my targeting keywords")
            .build();

    // Request ads when the user returns to this activity.
    mAdAdapter.loadAds(MY_AD_UNIT_ID, myRequestParameters);
    super.onResume();
}

Destroy the MoPubAdAdapter

The MoPubAdAdapter must be destroyed when its hosting Activity is destroyed. You should destroy the adapter in the life-cycle method that is the opposite of the method used to create the adapter. If you created the adapter in Activity#onCreate, you should destroy it in Activity#onDestroy. If you created the adapter in Activity#onResume, you should destroy it in Activity#onPause.

Sample code:

@Override
protected void onDestroy() {
    mAdAdapter.destroy();
    super.onDestroy();
}

Important Note:

For information on using Native Ads outside of an Adapter or without using the StreamAdPlacer, see Manual Integration of Native Ads.