Manual Integration of Native Ads - MoPub-Solutions-Eng/mopub.wiki.android.native.betasite GitHub Wiki

This document describes how to manually incorporate native advertisements into your applications. The approach outlined here is suitable for where the native ad placement is in a single view, or when other specific requirements cannot be fulfilled by using the AdPlacer integration. With this integration, publishers have to manually request and receive ads, handle caching, and handle cases where there is no fill. For more details on other supported integration methods, please check out the Native Ad Integration Types Overview.

Prerequisite

Before integrating native ads, follow the steps in our Android Getting Started Guide to create a MoPub account & integrate the MoPub SDK into your project. Additionally, check the Best Practices for guidelines on how native ads should be displayed in your app.

Requesting Native Ads

  1. The first step to request a native ad is to create a MoPubNative instance, which will be used to register ad listeners, and ad renderers, and to make ad requests. To instantiate your MoPubNative instance, specify a Context object, an ad unit ID of type String, and a MoPubNativeNetworkListener object that will be used to listen to ad load successes/failures.
moPubNativeNetworkListener = new MoPubNative.MoPubNativeNetworkListener() {
...
}

moPubNative = new MoPubNative(this, "11a17b188668469fb0412708c3d16813 ", moPubNativeNetworkListener);

To test your implementation, use the following test ad unit ID: 11a17b188668469fb0412708c3d16813
It will always return a static MoPub native creative.


  1. Create an XML layout, specifying how ad assets should be organized. As an example, this layout contains a standard hierarchy of our ad assets It will be used when we create our ViewBinder in the next step.


  1. Create a ViewBinder object to bind our layout XML and the ad's assets. We will use the XML layout created in step 2.
        viewBinder = new ViewBinder.Builder(R.layout.native_ad_layout)
                .mainImageId(R.id.native_main_image)
                .iconImageId(R.id.native_icon_image)
                .titleId(R.id.native_title)
                .textId(R.id.native_text)
                .privacyInformationIconImageId(R.id.native_privacy_information_icon_image)
                .build();

  1. (Optional) For direct-sold or mediated native ads, if there are additional assets, extra views for text or images can be included to the ViewBinder, as follows:
ViewBinder viewBinder = new ViewBinder.Builder(R.layout.native_ad_layout)
                .mainImageId(R.id.native_main_image)
                .iconImageId(R.id.native_icon_image)
                .titleId(R.id.native_title)
                .textId(R.id.native_text)
                .privacyInformationIconImageId(R.id.native_privacy_information_icon_imag
  // Your custom fields are bound with the addExtra() call.
  .addExtra("sponsoredtext", R.id.sponsored_text)
  .addExtra("sponsoredimage", R.id.sponsored_image)
  .build();

  1. Create a MoPubStaticNativeAdRenderer with the ViewBinder just created as the argument, and register it with the MoPubNative instance. The MoPubStaticNativeAdRenderer will be used to construct and render the ad view.
moPubNative.registerAdRenderer(new MoPubStaticNativeAdRenderer(viewBinder));

  1. (Optional) To improve the relevance of ads that get shown in your app, you can choose to pass location and/or additional keyword data (see the data passing guide) with the ad request. You can also specify exactly which assets you want, to help conserve bandwidth.
EnumSet<RequestParameters.NativeAdAsset> desiredAssets = EnumSet.of(
               RequestParameters.NativeAdAsset.TITLE,
               RequestParameters.NativeAdAsset.TEXT,
               RequestParameters.NativeAdAsset.CALL_TO_ACTION_TEXT,
               RequestParameters.NativeAdAsset.MAIN_IMAGE,
               RequestParameters.NativeAdAsset.ICON_IMAGE,
               RequestParameters.NativeAdAsset.STAR_RATING
       );

(Optional) Then, create a new RequestParameters object using the Builder():

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

  1. Call MoPubNative.makeRequest() to request an ad from the server and download associated images asynchronously.
moPubNative.makeRequest();

(Optional) You may optionally pass in the above RequestParameters object for additional targeting.

moPubNative.makeRequest(mRequestParameters);

  1. Upon success, the MoPubNativeNetworkListener.onNativeLoad() method will be called with an instance of NativeAd. Upon failure, the MoPubNativeNetworkListener.onNativeFail() method will be called with a corresponding error code object.
moPubNativeNetworkListener = new MoPubNative.MoPubNativeNetworkListener() {
            @Override
            public void onNativeLoad(final NativeAd nativeAd) {
			Log.d(TAG, "onNativeLoad");
			...
            }
            @Override
            public void onNativeFail(NativeErrorCode errorCode) {
			Log.d(TAG, "onNativeFail: " + errorCode.toString());
			...
            }
        };

(Optional) To receive callbacks for impression and click tracking, in the onNativeLoad() callback, register the MoPubNativeEventListener, and override onImpression() and onClick().

moPubNativeEventListener = new NativeAd.MoPubNativeEventListener() {

            @Override
            public void onImpression(View view) {
                Log.d(TAG, "onImpression");
                // Impress is recorded - do what is needed AFTER the ad is visibly shown here.
            }

            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick");
                // Click tracking.
            }
        };

