Build SDK Mediation Adapters for Android
- Quick Start for Adapter Configuration
- Quick Start for Adapter Logging
- Quick Start for Inline and Fullscreen Ads
- Quick Start for Native Ads
- Passing Extra Data To Mediation Adapters
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:
-
Create a subclass of
BaseAdapterConfiguration
(or implement theAdapterConfiguration
interface) in thecom.mopub.mobileads
package of your application. The name of this class should contain your ad network name. -
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. -
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, returnnull
. -
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. -
Override the
getNetworkSdkVersion()
method and implement code that returns the version number of your ad network SDK. -
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 callsonNetworkInitializationFinished()
afterwards.-
If initialization succeeds, pass
MoPubErrorCode.ADAPTER_INITIALIZATION_SUCCESS
as the parameter to the callback. -
If initialization fails, pass
MoPubErrorCode.ADAPTER_CONFIGURATION_ERROR
.
-
-
(Optional if you extend
BaseAdapterConfiguration
): If you implement theAdapterConfiguration
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 withconfiguration
being the Map containing the network parameters. Subsequently, override and implementgetCachedInitializationParameters(@NonNull final Context context)
to get aMap
of the cached data. -
Override and implement
setMoPubRequestOptions(@Nullable final Map<String, String> moPubRequestOptions)
andgetMoPubRequestOptions()
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:
-
Ensure that your mediation adapters are not using any legacy/custom log and/or Android’s
Log
APIs. -
Import
MoPubLog
(com.mopub.common.logging.MoPubLog
) to your mediation adapters. -
Optional: Declare a class-level variable to hold the class name of your mediation adapter:
this.getClass.getSimpleName()
. -
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 theAdapterLogEvent
enum from the SDK. Your mediation adapters should make use of as many such enum constants as you see fit. -
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.
-
Create a subclass of
BaseAd
in thecom.mopub.mobileads
package of your application, and implement the following methods. -
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.
-
-
Override
load(Context, AdData)
to request an ad. CallinggetExtras()
on theAdData
instance gets you aMap<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)
tofalse
to manually track impressions and clicks, callmInteractionListener.onAdImpression()
. This is optional otherwise, assetAutomaticImpressionAndClickTracking()
is set totrue
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 appropriateMoPubErrorCode
specific to that failure case.
-
-
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 callmInteractionListener.onAdDismissed()
later. -
When an ad fails to show, call
mInteractionListener.onAdFailed()
to notify MoPub of the event.
-
-
Override
getAdView()
to return the inline ad view. This is required for inline, but optional otherwise. -
Override
getAdNetworkId()
to return the current ad unit ID. Return an empty String if your SDK doesn’t support the concept of an ID. -
Override
getLifecycleListener()
to return an instance ofLifecycleListener
if your SDK wants to be notified of activity lifecycle events in the application. Returnnull
otherwise. This fails if the publisher is not notifying MoPub in the first place (for example,MoPub.onPause(Activity
). -
Override
onInvalidate()
if your adapter requires any sort of cleanup. -
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. -
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
-
Create a subclass of
com.mopub.nativeads.StaticNativeAd
in thecom.mopub.nativeads
package. This class will implement a MoPub Native Ad using a native ad from another network. -
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. -
Implement lifecycle methods for handling events with your native ad:
-
prepare
: Overrideprepare()
before an ad is displayed in the app. Set up impression tracking in this method. Refer tocom.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd#prepare
for an example of setting up impression tracking using thecom.mopub.nativeads.ImpressionTracker
class. -
handleClick
: ImplementhandleClick()
if the network requires you to explicitly handle click events of views rendered to screen. -
clear
: Callclear
when an ad is no longer displayed to a user. After this, you can delete or recycle theView
used for the ad. Implement this to clear any viewability tracking code you are using. If using anImpressionTracker
instance, remove the view here. -
destroy
: Calldestroy
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.
-
-
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
implementsImpressionInterface
, so you can instantiate anImpressionTracker
in your object’s construction. Add your ad’sView
to anImpressionTracker
instance inprepare
and remove it from theImpressionTracker
inclear
. CallImpressionTracker#destroy
indestroy
. Seecom.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd
for an example following this pattern. -
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. ImplementClickInterface
in your BaseNativeAd subclass and create an instance ofcom.mopub.nativeads.NativeClickHandler
in your class construction. Inprepare
, add your ad’sView
to theNativeClickHandler
and remove it from the click handler inclear
. Seecom.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd
for an example following this pattern. -
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
andClickInterface
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.
-
-
Create a subclass of
CustomEventNative
in thecom.mopub.nativeads
package. This class overrides theloadNativeAd()
method and requests a native ad from the network. TheserverExtras
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. -
Once the ad is loaded, create an instance of the
StaticNativeAd
orBaseNativeAd
class as described above. If the ad fails to load, callcustomEventNativeListener.onNativeAdFailed
with aNativeErrorCode
. -
Before calling
customEventNativeListener.onAdLoaded
, call the superclass’spreCacheImages
method to ensure that images are displayed immediately when your native ad renders. If images fail to download, callcustomEventNativeListener.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:
-
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 onCustomEventNativeListener
. -
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. -
Implementation of
MoPubAdRenderer
. This class is related to theNativeAd
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.
-
Extend
BaseNativeAd
to show native ads for the mediated ads SDK using MoPub. -
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. -
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). -
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. -
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 implementImpressionInterface
, and instantiate anImpressionTracker
in your object’s construction. Add your ad’sView
to anImpressionTracker
instance inprepare()
and remove it from theImpressionTracker
inclear()
. CallImpressionTracker#destroy()
indestroy()
. Seecom.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd
for an example following this pattern. -
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. ImplementClickInterface
in yourBaseNativeAd
subclass and create an instance ofcom.mopub.nativeads.NativeClickHandler
in your class construction. Inprepare()
, add your ad’sView
to theNativeClickHandler
and remove it from the click handler inclear()
. Seecom.mopub.nativeads.MoPubCustomEventNative.MoPubStaticNativeAd
for an example following this pattern.
Subclassing CustomEventNative
-
Create a subclass of
CustomEventNative
in thecom.mopub.nativeads
package. This class overrides theloadNativeAd
method and requests a native ad from the network. TheserverExtras
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. -
Once the ad is loaded, create an instance of the
StaticNativeAd
orBaseNativeAd
class as described above, then callcustomEventNativeListener.onNativeAdLoaded()
. If the ad fails to load, callcustomEventNativeListener.onNativeAdFailed()
with aNativeErrorCode
.
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
):
-
Implement
MoPubAdRenderer
:public class MyNativeAdRenderer implements MoPubAdRenderer<MyNativeAd> { }
-
Implement the
MoPubAdRenderer#supports
method :@Override public boolean supports(@NonNull final BaseNativeAd nativeAd) { return nativeAd instanceOf MyNativeAd.class; }
-
Implement the
createAdView()
andrenderAdView()
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 torenderAdView()
has been used to show a different ad in the past.
- The
Passing Extra Data To Mediation Adapters
-
localExtras
: ThelocalExtras
Map can be set anywhere in your application code by callingMoPubView.setLocalExtras(Map<String, Object>)
orMoPubInterstitial.setLocalExtras(Map<String, Object>)
. -
extras
: For inline and fullscreen ads, callinggetExtras()
on theAdData
instance gets you aMap<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 theextras
API for inline and fullscreen ads.
Last updated December 03, 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.)