Skip to main content
Version: SDK 4.x

Migration from 3.x to 4.0

BidMachine SDK 4.0 replaces the public API of 3.x. There is no compatibility layer: code written for 3.x doesn't compile against 4.0 and has to be updated as described on this page.

The main changes:

  • The SDK is initialized per publisher source and returns a BidMachineInstance. Ads are loaded through the instance, request builders are gone.
  • Ad objects are created by the SDK and delivered to AdLoadCallback, they have no public constructors.
  • Public classes moved to new packages: io.bidmachine.model.* for models and io.bidmachine.format.* for ad formats.
  • Privacy settings are passed as ConsentData, targeting and publisher data as FirstPartyData.
  • Native ads got a new binding API: bind / unbind, the ad owns its media, privacy and "Ad" badge views.
Staying on 3.x

SDK 3.8.x remains available. Its documentation is in the version selector at the top of the page, under 3.x.

1. Dependency​

SDK 4.0 is distributed through Maven Central instead of the BidMachine repository. The coordinates are unchanged, only the repository and the version change:

build.gradle
repositories {
mavenCentral()
}

dependencies {
implementation "io.bidmachine:ads:4.0.0"
}
  • The https://artifactory.bidmachine.io/bidmachine repository is no longer needed for the SDK itself. Keep it only if your app uses other BidMachine artifacts that are published there.
  • minSdk stays 21.
  • The ads artifact no longer brings the legacy GAM adapters (gam, gam_dynamic) as dependencies. If your app still uses them, move to the official AdMob / GAM adapter before upgrading.
  • Header bidding networks inside BidMachine are removed together with BidMachine.registerNetworks. Remove the io.bidmachine:ads.networks.* dependencies.

2. Initialization​

In 3.x the SDK had one global state configured through static BidMachine methods. In 4.0 BidMachine.initialize returns a BidMachineInstance for the given source id, and ads are loaded through that instance. Keep the reference: there is no static getter for it.

// 3.x
BidMachine.setTestMode(true);
BidMachine.setLoggingEnabled(true);
BidMachine.initialize(context, "SOURCE_ID", () -> {
// SDK is ready
});
// 4.0
BidMachine.setTestMode(true)
BidMachine.setLoggingEnabled(true)
val bidMachineInstance: BidMachineInstance = BidMachine.initialize(context, "SOURCE_ID")
  • BidMachine.initialize(context, sourceId, bidMachineConfiguration = null) returns the instance immediately. There is no initialization callback and no isInitialized(): loads and token requests made before the initialization finishes are queued and run when it completes. If the initialization fails, they fail with BMError.NotInitialized.
  • Calling initialize again with the same source id returns the same instance; a new configuration is ignored. Several source ids give several independent instances.
  • BidMachineConfiguration(mediationInfo) carries the mediation info (MediationInfo(name, version, adapterVersion)). It is used by mediation adapters.
  • setTestMode and setLoggingEnabled stay global on BidMachine.
  • BidMachine.getExtrasParam(context, key) is replaced with bidMachineInstance.getCustomParams().

3. Privacy and Targeting​

See Data Privacy and First-Party Data for the full description.

Privacy​

All 3.x privacy setters are replaced with one global BidMachine.setConsentData(ConsentData?):

3.x4.0 ConsentData
BidMachine.setSubjectToGDPR(Boolean)gdprApplies
BidMachine.setConsentStatus(boolean)gdprConsent
BidMachine.setCoppa(Boolean)coppa
BidMachine.setNonPersonalized(Boolean)nonPersonalized
BidMachine.setGPP(String, List<Integer>)gppString, gppSids
BidMachine.setConsentConfig(boolean, String)removed
BidMachine.setUSPrivacyString(String)removed
BidMachine.setConsentData(
ConsentData.Builder()
.setGdprApplies(true)
.setGdprConsent(true)
.setCoppa(false)
.build()
)

The SDK still reads the IAB values from the default SharedPreferences (IABTCF_gdprApplies, IABTCF_TCString, IABUSPrivacy_String, IABGPP_HDR_GppString, IABGPP_GppSID), so a CMP that writes them keeps working without code.

