Skip to content
nieny225 edited this page Aug 15, 2017 · 1 revision

Manual Integration of Native Ads

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 integration flowchart. 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 following best practices article for guidelines on how native ads should be displayed in your app. Requesting Native Ads 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.

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

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

Create a ViewBinder object to bind our layout XML and the ad’s assets. We will use the XML layout created in step 2.

Note: 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:

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.

(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.

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

Call MoPubNative.makeRequest() to request an ad from the server and download associated images asynchronously. You may optionally pass in the above RequestParameters object for additional targeting.

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.

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

Rendering Native Ads In your onNativeLoad callback, call AdapterHelper.getAdView() to get a fully populated View containing the rendered ad content. When instantiating an AdapterHelper instance for single ads (without using the MoPubStreamAdPlacer), you can pass in any integers as arguments for the interval It takes the following parameters: 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. @Deprecated @NonNull public View getAdView(@Nullable final View convertView,

        @Nullable final ViewGroup parent,
        @Nullable final NativeAd nativeAd,
        @Nullable final ViewBinder viewBinder) {
    final Context context = mContext.get();
    if (context == null) {
        MoPubLog.w("Weak reference to Context in"
                + " AdapterHelper became null. Returning empty view.");
        return new View(mApplicationContext);
    }
    return NativeAdViewHelper.getAdView(
            convertView,
            parent,
            context,
            nativeAd
    );

}

Note: The View returned by 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.

Native Video The process for inserting manual native video ads is similar. 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. [Elaborate]. Create an XML layout, specifying how video ads should be rendered. The XML layout must include a MediaLayout element. 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). For example: res/layout/native_video_ad_layout.xml

Create a MediaViewBinder object specifying the binding between your layout XML and the ad’s content.

Create a MoPubVideoNativeAdRenderer object and register it with the MoPubNative instance. Note: The video renderer must be declared before the MoPubStaticNativeAdRenderer.

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.

What’s Next? Mediation More Resources Android Getting Started Guide

Best Practices

Code Samples

FAQ

AdPlacer Integration

Custom Manual Integration

Inserting Native Ads into BaseAdapter subclasses



AdapterHelper contains a few convenience methods for including native ads in a feed. Create an instance of AdapterHelper, passing in a Context, along with int start (the position of the first ad in the feed) and int interval (the frequency with which ads are shown in the feed). Note: It is required to override certain Adapter methods as the inclusion of Native Ads will modify the position, number, and type of elements in the corresponding feed. Update the adapter’s getCount(...) to account for the addition of ads in the feed. Example (subclassing ArrayAdapter): mAdapterHelper = new AdapterHelper(context, start, interval);

@Override public int getCount() { int originalCount = super.getCount(); return mAdapterHelper.shiftedCount(originalCount);

Increment the adapter’s getViewTypeCount() method, indicating that an additional view type has been added to the adapter. Example (subclassing ArrayAdapter): int originalViewTypeCount = 2; // number of unique view types in the feed

@Override public int getViewTypeCount() { // Add 1 for native ad view type return originalViewTypeCount + 1;

Update the adapter’s getItem(...) method to account for the fact that ads are being placed in the feed. Example (subclassing ArrayAdapter): mAdapterHelper = new AdapterHelper(context, start, interval);

@Override public T getItem(int position) { // Shifted position returns the original position of the content // in ArrayAdapter's backing array int shiftedPosition = mAdapterHelper.shiftedPosition(position); return super.getItem(shiftedPosition); }

Update the adapter’s getItemViewType(...) method to specify the positions in the feed associated with native ads. Example (subclassing ArrayAdapter): mAdapterHelper = new AdapterHelper(context, start, interval);

private static final int EXISTING_ROW_TYPE_0 = 0; private static final int EXISTING_ROW_TYPE_1 = 1; private static final int MOPUB_NATIVE_ROW_TYPE = 2;

@Override public int getItemViewType(int position) { if (mAdapterHelper.isAdPosition(position) { return MOPUB_NATIVE_ROW_TYPE; } else { int shiftedPosition = mAdapterHelper.shiftedPosition(position); // Previous getItemViewType() logic, using shiftedPosition as the new index } }

Update getView(...) to return a native ad for the appropriate feed positions. Example (subclassing ArrayAdapter): mAdapterHelper = new AdapterHelper(context, start, interval);

@Override View getView(int position, View convertView, ViewGroup parent) { if (mAdapterHelper.isAdPosition(position)) { return new AdapterHelper.getAdView( convertView, parent, nativeAd, viewBinder, moPubNativeListener ); } else { // Previous getView() logic } }

Important Notes Avoid Excessive Ad Requests Making requests for ads which are never displayed to the user will consume unnecessary resources and may negatively impact your revenue. Therefore, your application should make an effort to request ads only when they are likely to be displayed. In particular, avoid caching large quantities of ads for long periods of time. For example, when a user initially navigates to a ListView with many rows, you should avoid requesting ads that will be displayed near the bottom of the ListView (i.e. far below the fold). Instead, wait for the user to begin scrolling through the feed before making additional ad requests.

Clone this wiki locally