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 andio.bidmachine.format.*for ad formats. - Privacy settings are passed as
ConsentData, targeting and publisher data asFirstPartyData. - Native ads got a new binding API:
bind/unbind, the ad owns its media, privacy and "Ad" badge views.
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:
repositories {
mavenCentral()
}
dependencies {
implementation "io.bidmachine:ads:4.0.0"
}
- The
https://artifactory.bidmachine.io/bidmachinerepository is no longer needed for the SDK itself. Keep it only if your app uses other BidMachine artifacts that are published there. minSdkstays 21.- The
adsartifact 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 theio.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 noisInitialized(): loads and token requests made before the initialization finishes are queued and run when it completes. If the initialization fails, they fail withBMError.NotInitialized.- Calling
initializeagain 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.setTestModeandsetLoggingEnabledstay global onBidMachine.BidMachine.getExtrasParam(context, key)is replaced withbidMachineInstance.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.x | 4.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.x | 4.0 FirstPartyData |
|---|---|
TargetingParams.setUserId, setGender, setCountry, setCity, setZip, setExternalUserIds | same names |
TargetingParams.setBirthdayYear | yearOfBirth |
TargetingParams.setKeywords(String...) | keywords: List<String> |
TargetingParams.setDeviceLocation | location |
TargetingParams.setStoreUrl, setStoreCategory, setStoreSubCategories, setPaid | storeUrl, storeCategory, storeSubCategories, isPaid |
TargetingParams.addBlockedAdvertiserIABCategory | blockedCategories |
TargetingParams.addBlockedAdvertiserDomain | blockedAdvertisers |
TargetingParams.addBlockedApplication | blockedApps |
TargetingParams.setFramework | removed |
Publisher id, name, domain, categories | publisherId, 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:
| Format | 4.0 |
|---|---|
| Banner | bidMachineInstance.loadBanner(placement, bannerAdSize, adLoadCallback) |
| Interstitial | bidMachineInstance.loadInterstitial(placement, adLoadCallback) |
| Rewarded | bidMachineInstance.loadRewarded(placement, adLoadCallback) |
| Native | bidMachineInstance.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 andCustomParamsofAdPlacementConfig. The placement is optional.AdContentType(static / video for interstitial and rewarded) andMediaAssetType(assets of native ads) are removed together with the request builders.PriceFloorParamsandsetPriceFloorParamsare removed. Pass the price floor in the placement extras under theprice_floorkey, see Price floor.setNetworks,setLoadingTimeOut,setSessionAdParamsandBidMachine.registerNetworksare 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.x | 4.0 |
|---|---|
io.bidmachine.banner.BannerView | io.bidmachine.format.bannerad.BannerView |
io.bidmachine.banner.BannerListener | io.bidmachine.format.bannerad.BannerListener |
io.bidmachine.interstitial.InterstitialAd | io.bidmachine.format.interstitialad.InterstitialAd |
io.bidmachine.interstitial.InterstitialListener | io.bidmachine.format.interstitialad.InterstitialListener |
io.bidmachine.rewarded.RewardedAd | io.bidmachine.format.rewardedad.RewardedAd |
io.bidmachine.rewarded.RewardedListener | io.bidmachine.format.rewardedad.RewardedListener |
io.bidmachine.nativead.NativeAd | io.bidmachine.format.nativead.NativeAd |
io.bidmachine.nativead.NativeListener | io.bidmachine.format.nativead.NativeListener |
io.bidmachine.BannerAdSize | io.bidmachine.model.BannerAdSize |
io.bidmachine.utils.BMError | io.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/Loss | notifyWin(), 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 AdListener | 4.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
BannerViewto the layout on the main thread only: added from another thread, itsWebViewcrashes the app.AdLoadCallbackis already called on the main thread. BannerAdSizekeepsBanner,MediumRectangle,Leaderboardandadaptive(width, maxHeight).- The deprecated
BannerSizeenum is removed.
7. Interstitial and Rewarded
- Load with
loadInterstitial/loadRewardedand callshow()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)becameonAdClosed(ad); the reward is reported toonAdRewarded(ad)as before.AdContentTypeis 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.x | 4.0 |
|---|---|
getTitle(): String | getTitle(): String? |
getDescription(): String | getBody(): 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(): ImageData | getIcon(): ImageData? |
getMainImage(): ImageData | getMainImage(): ImageData? |
hasVideo(): boolean | hasVideoContent(): Boolean |
getProviderView(context) | removed, use getAdChoiceView() |
getAdData(): NativePublicData | removed, 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 NativeAd | Purpose |
|---|---|
getMediaView(): View | Media 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(): View | Privacy 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()): Booleanbinds the ad to the container synchronously and returns whether it's bound. It must be called on the main thread, otherwise it returnsfalseand reportsonAdShowFailed.binddoesn't fill the views anymore: set the texts, the icon and the rating yourself. In 3.xregisterViewfilled the icon view.- A repeated
bindis 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 everythingbindadded. It is safe to call several times, without a binding, afterdestroy()and from any thread.destroy()unbinds the ad and releases it, a separateunbind()before it isn't needed.- Placing
getMediaView()is optional: when it isn't inside the container atbind, the impression is tracked without the media content. - Calling
bindon an ad that isn't loaded, has expired or is destroyed returnsfalseand reportsonAdShowFailed.
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 attribute | 4.0 attribute |
|---|---|
titleViewId | titleViewId |
descriptionViewId | bodyViewId |
callToActionViewId | callToActionViewId |
ratingViewId | starRatingViewId |
iconViewId | iconViewId |
mediaViewId (a NativeMediaView) | mediaViewId (any ViewGroup, the layout puts getMediaView() into it) |
providerViewId | removed, use adChoiceViewId |
ageRestrictionViewId | removed |
| — | 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 newadvertiserView,adChoiceContainerandadBadgeContainer.providerViewis removed. bind(nativeAd)andregisterViewForInteraction(nativeAd, clickableViews)are merged intobind(nativeAd, clickableViews). It fills the views, the icon included, placesgetMediaView(),getAdChoiceView()andgetAdBadgeView()and binds the ad withNativeAd.bind, returning its result.clickableViewsdefaults to all content views of the layout, the SDK sets the asset type of each one. WithoutadChoiceViewId/adBadgeViewIdthe privacy view and the badge are placed over the layout at their server positions.starRatingViewIdcan point to aRatingBaror aTextView, the latter shows the rating as4.5. Without a rating the view is made invisible.unregisterViewForInteraction()is renamed tounbind(),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.x | 4.0 |
|---|---|
BMError.SERVER | BMError.HTTP_SERVER_ERROR |
BMError.EXPIRED | BMError.WAS_EXPIRED |
BMError.DESTROYED | BMError.WAS_DESTROYED |
BMError.DUPLICATED | BMError.WAS_USED_ALREADY |
BMError.HANDLED_EXCEPTION | BMError.EXCEPTION |
BMError.HB_NETWORK, BMError.PLACEHOLDER_TIMEOUT | removed |
| — | 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 AuctionResult | 4.0 AuctionInfo |
|---|---|
getId() | bidId |
getPrice() | price |
getDemandSource() | demandSource |
getCreativeId() | creativeId |
getDeal() | dealId |
getCid() | campaignId |
getNetworkKey(), getCreativeFormat() | removed |
| — | customParams (new) |
10. Removed API
| 3.x | 4.0 |
|---|---|
BidMachine.isInitialized(), InitializationCallback | removed, see Initialization |
BidMachine.setEndpoint(url) | removed |
BidMachine.setTargetingParams, BidMachine.setPublisher, TargetingParams, Publisher, BlockedParams | FirstPartyData |
Privacy setters on BidMachine | BidMachine.setConsentData(ConsentData) |
BidMachine.registerNetworks(...) | removed |
BidMachine.getBidToken(...) | bidMachineInstance.collectToken(...) |
BidMachine.getExtrasParam(context, key) | bidMachineInstance.getCustomParams() |
BidMachine.registerAdRequestListener / unregisterAdRequestListener | removed |
BannerRequest, InterstitialRequest, RewardedRequest, NativeRequest, AdRequest.AdRequestListener | bidMachineInstance.load*(...) and AdLoadCallback |
AdPlacementConfig builders, CustomParams | Placement(id, extras) |
AdContentType, MediaAssetType, AdsFormat | removed |
PriceFloorParams | Placement extra "price_floor" |
SessionAdParams | removed |
BidMachineFetcher | removed |
BannerSize | BannerAdSize |
Simple*Listener | implement the listener interfaces |
RendererConfiguration | Ad.setExtras(Map<String, Any>) |
NativeMediaView, NativeContainer, NativePublicData | NativeAd.getMediaView(), NativeAd.bind, NativeData |
11. Mediation Adapters
Binding a Native Ad from a Mediation Adapter
| Mediation call | BidMachine 4.0 |
|---|---|
| Media view of the mediated ad | nativeAd.getMediaView() |
| Options / AdChoices view | nativeAd.getAdChoiceView() (optional, otherwise placed automatically) |
| Prepare views for interaction | nativeAd.bind(container, clickableViews), return its result |
| Untrack / unregister views | nativeAd.unbind() |
| Destroy | nativeAd.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()).