The SDK does not watch these values. When the consent changes during the app's run, including a change the CMP made, call BidMachine.setConsentData again: the SDK compares ConsentData and the CMP's IABTCF_gdprApplies / IABTCF_TCString with the previous call's and, if anything differs, repeats the initialization request and restarts the sessions. A call that changes nothing does nothing. The CMP's US Privacy and GPP values are not compared; the next request carries them as they are.

Targeting and Publisher Data​

BidMachine.setTargetingParams(TargetingParams) and BidMachine.setPublisher(Publisher) are replaced with bidMachineInstance.setFirstPartyData(FirstPartyData?), which is set per instance. Per-request targeting is removed.

3.x4.0 FirstPartyData
TargetingParams.setUserId, setGender, setCountry, setCity, setZip, setExternalUserIdssame names
TargetingParams.setBirthdayYearyearOfBirth
TargetingParams.setKeywords(String...)keywords: List<String>
TargetingParams.setDeviceLocationlocation
TargetingParams.setStoreUrl, setStoreCategory, setStoreSubCategories, setPaidstoreUrl, storeCategory, storeSubCategories, isPaid
TargetingParams.addBlockedAdvertiserIABCategoryblockedCategories
TargetingParams.addBlockedAdvertiserDomainblockedAdvertisers
TargetingParams.addBlockedApplicationblockedApps
TargetingParams.setFrameworkremoved
Publisher id, name, domain, categoriespublisherId, publisherName, publisherDomain, publisherCategories
bidMachineInstance.setFirstPartyData(
FirstPartyData.Builder()
.setUserId("user_id")
.setGender(Gender.Female)
.setYearOfBirth(1990)
.build()
)

Gender, ExternalUserId and ImageData moved to io.bidmachine.model.

4. Loading Ads​

Requests Are Replaced with load* Methods​

The request builders (BannerRequest, InterstitialRequest, RewardedRequest, NativeRequest), ad.load(request) and AdRequest.AdRequestListener are removed. Ads are loaded through the instance, the result comes to AdLoadCallback on the main thread:

Format4.0
BannerbidMachineInstance.loadBanner(placement, bannerAdSize, adLoadCallback)
InterstitialbidMachineInstance.loadInterstitial(placement, adLoadCallback)
RewardedbidMachineInstance.loadRewarded(placement, adLoadCallback)
NativebidMachineInstance.loadNative(placement, adLoadCallback)
// 3.x
InterstitialRequest request = new InterstitialRequest.Builder(
AdPlacementConfig.interstitialBuilder()
.withPlacementId("placement_id")
.withCustomParams(new CustomParams().addParam("key", "value"))
.build())
.setListener(requestListener)
.build();
InterstitialAd interstitialAd = new InterstitialAd(context);
interstitialAd.setListener(interstitialListener);
interstitialAd.load(request);
// 4.0
private var interstitialAd: InterstitialAd? = null

bidMachineInstance.loadInterstitial(
placement = Placement(
id = "placement_id",
extras = mapOf("key" to "value")
),
adLoadCallback = object : AdLoadCallback<InterstitialAd> {
override fun onAdLoaded(ad: InterstitialAd) {
interstitialAd = ad
ad.setListener(interstitialListener)
ad.show()
}

override fun onAdLoadFailed(bmError: BMError) {
// Load failed
}
}
)

// When the ad is no longer needed, e.g. when the screen is destroyed
interstitialAd?.destroy()
interstitialAd = null
  • Placement(id, extras) replaces the placement id and CustomParams of AdPlacementConfig. The placement is optional.
  • AdContentType (static / video for interstitial and rewarded) and MediaAssetType (assets of native ads) are removed together with the request builders.
  • PriceFloorParams and setPriceFloorParams are removed. Pass the price floor in the placement extras under the price_floor key, see Price floor.
  • setNetworks, setLoadingTimeOut, setSessionAdParams and BidMachine.registerNetworks are removed.
  • AdRequest.request(context) (prebid without an ad object) is removed: an ad is always loaded with its object.

