Build SDK Mediation Adapters for Android

Write custom events to support custom ad networks not listed on our Supported Mediation Partners page.

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

Quick Start for Adapter Configuration

To support MoPub SDK 5.5.0+, you must implement an adapter configuration class to enable an interface between your custom event 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 of the adapter or custom event. All of MoPub’s adapters and custom events 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 custom event 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 custom event caches network IDs after a successful ad request, implement the below logic to retain and reuse the data:
    • In the constructor of your custom event (e.g. interstitial), create a new instance of your adapter configuration.
    • When the custom event 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 5.5.0+, you must implement the new logging API to be consistent with MoPub as well as mediation SDKs. When the new API is used, you will have access to more expressive and constructive logs that can help with debugging purposes. Follow the steps outlined below to add logging to your custom events:

  1. Ensure that your custom events are not using any legacy/custom log and/or Android’s Log APIs.
  2. Import MoPubLog (com.mopub.common.logging.MoPubLog) to your custom events.
  3. Optional: Declare a class-level variable to hold the class name of your custom event: this.getClass.getSimpleName().
  4. For each of the ad’s lifecycle events that happens, your custom event 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 custom event 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 custom events 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 custom event 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 Banners

  1. Create a subclass of CustomEventBanner in the com.mopub.mobileads package of your application.

  2. Override the loadBanner(Context, CustomEventBannerListener, Map<String, Object>, Map<String, String>) method and implement code that requests an ad.

  3. When your ad loads successfully, notify MoPub of the event, and display your ad by calling the onBannerLoaded(View) method on the CustomEventBannerListener object (passed in loadAd()).

  4. Similarly, notify the CustomEventBannerListener object when your ad fails to load. To do this, call the onBannerFailed(MoPubErrorCode) method on the listener object. Pass a suitable MoPubErrorCode constant (see MoPubErrorCode.java).

  5. Optional: Notify the listener object of other ad lifecycle events via the corresponding methods on CustomEventBannerListener.

    public void onBannerClicked(); public void onBannerImpression() public void onLeaveApplication();

  6. Optional: Override the onInvalidate() method of CustomEventBanner if your custom event requires any sort of cleanup.

  7. On the MoPub web interface, create a network with the “Custom SDK Network” type. Place the fully qualified class name of your custom event (for example, com.mopub.mobileads.YourCustomEventBanner) in the “Custom Event Class” column.

Once you’ve completed these steps, the MoPub SDK can instantiate your CustomEventBanner 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 CustomEventBanner object on every ad call, so you can safely make changes to the custom event object’s internal state between calls.

Quick Start for Interstitials

  1. Create a subclass of CustomEventInterstitial in the com.mopub.mobileads package of your application.

  2. Override the loadInterstitial(Context, CustomEventInterstitialListener, Map<String, Object>, Map<String, String>) method and implement code that requests an interstitial.

  3. Override the showInterstitial() method and implement code that displays your interstitial.

  4. When your ad loads successfully, you must notify MoPub of the event, and display your ad by calling the onInterstitialLoaded() method on the CustomEventInterstitialListener object (passed in loadAd).

  5. Similarly, you must notify the CustomEventInterstitialListener object when your ad fails to load by calling the onInterstitialFailed(MoPubErrorCode) method on the listener object.

  6. (Optional) Notify the listener object of other ad lifecycle events via the corresponding methods on CustomEventInterstitialListener.

    public void onInterstitialShown(); public void onInterstitialImpression(); public void onInterstitialDismissed(); public void onInterstitialClicked(); public void onLeaveApplication();

  7. Optional: Override the onInvalidate() method of CustomEventInterstitial if your custom event requires any sort of cleanup.

  8. Finally, on the MoPub web interface, create a network with the “Custom SDK Network” type. Place the fully qualified class name of your custom event (for example, com.mopub.mobileads.YourCustomEventInterstitial) in the “Custom Event Class” column.

The MoPub SDK can now instantiate your CustomEventInterstitial subclass at the correct time while your application is running. You don’t need to instantiate any of these subclasses in your application code.

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

Quick Start for Rewarded Videos

1.  Create a subclass of CustomEventRewardedVideo in the com.mopub.mobileads package of your application.

2.  Use the checkAndInitializeSdk(Context, Map<String, Object>, Map<String, String>) method to initialize the network SDK.

3.  Override the loadWithSdkInitialized(Context, Map<String, Object>, Map<String, String>) method and implement code that requests a rewarded interstitial.

4.  Override the hasVideoAvailable() method to return whether or not there is a video available from the network SDK.

5.  Override the showVideo() method and implement code that displays your rewarded interstitial.

6.  Notify the listener object of all the ad lifecycle events via the corresponding methods on MoPubRewardedVideoManager.

public void onRewardedVideoLoadSuccess
public void onRewardedVideoLoadFailure
public void onRewardedVideoStarted
public void onRewardedVideoPlaybackError
public void onRewardedVideoClicked
public void onRewardedVideoClosed
public void onRewardedVideoCompleted

7.  Override the onInvalidate() method of CustomEventRewardedVideo if your custom event requires any sort of cleanup.

8.  Implement MediationSettings marker interface if you want to enable to publishers to pass any network-specific additional parameters during the initialization.

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.
  1. 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.
  2. Implement impression tracking options: All Native Custom Events 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.

  3. Implement click tracking details: All Native Custom Events 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.

  4. 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.
  5. 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.

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

  7. 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: Native Ads

Because Native Ads inflate ViewGroup and View subclasses, developing a Native Ad custom event can be more complicated than developing custom events for banners or interstitials.

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 Custom Event. 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

NOTE You may subclass StaticNativeAd for simpler code. See 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 Custom Events

The loadAd() / loadInterstitial() method of your custom event subclass exposes two Map objects that you can use to provide your custom event with any additional data it needs: Map<String, Object> localExtras and Map<String, String> serverExtras.

  • 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>).

  • serverExtras: The serverExtras Map is populated with data entered in the MoPub web interface. 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.

Last updated October 16, 2019

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.

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