Build SDK Mediation Adapters for Android

Write mediation adapters to support custom ad networks not listed on our Supported Mediation Partners list.

Disclaimer: MoPub discourages using non-supported network adapters and does not provide testing or technical support for problems arising from their use. Refer to our list of supported network adapters.

Quick Start for Adapter Configuration

To support MoPub SDK v5.5.0+, you must implement an adapter configuration class to enable an interface between your mediation adapter and the MoPub SDK. This interface faciliates a pre-initialization of your SDK, and can be written using the steps below:

  1. Create a subclass of BaseAdapterConfiguration (or implement the AdapterConfiguration interface) in the com.mopub.mobileads package of your application. The name of this class should contain your ad network name.

  2. Override the getAdapterVersion() method and implement code that returns the version number the mediation adapter. All of MoPub’s adapters and mediation adapters use a 4-digit versioning scheme, of which the leftmost 3 digits correspond to the network SDK version, and the last digit denotes the minor version number referring to an adapter release.

  3. Override the getBiddingToken() method and implement code that returns the bidding token String from your ad network. If the ad network does not support Advanced Bidding, return null.

  4. Override the getMoPubNetworkName() method and implement code that returns a lowercase String that represents your ad network name. Use underscores if the String needs to contain spaces.

  5. Override the getNetworkSdkVersion() method and implement code that returns the version number of your ad network SDK.

  6. Override the initializeNetwork(@NonNull Context context, @Nullable Map<String, String> configuration, @NonNull OnNetworkInitializationFinishedListener listener) method and implement code that initializes your network SDK. This logic executes alongside the initialization of the MoPub SDK. Ensure that your mediation adapter always calls onNetworkInitializationFinished() afterwards.

    • If initialization succeeds, pass MoPubErrorCode.ADAPTER_INITIALIZATION_SUCCESS as the parameter to the callback.

    • If initialization fails, pass MoPubErrorCode.ADAPTER_CONFIGURATION_ERROR.

  7. (Optional if you extend BaseAdapterConfiguration): If you implement the AdapterConfiguration interface and if your mediation adapter caches network IDs after a successful ad request, implement the below logic to retain and reuse the data:

    • In the constructor of your mediation adapter (e.g. fullscreen ads), create a new instance of your adapter configuration.

    • When the mediation adapter has validated the network IDs returned from the server, call setCachedInitializationParameters(@NonNull final Context context, @Nullable final Map<String, String> configuration) on your adapter configuration instance with configuration being the Map containing the network parameters. Subsequently, override and implement getCachedInitializationParameters(@NonNull final Context context) to get a Map of the cached data.

    • Override and implement setMoPubRequestOptions(@Nullable final Map<String, String> moPubRequestOptions) and getMoPubRequestOptions() to set and get a map of options to be passed to the MoPub ad server.

Quick Start for Adapter Logging