Client Bidding​

setBidPayload(payload) on a request builder is replaced with the load* overloads that take the payload:

bidMachineInstance.loadInterstitial(
payload = bidPayload,
adLoadCallback = interstitialLoadCallback
)

The bid token is collected per instance and is no longer tied to an ad format:

// 3.x
BidMachine.getBidToken(context, AdPlacementConfig.interstitialBuilder().build(), token -> {
// Use the token
});
// 4.0
bidMachineInstance.collectToken(
placements = listOf(Placement("placement_id")),
bidTokenCallback = object : BidTokenCallback {
override fun onCollected(bidToken: String) {
// Use the token
}

override fun onCollectionFailed(bmError: BMError) {
// Token is not collected
}
}
)

The synchronous getBidToken is removed, collectToken is always asynchronous and reports failures to onCollectionFailed.

Win and Loss Notifications​

AdRequest.notifyMediationWin() / notifyMediationLoss(...) moved to the ad: ad.notifyWin(), ad.notifyLoss(), ad.notifyLoss(winner, price).

5. Ad Objects and Listeners​

Packages​

3.x4.0
io.bidmachine.banner.BannerViewio.bidmachine.format.bannerad.BannerView
io.bidmachine.banner.BannerListenerio.bidmachine.format.bannerad.BannerListener
io.bidmachine.interstitial.InterstitialAdio.bidmachine.format.interstitialad.InterstitialAd
io.bidmachine.interstitial.InterstitialListenerio.bidmachine.format.interstitialad.InterstitialListener
io.bidmachine.rewarded.RewardedAdio.bidmachine.format.rewardedad.RewardedAd
io.bidmachine.rewarded.RewardedListenerio.bidmachine.format.rewardedad.RewardedListener
io.bidmachine.nativead.NativeAdio.bidmachine.format.nativead.NativeAd
io.bidmachine.nativead.NativeListenerio.bidmachine.format.nativead.NativeListener
io.bidmachine.BannerAdSizeio.bidmachine.model.BannerAdSize
io.bidmachine.utils.BMErrorio.bidmachine.BMError

Ad Objects​

Ads have no public constructors: they are created by the SDK and delivered to AdLoadCallback.onAdLoaded. The common interface is io.bidmachine.Ad:

3.x (IAd)4.0 (Ad)
load(request)bidMachineInstance.load*(...)
getAuctionResult()getAuctionInfo()
setRendererConfiguration(RendererConfiguration)setExtras(Map<String, Any>)
canShow()canShow()
isLoading(), isLoaded(), isExpired(), isDestroyed()removed, use canShow()
destroy()destroy()
AdRequest.notifyMediationWin/LossnotifyWin(), notifyLoss(), notifyLoss(winner, price)

setListener no longer returns the ad, the calls can't be chained.

Listeners​

The load callbacks moved from the listeners to AdLoadCallback:

3.x AdListener4.0
onAdLoaded(ad)AdLoadCallback.onAdLoaded(ad)
onAdLoadFailed(ad, error)AdLoadCallback.onAdLoadFailed(error)
—AdListener.onAdPresented(ad) (new)
onAdShowFailed(ad, error)AdListener.onAdShowFailed(ad, error)
onAdImpression(ad)AdListener.onAdImpression(ad)
onAdClicked(ad)AdListener.onAdClicked(ad)
onAdExpired(ad)AdListener.onAdExpired(ad)
AdFullScreenListener.onAdClosed(ad, finished)FullScreenAdListener.onAdClosed(ad)
AdRewardedListener.onAdRewarded(ad)RewardedAdListener.onAdRewarded(ad)

The Simple*Listener adapter classes are removed: implement the listener interfaces directly.

6. Banner​

See Banner Ads for the full description.

BannerView is no longer created in code or declared in XML. Load it with loadBanner and add the delivered view to your layout; it's shown when it's attached and visible.