Rendering Native Ads

You have to use AdapterHelper to get a fully populated View containing the rendered ad content. It's important as the View returned by AdapterHelper.getAdView() has a click listener attached to it, and will automatically handle opening the ad's destination URL. It will also track impressions and clicks automatically.

  1. When instantiating an AdapterHelper instance for single ads (without using the MoPubStreamAdPlacer), you can pass in any integers as arguments for the interval:
adapterHelper = new AdapterHelper(this, 0, 3); // When standalone, any range will be fine.
  1. In your onNativeLoad callback, call AdapterHelper.getAdView() with the following parameters:
@NonNull
public View getAdView(@Nullable final View convertView,
        @Nullable final ViewGroup parent,
        @Nullable final NativeAd nativeAd,
        @Nullable final ViewBinder viewBinder) {
   ...
}
  • View convertView: An old view to reuse, if possible, as per Adapter.getView(). If null, a new View will be inflated from XML.

  • ViewGroup parentView: The optional parent view, which provides the correct subclass of LayoutParams for the root view’s XML.

  • NativeAd nativeAd: The native ad returned by the MoPub SDK. This should have been previously obtained from MoPubNativeListener.onNativeLoad(). If this is null or destroyed, the view returned will have its visibility set to View.GONE.

  • ViewBinder viewBinder: It's just a placeholder that is never used in this method. Should just pass in any non-null ViewBinder as below.

 // Retrieve the pre-built ad view that AdapterHelper prepared for us.

                View v = adapterHelper.getAdView(null, nativeAdView, nativeAd, new ViewBinder.Builder(0).build());

                // Set the native event listeners (onImpression, and onClick).
                nativeAd.setMoPubNativeEventListener(moPubNativeEventListener);

//                v.setLayoutParams(new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

                // Add the ad view to our view hierarchy, defined in the XML (activity_main.xml).
                parentView.addView(v);

Native Video

Native video is currently in private beta. For more information about using MoPub for native video ads, please contact your account team or [email protected] to learn more.

The process for inserting manual native video ads is similar, you should have completed the native static ad integration above before starting this. With the addition of native video, AdapterHelper was modified to use the renderers instead of the ViewBinder that is passed in. Right before declaring the MoPubStaticNativeAdRenderer, add the MoPubVideoNativeAdRenderer as outlined below.

To test your implementation, use the following test ad unit ID: 02a2d288d2674ad09f3241d46a44356e It will always return a MoPub native video creative.


  1. Create an XML layout, specifying how video ads should be rendered. The XML layout must include a MediaLayout element as below.
...
<com.mopub.nativeads.MediaLayout
        android:id="@+id/native_ad_video_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
...

As an example, this layout contains one MediaLayout (for the video), two TextViews (for a title and additional text), and an ImageView (for an icon image).

<TODO: INSERT SCREENSHOT OF A SAMPLE NATIVE AD>

  1. Create a MediaViewBinder object specifying the binding between your layout XML and the ad's content.
mediaViewBinder = new MediaViewBinder.Builder(R.layout.native_ad_video_view)
                .mediaLayoutId(R.id.native_ad_video_view)
                .iconImageId(R.id.native_ad_icon_image)
                .privacyInformationIconImageId(R.id.native_ad_daa_icon_image)
                .titleId(R.id.native_ad_title)
                .textId(R.id.native_ad_text)
                .callToActionId(R.id.native_ad_video_cta_btn)
                .build();

  1. Create a MoPubVideoNativeAdRenderer object and register it with the MoPubNative instance. Note: The video renderer must be declared before the MoPubStaticNativeAdRenderer.
moPubNative.registerAdRenderer(new MoPubVideoNativeAdRenderer(mediaViewBinder));
moPubNative.registerAdRenderer(new MoPubStaticNativeAdRenderer(viewBinder));

  1. The process for requesting video native ads is unchanged. See Requesting Native Ads for further instructions setting up the static ad renderer and requesting native ads.

More Resources

  • Android Getting Started Guide
  • Best Practices
  • Code Samples
  • FAQ
  • AdPlacer Integration
  • Custom Manual Integration
  • Mediation