To support MoPub SDK v5.5.0+, you must implement the new logging API to be consistent with MoPub and mediation SDKs. When you use the new API, you will have access to more expressive and constructive logs for debugging purposes. Follow the steps outlined below to add logging to your mediation adapters:

  1. Ensure that your mediation adapters are not using any legacy/custom log and/or Android’s Log APIs.

  2. Import MoPubLog (com.mopub.common.logging.MoPubLog) to your mediation adapters.

  3. Optional: Declare a class-level variable to hold the class name of your mediation adapter: this.getClass.getSimpleName().

  4. For each of the ad’s lifecycle events that happens, your mediation adapter will log it by invoking MoPubLog.log(). The call accepts an official enum constant (representing the event), followed by different macros representing the additional data to be logged (e.g. the class name from #3).

    For example, after an ad request, your mediation adapter should log a LOAD_ATTEMPTED event: MoPubLog.log(adUnitId, LOAD_ATTEMPTED, ADAPTER_NAME). For the comprehensive list of the enum constants as well as the macros, check out the AdapterLogEvent enum from the SDK. Your mediation adapters should make use of as many such enum constants as you see fit.

  5. For any other generic messages that need to be logged, your mediation adapter will use the CUSTOM macro, followed by a String containing the message. For example: MoPubLog.log(AdapterLogEvent.CUSTOM, ADAPTER_NAME, "Ad view created.").

Quick Start for Inline and Fullscreen Ads

This API requires v5.13.0 or newer of the MoPub SDK.

  1. Create a subclass of BaseAd in the com.mopub.mobileads package of your application, and implement the following methods.

  2. Override checkAndInitializeSdk(Activity, AdData) to initialize your SDK. From then on, the SDK should be reused without initialization.

    • Return false if your SDK does not need to initialize, or has previously initialized.

    • Return true if your SDK needs to initialize (especially rewarded ads requests). If so, implement this method with code to initialize your SDK.

  3. Override load(Context, AdData) to request an ad. Calling getExtras() on the AdData instance gets you a Map<String, String> containing the IDs needed for your ad logic.

    • When an ad successfully loads, call mLoadListener.onAdLoaded() to notify MoPub of the event.

    • When an ad has registered an impression, if you have set setAutomaticImpressionAndClickTracking(boolean) to false to manually track impressions and clicks, call mInteractionListener.onAdImpression(). This is optional otherwise, as setAutomaticImpressionAndClickTracking() is set to true by default, which tells MoPub to use automatic impression and click tracking.

    • When an ad fails to load, call mLoadListener.onAdLoadFailed(MoPubErrorCode) to notify MoPub of the event. Pass in an appropriate MoPubErrorCode specific to that failure case.

  4. Override show() to display an ad. This is required for fullscreen ads, but optional otherwise.

    • When an ad successfully shows, call mInteractionListener.onAdShown() to notify MoPub of the event. If you call this method, you should make sure to call mInteractionListener.onAdDismissed() later.

    • When an ad fails to show, call mInteractionListener.onAdFailed() to notify MoPub of the event.

  5. Override getAdView() to return the inline ad view. This is required for inline, but optional otherwise.

  6. Override getAdNetworkId() to return the current ad unit ID. Return an empty String if your SDK doesn’t support the concept of an ID.

  7. Override getLifecycleListener() to return an instance of LifecycleListener if your SDK wants to be notified of activity lifecycle events in the application. Return null otherwise. This fails if the publisher is not notifying MoPub in the first place (for example, MoPub.onPause(Activity).

  8. Override onInvalidate() if your adapter requires any sort of cleanup.

  9. Optional: Notify MoPub of the following events wherever applicable:

    Ad format Listener When to call
    Inline mInteractionListener.onAdClicked() When the user taps on an ad
      mInteractionListener.onAdExpanded() When an ad is expanded
      mInteractionListener.onAdCollapsed() When an ad is collapsed
    Fullscreen mInteractionListener.onAdClicked() When the user taps on an ad
      mInteractionListener.onAdDismissed() When an ad is dismissed
      mInteractionListener.onAdComplete(MoPubReward.success(label, amount)) When an ad has completed its minimum required viewing, such as for giving a reward in a rewarded ad.
  10. On the MoPub web interface, create a network with the “Custom SDK Network” type. Place the fully qualified class name of your mediation adapter (for example, com.mopub.mobileads.YourInlineAdAdapter) in the “Custom Event Class” column.

Once you’ve completed these steps, the MoPub SDK can instantiate your BaseAd subclass at the proper time while your application is running. You do not need to instantiate any of these subclasses in your application code.

Note: the MoPub SDK will instantiate a new BaseAd object on every ad call, so you can safely make changes to the mediation adapter object’s internal state between calls.

Quick Start for Native Ads

  1. Create a subclass of com.mopub.nativeads.StaticNativeAd in the com.mopub.nativeads package. This class will implement a MoPub Native Ad using a native ad from another network.

  2. After loading the native ad from the network, initialize your object using the following setter methods:

    Method Description
    setTitle() For a title string.
    setText() For a text string.
    setIconImageUrl() For the icon image.
    setMainImageUrl() For the main image.
    setCallToAction() For a call to action string.
    setStarRating() For a star rating between 0 and 5 (optional).
    setClickDestinationUrl() For a click destination URL.
    addExtra() For any additional fields. A string key is required to store and retrieve them.
    addImpressionTracker() For any additional impression tracking urls you want fired.
    setImpressionMinTimeViewed() For the minimum amount of time the view is required to be on the screen before recording an impression. Set this value according to how the network records their impression. The default value is 500ms.
  3. Implement lifecycle methods for handling events with your native ad:

    • prepare: Override prepare() before an ad is displayed in the app. Set up impression tracking in this method. Refer to com.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd#prepare for an example of setting up impression tracking using the com.mopub.nativeads.ImpressionTracker class.

    • handleClick: Implement handleClick() if the network requires you to explicitly handle click events of views rendered to screen.

    • clear: Call clear when an ad is no longer displayed to a user. After this, you can delete or recycle the View used for the ad. Implement this to clear any viewability tracking code you are using. If using an ImpressionTracker instance, remove the view here.

    • destroy: Call destroy when the ad will never be displayed again. Implement it if the network requires you to destroy or clean up their native ad when you are finished with it.

  4. Implement impression tracking options: All Native mediation adapters must implement their own impression tracking and call #notifyAdImpressed when the impression is recorded. MoPub provides utility classes to provide automatic impression tracking. StaticNativeAd implements ImpressionInterface, so you can instantiate an ImpressionTracker in your object’s construction. Add your ad’s View to an ImpressionTracker instance in prepare and remove it from the ImpressionTracker in clear. Call ImpressionTracker#destroy in destroy. See com.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd for an example following this pattern.

  5. Implement click tracking details: All Native mediation adapters are responsible for firing click trackers when sending the user to the destination URL. You can easily do this by calling #notifyAdClicked immediately before opening the destination URL. You can also delegate Click URL handling to the MoPub SDK. Implement ClickInterface in your BaseNativeAd subclass and create an instance of com.mopub.nativeads.NativeClickHandler in your class construction. In prepare, add your ad’s View to the NativeClickHandler and remove it from the click handler in clear. See com.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd for an example following this pattern.

  6. If the network exposes impression or click callbacks, have them call the following methods to notify the SDK to record an impression or click. This is an alternative to using the MoPub ImpressionTracker, ImpressionInterface, NativeClickHandler and ClickInterface classes.

    • notifyAdImpressed: CallnotifyAdImpressed from the network’s impression callback to notify the SDK to record an impression.

    • notifyAdClicked: CallnotifyAdClicked from the network’s click callback to notify the SDK to record a click event.

  7. Create a subclass of CustomEventNative in the com.mopub.nativeads package. This class overrides the loadNativeAd() method and requests a native ad from the network. The serverExtras map contains any values that were entered into the “Custom Event Class Data” field when you created your Custom SDK Network in the MoPub web UI, such as the placement ID.

  8. Once the ad is loaded, create an instance of the StaticNativeAd or BaseNativeAd class as described above. If the ad fails to load, call customEventNativeListener.onNativeAdFailed with a NativeErrorCode.

  9. Before calling customEventNativeListener.onAdLoaded, call the superclass’s preCacheImages method to ensure that images are displayed immediately when your native ad renders. If images fail to download, call customEventNativeListener.onNativeAdFailed.

Advanced Instructions for Native Ads

Because Native Ads inflate ViewGroup and View subclasses, developing a Native Ad mediation adapter can be more complicated than developing mediation adapters for inline or fullscreen ads.

A full implementation of Native Ads Mediation for the MoPub Android SDK requires three classes:

  1. Subclass of CustomEventNative. This class is instantiated by the MoPub SDK when the MoPub ad server returns a result saying the third-party network should load a native ad. This class is responsible for requesting a native ad from the third-party SDK and notifying the MoPub SDK when the ad has loaded or failed to load by calling the corresponding methods on CustomEventNativeListener.

  2. Subclass of BaseNativeAd. This class represents the state of the ad and handles impression and click tracking, and forwards that notification to the MoPub SDK.

  3. Implementation of MoPubAdRenderer. This class is related to the NativeAd subclass.

If your SDK contains text, images, and a call to action link, the MoPub SDK provides classes that simplify development of your mediation adapter. Follow the instructions in Quick Start for Native Ads for the simplest implementation of Native Ads mediation. You do not need to write a MoPubAdRenderer subclass, and you will subclass StaticNativeAd instead of BaseNativeAd.

Subclassing BaseNativeAd

You may subclass StaticNativeAd for simpler code. Refer to the Quick Start for Native Ads.

  1. Extend BaseNativeAd to show native ads for the mediated ads SDK using MoPub.

  2. Implement the #prepare(View) method. This method is called just before an ad is displayed on screen. It’s commonly used to initialize impression tracking.

  3. Implement the #clear(View) method. This is called when the ad is no longer visible to the user and may be recycled. Stop any background tasks associated with this ad (for example, impression tracking).

  4. Implement the #destroy() method. This is called when the ad will never be displayed to the user again. Any state associated with the ad (downloaded image or video files, background tasks) can be cleaned up.

  5. When your SDK records an impression, call the method BaseNativeAd#notifyAdImpressed(). You can also use MoPub-provided utility classes to provide automatic impression tracking. You can implement ImpressionInterface, and instantiate an ImpressionTracker in your object’s construction. Add your ad’s View to an ImpressionTracker instance in prepare() and remove it from the ImpressionTracker in clear(). Call ImpressionTracker#destroy() in destroy(). See com.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd for an example following this pattern.

  6. When your SDK records an ad click, call the BaseNativeAd#notifyAdClicked() method before opening the destination URL. You can also delegate Click URL handling to the MoPub SDK. Implement ClickInterface in your BaseNativeAd subclass and create an instance of com.mopub.nativeads.NativeClickHandler in your class construction. In prepare(), add your ad’s View to the NativeClickHandler and remove it from the click handler in clear(). See com.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd for an example following this pattern.

Subclassing CustomEventNative

  1. Create a subclass of CustomEventNative in the com.mopub.nativeads package. This class overrides the loadNativeAd method and requests a native ad from the network. The serverExtras map contains any values that were entered into the “Custom Event Class Data” field when you created your Custom Native Network in the MoPub web UI, such as the placement ID.

  2. Once the ad is loaded, create an instance of the StaticNativeAd or BaseNativeAd class as described above, then call customEventNativeListener.onNativeAdLoaded(). If the ad fails to load, call customEventNativeListener.onNativeAdFailed() with a NativeErrorCode.

Implementing MoPubAdRenderer<T>

Each BaseNativeAd needs a corresponding renderer that understands the fields that the BaseNativeAd provides, as well as how to construct and populate the View that shows the ad. MoPub provides the class MoPubStaticNativeAdRenderer that supports all subclasses of StaticNativeAd.

To create your own renderer for your BaseNativeAd (in this example, suppose your ad is of the class MyNativeAd):

  1. Implement MoPubAdRenderer:

     public class MyNativeAdRenderer implements MoPubAdRenderer<MyNativeAd> {
    
     }
    
  2. Implement the MoPubAdRenderer#supports method :

     @Override
     public boolean supports(@NonNull final BaseNativeAd nativeAd) {
       return nativeAd instanceOf MyNativeAd.class;
     }
    
  3. Implement the createAdView() and renderAdView() methods.

    • The createAdView() method inflates a layout for the ad type that the renderer supports.
    • The renderAdView() method attaches the ad creative to the View, setting text and drawable values. Assume that the View provided to renderAdView() has been used to show a different ad in the past.

Passing Extra Data To Mediation Adapters

  • localExtras: The localExtras Map can be set anywhere in your application code by calling MoPubView.setLocalExtras(Map<String, Object>) or MoPubInterstitial.setLocalExtras(Map<String, Object>).

  • extras: For inline and fullscreen ads, calling getExtras() on the AdData instance gets you a Map<String, String> containing the IDs required for your ad logic. These are the key-value pairs that you (as a publisher) have entered in on the MoPub UI. Specifically, after navigating to the Custom SDK Network edit page, you can select the “Custom Event Class Data” column and enter a JSON object with String keys and values in the Data field (e.g. {"id": "12345", "foo": "bar"}). This is particularly useful for passing down third-party Network IDs without making changes to your application code.

  • serverExtras: This API is applicable to native ads only. It is functionally equivalent to the extras API for inline and fullscreen ads.

Last updated October 06, 2020

TWITTER, MOPUB, and the Bird logo are trademarks of Twitter, Inc. or its affiliates. All third party logos and trademarks included are the property of their respective owners.

© 2020 MoPub (a division of Twitter, Inc.)