// 3.x
BannerView bannerView = findViewById(R.id.banner_view);
bannerView.setListener(bannerListener);
bannerView.load(new BannerRequest.Builder(AdPlacementConfig.bannerBuilder(BannerAdSize.Banner).build()).build());
// 4.0
bidMachineInstance.loadBanner(
bannerAdSize = BannerAdSize.Banner,
adLoadCallback = object : AdLoadCallback<BannerView> {
override fun onAdLoaded(ad: BannerView) {
ad.setListener(bannerListener)
bannerContainer.addView(ad)
}

override fun onAdLoadFailed(bmError: BMError) {
// Load failed
}
}
)
  • Add BannerView to the layout on the main thread only: added from another thread, its WebView crashes the app. AdLoadCallback is already called on the main thread.
  • BannerAdSize keeps Banner, MediumRectangle, Leaderboard and adaptive(width, maxHeight).
  • The deprecated BannerSize enum is removed.

7. Interstitial and Rewarded​

  • Load with loadInterstitial / loadRewarded and call show() on the delivered ad.
  • Keep a reference to the delivered ad for as long as it's needed and call destroy() at the end. The SDK doesn't hold the ad: an ad nothing references may be garbage collected even while it's on screen, and then the rest of its show is lost, the callbacks (onAdClicked, onAdClosed, onAdRewarded) and the tracking included.
  • onAdClosed(ad, finished) became onAdClosed(ad); the reward is reported to onAdRewarded(ad) as before.
  • AdContentType is removed: the content type is no longer chosen on the client.

8. Native​

See Native Ads for the full description.

Native ads changed most. The host app renders the ad content (texts, icon, rating) from the ad data, while the ad owns its media view, privacy (AdChoices) view and "Ad" badge, and the host only places them.

Loading​

bidMachineInstance.loadNative(
placement = Placement("placement_id"),
adLoadCallback = object : AdLoadCallback<NativeAd> {
override fun onAdLoaded(ad: NativeAd) {
ad.setListener(nativeListener)
showNativeAd(ad)
}

override fun onAdLoadFailed(bmError: BMError) {
// Load failed
}
}
)

MediaAssetType is removed: the SDK no longer validates the assets on the client and always downloads the icon and the main image the server returns.

Ad Data​

3.x4.0
getTitle(): StringgetTitle(): String?
getDescription(): StringgetBody(): String?
getCallToAction(): String ("Install" when empty)getCallToAction(): String?, no fallback value
getRating(): float (-1 when absent)getStarRating(): Double?, from 0 to 5, null when absent
—getAdvertiser(): String? (new, the "sponsored by" text)
getIcon(): ImageDatagetIcon(): ImageData?
getMainImage(): ImageDatagetMainImage(): ImageData?
hasVideo(): booleanhasVideoContent(): Boolean
getProviderView(context)removed, use getAdChoiceView()
getAdData(): NativePublicDataremoved, the getters are on NativeAd
isViewRegistered()removed

NativePublicData is replaced with NativeData. ImageData keeps getRemoteUrl(), getImage() and getLocalUri().

Views Owned by the Ad​

4.0 NativeAdPurpose
getMediaView(): ViewMedia content of the ad. Place it into your layout, its size is up to the layout; without an exact height it keeps 16:9. Replaces NativeMediaView.
getAdChoiceView(): ViewPrivacy icon, a click opens the privacy sheet. Replaces getProviderView.
getAdBadgeView(): View"Ad" badge, a click opens the advertiser link. New.

NativeMediaView is removed: don't create a media view yourself, place nativeAd.getMediaView(). Placing getAdChoiceView() and getAdBadgeView() is optional, see Binding.

Binding​

registerView(nativeAdView, iconView, nativeMediaView, clickableViews) / unregisterView() are replaced with bind / unbind:

// 3.x
nativeAd.registerView(nativeAdView, iconView, nativeMediaView, clickableViews);
...
nativeAd.unregisterView();
// 4.0
titleView.text = nativeAd.getTitle()
bodyView.text = nativeAd.getBody()
callToActionView.text = nativeAd.getCallToAction()
mediaContainer.addView(nativeAd.getMediaView())

val isBound: Boolean = nativeAd.bind(
nativeAdContainer = nativeAdView,
clickableViews = listOf(
NativeClickableView(callToActionView, NativeAssetType.CALL_TO_ACTION),
NativeClickableView(titleView, NativeAssetType.TITLE),
NativeClickableView(iconView, NativeAssetType.ICON)
)
)
...
nativeAd.unbind()
  • bind(nativeAdContainer, clickableViews = emptyList()): Boolean binds the ad to the container synchronously and returns whether it's bound. It must be called on the main thread, otherwise it returns false and reports onAdShowFailed.
  • bind doesn't fill the views anymore: set the texts, the icon and the rating yourself. In 3.x registerView filled the icon view.
  • A repeated bind is allowed: it unbinds the previous container first, the same or another one.
  • NativeClickableView(view, assetType = NativeAssetType.UNKNOWN) describes a view that opens the ad on click and the asset it shows. The view is held weakly, duplicates are ignored.
  • unbind() removes everything bind added. It is safe to call several times, without a binding, after destroy() and from any thread.
  • destroy() unbinds the ad and releases it, a separate unbind() before it isn't needed.
  • Placing getMediaView() is optional: when it isn't inside the container at bind, the impression is tracked without the media content.
  • Calling bind on an ad that isn't loaded, has expired or is destroyed returns false and reports onAdShowFailed.

Clicks​

The ad sets its own View.OnClickListener on the views passed in clickableViews: a listener set before is replaced and unbind doesn't restore it. The SDK logs a warning for a view that already has a click listener and an error for a disabled view, the views are bound anyway. Clicks are measured by the SDK and reported to onAdClicked.

Privacy View and "Ad" Badge​

If getAdChoiceView() or getAdBadgeView() is not placed inside the container when bind is called, the SDK places it over the container at the position from the server. This works when the container is a FrameLayout; for another container the SDK logs a warning and leaves the views unplaced, so place them yourself in that case.

NativeAdContentLayout​

NativeAdContentLayout is kept as an optional helper that fills the content views and binds the ad.

3.x attribute4.0 attribute
titleViewIdtitleViewId
descriptionViewIdbodyViewId
callToActionViewIdcallToActionViewId
ratingViewIdstarRatingViewId
iconViewIdiconViewId
mediaViewId (a NativeMediaView)mediaViewId (any ViewGroup, the layout puts getMediaView() into it)
providerViewIdremoved, use adChoiceViewId
ageRestrictionViewIdremoved
—advertiserViewId (new)
—adChoiceViewId (new, container for getAdChoiceView())
—adBadgeViewId (new, container for getAdBadgeView())
  • The properties are renamed the same way: descriptionView → bodyView, ratingView → starRatingView, nativeMediaView → mediaViewContainer, plus the new advertiserView, adChoiceContainer and adBadgeContainer. providerView is removed.
  • bind(nativeAd) and registerViewForInteraction(nativeAd, clickableViews) are merged into bind(nativeAd, clickableViews). It fills the views, the icon included, places getMediaView(), getAdChoiceView() and getAdBadgeView() and binds the ad with NativeAd.bind, returning its result. clickableViews defaults to all content views of the layout, the SDK sets the asset type of each one. Without adChoiceViewId / adBadgeViewId the privacy view and the badge are placed over the layout at their server positions.
  • starRatingViewId can point to a RatingBar or a TextView, the latter shows the rating as 4.5. Without a rating the view is made invisible.
  • unregisterViewForInteraction() is renamed to unbind(), isRegistered() is removed.
<io.bidmachine.format.nativead.view.NativeAdContentLayout
android:id="@+id/native_ad_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:titleViewId="@id/title"
app:bodyViewId="@id/body"
app:callToActionViewId="@id/call_to_action"
app:advertiserViewId="@id/advertiser"
app:starRatingViewId="@id/star_rating"
app:iconViewId="@id/icon"
app:mediaViewId="@id/media_container"
app:adChoiceViewId="@id/ad_choice_container"
app:adBadgeViewId="@id/ad_badge_container">
<!-- Ad content -->
</io.bidmachine.format.nativead.view.NativeAdContentLayout>
nativeAdContentLayout.bind(nativeAd)

9. Errors and Auction Data​

BMError moved to io.bidmachine.BMError and exposes code, message and errorExtension as Kotlin properties. Renamed codes:

3.x4.0
BMError.SERVERBMError.HTTP_SERVER_ERROR
BMError.EXPIREDBMError.WAS_EXPIRED
BMError.DESTROYEDBMError.WAS_DESTROYED
BMError.DUPLICATEDBMError.WAS_USED_ALREADY
BMError.HANDLED_EXCEPTIONBMError.EXCEPTION
BMError.HB_NETWORK, BMError.PLACEHOLDER_TIMEOUTremoved
—NOT_INITIALIZED, NOT_LOADED, NO_CONTAINER, NOT_VISIBLE, ADAPTER (new)

Compare errors with the code constants, not with numeric values.

AuctionResult (from getAuctionResult()) is replaced with AuctionInfo (from getAuctionInfo()):

3.x AuctionResult4.0 AuctionInfo
getId()bidId
getPrice()price
getDemandSource()demandSource
getCreativeId()creativeId
getDeal()dealId
getCid()campaignId
getNetworkKey(), getCreativeFormat()removed
—customParams (new)

10. Removed API​

3.x4.0
BidMachine.isInitialized(), InitializationCallbackremoved, see Initialization
BidMachine.setEndpoint(url)removed
BidMachine.setTargetingParams, BidMachine.setPublisher, TargetingParams, Publisher, BlockedParamsFirstPartyData
Privacy setters on BidMachineBidMachine.setConsentData(ConsentData)
BidMachine.registerNetworks(...)removed
BidMachine.getBidToken(...)bidMachineInstance.collectToken(...)
BidMachine.getExtrasParam(context, key)bidMachineInstance.getCustomParams()
BidMachine.registerAdRequestListener / unregisterAdRequestListenerremoved
BannerRequest, InterstitialRequest, RewardedRequest, NativeRequest, AdRequest.AdRequestListenerbidMachineInstance.load*(...) and AdLoadCallback
AdPlacementConfig builders, CustomParamsPlacement(id, extras)
AdContentType, MediaAssetType, AdsFormatremoved
PriceFloorParamsPlacement extra "price_floor"
SessionAdParamsremoved
BidMachineFetcherremoved
BannerSizeBannerAdSize
Simple*Listenerimplement the listener interfaces
RendererConfigurationAd.setExtras(Map<String, Any>)
NativeMediaView, NativeContainer, NativePublicDataNativeAd.getMediaView(), NativeAd.bind, NativeData

11. Mediation Adapters​

Binding a Native Ad from a Mediation Adapter​

Mediation callBidMachine 4.0
Media view of the mediated adnativeAd.getMediaView()
Options / AdChoices viewnativeAd.getAdChoiceView() (optional, otherwise placed automatically)
Prepare views for interactionnativeAd.bind(container, clickableViews), return its result
Untrack / unregister viewsnativeAd.unbind()
DestroynativeAd.destroy()
// AppLovin MAX adapter
@Override
public boolean prepareForInteraction(final List<View> clickableViews, final ViewGroup container)
{
final List<NativeClickableView> nativeClickableViews = new ArrayList<>( clickableViews.size() );
for ( final View clickableView : clickableViews )
{
nativeClickableViews.add( new NativeClickableView( clickableView ) );
}
return nativeAd.bind( container, nativeClickableViews );
}

bind must be called on the main thread. AppLovin MAX calls prepareForInteraction on the main thread unless shouldPrepareViewForInteractionOnMainThread() is overridden to return false.

Pass the advertiser and the star rating to the mediation ad when it supports them, for example MaxNativeAd.Builder.setAdvertiser(nativeAd.getAdvertiser()) and setStarRating(nativeAd.getStarRating()).