View as Markdown

Android

The Ezoic Ads SDK for Android lets you display banner, rewarded, interstitial, native, outstream video, and instream video ads in native Android apps. The SDK initializes Ezoic configuration, Prebid, Google Ad Manager, and consent handling from one integration point.

Requirements

  • Android SDK 24 or higher
  • Android Gradle Plugin 8.0 or higher
  • Kotlin 2.0 or higher
  • Google Mobile Ads application ID

Installation

The current SDK version is 1.13.2. Add the Ezoic Ads SDK dependency to your app module:

dependencies {
    implementation("com.ezoic.sdk:ezoic-ads-sdk:1.13.2")
}

The SDK depends on Google Mobile Ads and Prebid Mobile. Make sure your project resolves dependencies from Google's Maven repository and Maven Central.

Initialize the SDK

Initialize the SDK from your Application class or main Activity before loading ads.

import android.app.Application
import android.util.Log
import com.ezoic.ads.sdk.core.EzoicAds
import com.ezoic.ads.sdk.core.EzoicConfiguration

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        val config = EzoicConfiguration(
            domain = "example.com",
            debugEnabled = false,
            testMode = false
        )

        EzoicAds.instance.initialize(this, config) { result ->
            result.onSuccess {
                Log.d("Ezoic", "SDK initialized")
            }.onFailure { error ->
                Log.e("Ezoic", "Initialization failed: $error")
            }
        }
    }
}

domain must match the domain configured for your site in Ezoic.

Add a Banner Ad

Create an EzoicBannerView, add it to your layout, and call loadAd() after the SDK is initialized.

import android.os.Bundle
import android.util.Log
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import com.ezoic.ads.sdk.adunits.EzoicBannerView
import com.ezoic.ads.sdk.adunits.EzoicBannerViewListener
import com.ezoic.ads.sdk.core.EzoicError

class MainActivity : AppCompatActivity(), EzoicBannerViewListener {
    private lateinit var bannerView: EzoicBannerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        bannerView = EzoicBannerView(this, 12345)
        bannerView.listener = this

        val container = findViewById<FrameLayout>(R.id.banner_container)
        container.addView(bannerView)

        bannerView.loadAd("300x250")
    }

    override fun onBannerLoaded(bannerView: EzoicBannerView) {
        Log.d("Ezoic", "Banner loaded")
    }

    override fun onBannerLoadFailed(bannerView: EzoicBannerView, error: EzoicError) {
        Log.e("Ezoic", "Banner failed: ${error.message}")
    }

    override fun onBannerSizeChanged(bannerView: EzoicBannerView, widthDp: Int, heightDp: Int) {
        Log.d("Ezoic", "Banner size: ${widthDp}x${heightDp}")
    }

    override fun onDestroy() {
        bannerView.destroy()
        super.onDestroy()
    }
}

Replace 12345 with your Ezoic ad unit identifier. The SDK fetches the Google Ad Manager ad unit, Prebid configuration, supported sizes, targeting values, and refresh interval from Ezoic servers. Give the banner container android:layout_height="wrap_content" so collapse can take effect.

Unfilled ads

When no ad fills, EzoicBannerView collapses (View.GONE) so it does not leave a blank gap. This is controlled by collapseOnNoFill (default true). isCollapsed is true while the view is collapsed. If a refresh does not fill, the previous ad stays visible. onBannerSizeChanged reports the displayed size in dp, or 0×0 when the view collapses.

You can load ads with an adaptive default size, a typed size, one size string, or a list of size strings.

bannerView.loadAd()
bannerView.loadAd(EzoicBannerSize.MediumRectangle)
bannerView.loadAd("300x250")
bannerView.loadAd(listOf("300x250", "320x50"))

Common sizes include:

  • EzoicBannerSize.Banner: 320x50
  • EzoicBannerSize.LargeBanner: 320x100
  • EzoicBannerSize.MediumRectangle: 300x250
  • EzoicBannerSize.FullBanner: 468x60
  • EzoicBannerSize.Leaderboard: 728x90
  • EzoicBannerSize.Custom(width, height): custom dimensions

Add a Rewarded Ad

Rewarded ads are full-screen ads that grant an in-app reward when the user finishes watching. They use a load-then-show lifecycle: load the ad ahead of time (for example, at the start of a level), then present it at a natural break and grant the reward when it is earned.

import com.ezoic.ads.sdk.adunits.EzoicRewardedAd
import com.ezoic.ads.sdk.adunits.EzoicRewardedAdListenerAdapter

EzoicRewardedAd.load(this, 12345) { result ->
    result.onSuccess { ad ->
        // Optional: observe lifecycle events
        ad.listener = object : EzoicRewardedAdListenerAdapter() {
            override fun onRewardedAdDismissed(rewardedAd: EzoicRewardedAd) {
                Log.d("Ezoic", "Rewarded ad closed")
            }
        }
        // Present and grant the reward when earned
        ad.show(this) { reward ->
            Log.d("Ezoic", "Earned ${reward.amount} ${reward.type}")
            grantReward(reward.amount)
        }
    }.onFailure { error ->
        Log.e("Ezoic", "Rewarded load failed: ${error.message}")
    }
}

Replace 12345 with your Ezoic ad unit identifier. Call show(activity) only after the ad has loaded; showing before the load completes (or after the ad was already shown) reports EzoicError.AdNotReady. Rewarded ads are single-use — load a new ad for each opportunity.

You can pass a reward name when you show the ad. The name appears in your reports.

ad.show(this, "extra life") { reward ->
    grantReward(reward.amount)
}

The reward type and amount come from the reward configured on the Google Ad Manager rewarded ad unit. The EzoicRewardedAdListener also reports onRewardedAdShown, onRewardedAdFailedToShow, onRewardedAdImpression, onRewardedAdClicked, and onUserEarnedReward. Java apps load with an EzoicRewardedAdLoadListener and extend EzoicRewardedAdListenerAdapter.

Add an Interstitial Ad

Interstitial ads are full-screen ads shown at natural transition points (for example, between levels or screens). Unlike rewarded ads, they grant no reward. They use the same load-then-show lifecycle: load the ad ahead of time, then present it at a natural break.

import com.ezoic.ads.sdk.adunits.EzoicInterstitialAd
import com.ezoic.ads.sdk.adunits.EzoicInterstitialAdListenerAdapter

EzoicInterstitialAd.load(this, 12345) { result ->
    result.onSuccess { ad ->
        // Optional: observe lifecycle events
        ad.listener = object : EzoicInterstitialAdListenerAdapter() {
            override fun onInterstitialAdDismissed(interstitialAd: EzoicInterstitialAd) {
                Log.d("Ezoic", "Interstitial ad closed")
            }
        }
        // Present at a natural transition point
        ad.show(this)
    }.onFailure { error ->
        Log.e("Ezoic", "Interstitial load failed: ${error.message}")
    }
}

Replace 12345 with your Ezoic ad unit identifier. Call show(activity) only after the ad has loaded; showing before the load completes (or after the ad was already shown) reports EzoicError.AdNotReady. Interstitial ads are single-use — load a new ad for each opportunity.

The EzoicInterstitialAdListener reports onInterstitialAdShown, onInterstitialAdFailedToShow, onInterstitialAdImpression, onInterstitialAdClicked, and onInterstitialAdDismissed. Java apps load with an EzoicInterstitialAdLoadListener and extend EzoicInterstitialAdListenerAdapter.

Add an Outstream Video Ad

Outstream video ads render inline in your own layout, like a banner, but with a video creative in an SDK-built player. Create an EzoicOutstreamAdView, add it to your layout, and call loadAd().

import com.ezoic.ads.sdk.adunits.EzoicOutstreamAdView
import com.ezoic.ads.sdk.adunits.EzoicOutstreamAdViewListener
import com.ezoic.ads.sdk.core.EzoicError

class MainActivity : AppCompatActivity(), EzoicOutstreamAdViewListener {
    private lateinit var outstreamAdView: EzoicOutstreamAdView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        outstreamAdView = EzoicOutstreamAdView(this, 12345)
        outstreamAdView.listener = this

        val container = findViewById<FrameLayout>(R.id.outstream_container)
        container.addView(outstreamAdView)

        outstreamAdView.loadAd()
    }

    override fun onOutstreamLoaded(adView: EzoicOutstreamAdView) {
        Log.d("Ezoic", "Outstream ad loaded")
    }

    override fun onOutstreamLoadFailed(adView: EzoicOutstreamAdView, error: EzoicError) {
        Log.e("Ezoic", "Outstream failed: ${error.message}")
    }

    override fun onDestroy() {
        outstreamAdView.destroy()
        super.onDestroy()
    }
}

Replace 12345 with your Ezoic ad unit identifier. EzoicOutstreamAdView is also XML-inflatable. Unlike EzoicBannerView, loadAd() takes no size — the SDK renders at the size configured on the server (640x360 by default). Call destroy() when the hosting Activity or Fragment is destroyed.

The EzoicOutstreamAdViewListener also reports onOutstreamImpression, onOutstreamClicked, onOutstreamOpened, onOutstreamClosed, and onOutstreamSizeChanged — all optional. EzoicOutstreamAdView collapses on no-fill the same way as EzoicBannerView (collapseOnNoFill, default true). Use a wrap_content container so the collapse takes effect.

Add an Instream Video Ad

Instream video ads play inside your own video content. Your app owns the video player and the Google IMA SDK; the Ezoic SDK's job is to build the Google Ad Manager VAST ad-tag URL you hand to IMA. There is no Ezoic view — the deliverable is a URL string. EzoicInstreamAd is a view-less, multi-use controller: unlike rewarded and interstitial ads it is not single-use, so keep the instance and call load() again for the next video.

import com.ezoic.ads.sdk.adunits.EzoicInstreamAd
import com.ezoic.ads.sdk.adunits.EzoicInstreamAdListener
import com.ezoic.ads.sdk.core.EzoicError
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory

private val instreamAd = EzoicInstreamAd(12345)

instreamAd.load(this, contentUrl = playingVideoUrl, listener = object : EzoicInstreamAdListener {
    override fun onAdTagReady(adTagUrl: String) {
        // Feed the tag to your IMA ads request.
        val request = ImaSdkFactory.getInstance().createAdsRequest()
        request.adTagUrl = adTagUrl
        adsLoader.requestAds(request)
    }

    override fun onAdFailedToLoad(error: EzoicError) {
        Log.e("Ezoic", "Instream load failed: ${error.message}")
        // Play content without a preroll.
    }
})

// In your AdErrorEvent.AdErrorListener, walk down the floor waterfall:
instreamAd.getNextAdTagUrl()?.let { nextTag ->
    val request = ImaSdkFactory.getInstance().createAdsRequest()
    request.adTagUrl = nextTag
    adsLoader.requestAds(request)
}

// In your AdEvent.AdEventListener, on AdEventType.STARTED:
instreamAd.reportImpression()

Replace 12345 with your Ezoic ad unit identifier. contentUrl (the URL of the video being played) is optional and, when supplied, is added to the ad tag for contextual targeting. The EzoicInstreamAdListener reports onAdTagReady(adTagUrl) when the tag is ready and onAdFailedToLoad(error) on no fill. On an IMA ad error, call getNextAdTagUrl() to retry the next floor in the waterfall — it returns null once the waterfall is exhausted. On the IMA STARTED event, call reportImpression() (optionally passing a revenueUsd value) to record the Ezoic impression. Unlike rewarded and interstitial ads, EzoicInstreamAd is multi-use — call destroy() only when the ad unit is no longer needed, for example when the player is torn down.

Add a Native Ad

Native ads deliver ad assets (headline, image, body text, call to action) that you render inside your own layout instead of a fixed banner or full-screen format, so the ad matches the look and feel of your content.

import com.ezoic.ads.sdk.adunits.EzoicNativeAd
import com.google.android.gms.ads.nativead.NativeAdView

private var ezoicNativeAd: EzoicNativeAd? = null

EzoicNativeAd.load(this, 12345) { result ->
    result.onSuccess { ad ->
        ezoicNativeAd = ad
        val gmaAd = ad.nativeAd ?: return@onSuccess

        // Inflate your own NativeAdView layout and populate its asset views
        val adView = layoutInflater.inflate(R.layout.native_ad_view, null) as NativeAdView
        val headline = adView.findViewById<TextView>(R.id.ad_headline)
        headline.text = gmaAd.headline
        adView.headlineView = headline
        adView.setNativeAd(gmaAd)

        adContainer.removeAllViews()
        adContainer.addView(adView)
    }.onFailure { error ->
        Log.e("Ezoic", "Native load failed: ${error.message}")
    }
}

Replace 12345 with your Ezoic ad unit identifier. The SDK returns the underlying Google Mobile Ads NativeAd on ad.nativeAd; populate a NativeAdView with your own styling and assign it with setNativeAd().

Release the ad when the hosting Activity or Fragment is destroyed:

override fun onDestroy() {
    ezoicNativeAd?.destroy()
    ezoicNativeAd = null
    super.onDestroy()
}

The EzoicNativeAdListener reports onNativeAdImpression, onNativeAdClicked, onNativeAdOpened, and onNativeAdClosed. Java apps load with an EzoicNativeAdLoadListener and can extend EzoicNativeAdListenerAdapter.

AndroidManifest.xml

Add your Google Mobile Ads application ID to AndroidManifest.xml:

In most Ezoic mobile app integrations, this app ID is provided by Ezoic and can be found in your Ezoic dashboard. Use the value assigned to your app unless your Ezoic representative gives you a different Google Mobile Ads application ID.

<manifest>
    <application>
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX" />
    </application>
</manifest>

If your app targets Android 12 or higher and uses the advertising ID, add the advertising ID permission:

<uses-permission android:name="com.google.android.gms.permission.AD_ID" />

app-ads.txt

Host an app-ads.txt file at the root of the developer website listed on your app's Play Store page (for example, https://example.com/app-ads.txt). It authorizes the buyers and exchanges that may sell your inventory; a missing or incomplete file causes most programmatic demand to be filtered out. Ezoic provides the required entries — confirm the file is published and current.

Unlike iOS, Android has no App Tracking Transparency or SKAdNetwork requirements. The advertising ID permission above is the main identifier-related step, and Google Mobile Ads merges its own required entries through the manifest automatically.

Starting with SDK 1.13.0, the SDK includes an IAB TCF 2.4 consent management platform (CMP ID 299). It only acts for users in GDPR regions; elsewhere no dialog is shown and ads load as before.

The dialog is used only when both of these are true:

  • Ezoic has enabled the consent dialog for your domain. This is a server-side setting.
  • cmpEnabled is true in EzoicConfiguration. This is the default.
If your app already runs another CMP (for example UMP or OneTrust), you must set cmpEnabled = false (Java: .cmpEnabled(false)). See Using your own CMP.

Call presentConsentIfRequired once per process from your first Activity's onCreate, right after EzoicAds.initialize. It is safe to call before initialization finishes: it waits for the init response. If that Activity is recreated or finishes while the dialog loads, the dialog opens on whichever Activity is in front (waiting up to 10 seconds for one to resume). Calling it again is harmless: you get AlreadyPresenting while a dialog is in flight and AlreadyDecided once a valid decision is stored.

You must also add a "Privacy settings" button or menu item that is always reachable and calls presentConsentSettings. TCF policy requires users to be able to reopen the dialog and withdraw consent at any time.

import com.ezoic.ads.sdk.privacy.cmp.ConsentOutcome

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    EzoicAds.instance.presentConsentIfRequired(this) { outcome ->
        when (outcome) {
            is ConsentOutcome.Decided -> Log.d("Ezoic", "User chose ${outcome.decision}")
            is ConsentOutcome.Failed -> Log.w("Ezoic", "Consent UI failed: ${outcome.error.message}")
            else -> Unit // NotRequired, AlreadyDecided, Dismissed, AlreadyPresenting
        }
    }
}

// "Privacy settings" button (required): reopen the dialog with the user's stored choices
privacyButton.setOnClickListener {
    EzoicAds.instance.presentConsentSettings(this) { outcome -> /* ... */ }
}

Java apps use the …WithListener overloads, which take a ConsentOutcomeListener:

EzoicAds.getInstance().presentConsentIfRequiredWithListener(this, outcome -> {
    if (outcome instanceof ConsentOutcome.Decided) {
        Log.d("Ezoic", "User chose " + ((ConsentOutcome.Decided) outcome).getDecision());
    }
});

privacyButton.setOnClickListener(v ->
    EzoicAds.getInstance().presentConsentSettingsWithListener(this, outcome -> { /* ... */ }));
Upgrading to 1.13.0: if you keep the default cmpEnabled = true and never call presentConsentIfRequired, ad loads for GDPR-region users will fail once Ezoic enables the consent dialog for your domain. Either add the call above or set cmpEnabled = false if you run your own CMP.

Callbacks run on the main thread. ConsentOutcome tells you what happened:

Outcome When
NotRequired GDPR doesn't apply, the built-in CMP is disabled (cmpEnabled = false or by Ezoic), another CMP owns consent, or consent is managed by the app (see Setting consent manually)
AlreadyDecided A still-valid decision is stored; no dialog shown
Decided(decision) The user chose ACCEPT_ALL, REJECT_ALL or CUSTOM; the choice is saved
Dismissed The dialog closed without a choice; ads stay gated for this session. This can happen without user action (the system finished the screen, it failed to start, or resetConsent() ran meanwhile)
AlreadyPresenting A consent dialog is already on screen, or one is being prepared with nothing on screen yet
Failed(error) The dialog couldn't be shown (for example a network error, or no Activity in front within 10 seconds). Failed(NotInitialized) means it was called before initialize, or init failed

Other consent calls:

  • presentConsentSettings always reopens the dialog in GDPR regions, even if the user already decided. It returns NotRequired outside GDPR regions, when cmpEnabled is false, when another CMP is present, or when consent is managed by the app. If the dialog can't be loaded (for example offline) and a still-valid decision is stored, it returns AlreadyDecided.
  • isConsentRequired (Boolean?) is null until the init request completes, or when the server sent no consent information. It is true whenever GDPR applies and the built-in CMP is in charge, including after the user has decided, and false otherwise.
  • resetConsent() deletes the stored decision so the dialog shows again. Ads are gated again until the user decides. Keys written by another CMP are left alone.

Decisions are written as standard IABTCF_* keys to the app's default SharedPreferences, with the Google Additional Consent string in IABTCF_AddtlConsent, so Prebid, Google Ad Manager, and other IAB-aware SDKs read them as usual. A stored decision is asked for again after the publisher's consent interval (at most 390 days), when the TCF policy version changes, or when the vendor list moves more than 2 versions ahead.

In GDPR regions, while the built-in CMP is in charge and no decision is stored, ad loads wait for the user's decision:

  • While the consent dialog is loading or on screen, ad loads wait up to 5 minutes in total per dialog, counted from presentConsentIfRequired and shared by all waiting ad loads.
  • While no dialog is in progress, the open dialog is covered by another Activity, or the app is in the background, ad loads wait up to 10 seconds.

If the wait runs out, the ad load fails with EzoicError.ConsentRequired.

If the dialog can't be shown (Failed), the SDK fails open: ads proceed with IABTCF_gdprApplies=1 and no TC string, which Google treats as limited ads and many Prebid bidders skip. An earlier TC string, if any, is cleared when the stored decision was stale. Failed(NotInitialized) writes nothing.

Using your own CMP

Set cmpEnabled = false (Kotlin) or .cmpEnabled(false) (Java Builder). The SDK then reads your CMP's IABTCF_* keys as before. The built-in CMP also stays out of the way automatically if it finds IABTCF_CmpSdkID set to another CMP's ID.

val config = EzoicConfiguration(domain = "example.com", cmpEnabled = false)

Whichever CMP writes them, the SDK automatically reads consent signals from SharedPreferences:

  • TCF v2 consent is read from IABTCF_* keys.
  • GPP consent is read from IABGPP_* keys.
  • US Privacy consent is read from the standard IAB privacy key.

You can also set consent in code. Manual consent and the built-in CMP are mutually exclusive: once setGDPRConsent is called, or when autoReadConsent is false, the built-in CMP doesn't gate ad loads, show its dialog, or write IABTCF_* keys, and resetConsent() leaves the keys alone.

The setGDPRConsent value lasts for the current process only. Call setGDPRConsent before EzoicAds.initialize on every launch, or set cmpEnabled = false. Otherwise each cold start begins with the built-in CMP in charge until your call lands, and it can gate ad loads, show its dialog, and write IABTCF_* keys. setGDPRConsent doesn't write your consent to IABTCF_* keys in SharedPreferences for Google Mobile Ads or other SDKs in the app, so your own CMP must write those keys.

EzoicAds.instance.setGDPRConsent(
    applies = true,
    consentString = "TCF_CONSENT_STRING"
)

EzoicAds.instance.setGPPConsent(
    gppString = "GPP_STRING",
    sectionIds = "7"
)

EzoicAds.instance.setSubjectToCOPPA(true)

// Then initialize
EzoicAds.instance.initialize(this, config) { result -> /* ... */ }

Pageview Tracking

Ezoic reports app traffic per screen, the way it reports a website per URL. Apps have no URLs, so the SDK gives each screen one:

https://<your domain>/<application id>/<screen label>

That URL is what per-page reporting and placement optimization key on, so the screen label is what you will see in the Ezoic dashboard.

Automatic tracking

The SDK automatically tracks a pageview for every Activity resume, Fragment resume, and view-hosted Navigation destination change after initialization. Without any code from you, the screen label defaults to the Activity or Fragment class name (or the navigation route), for example https://example.com/com.example.app/SettingsFragment.

If your app uses Compose Navigation, opt in with your NavController:

val navController = rememberNavController()
EzoicAds.instance.TrackNavigation(navController)

For WebView-heavy apps, use EzoicWebViewClient so page loads are tracked as pageviews, labeled with the page's URL path:

webView.webViewClient = EzoicWebViewClient()

Labeling screens

To name screens the way you want to see them in reporting, call trackPageview(screen) when the user lands on a screen, typically from onResume(). Available in SDK 1.12.0 and later.

override fun onResume() {
    super.onResume()
    EzoicAds.instance.trackPageview("members area")
    // reported as https://example.com/com.example.app/members-area
}
EzoicAds.getInstance().trackPageview("members/profile");
// reported as https://example.com/com.example.app/members/profile

Labels are free text. Use / for hierarchy (members/profile); spaces become -, punctuation is dropped, and case is kept. The label is also attached to every ad request on that screen, so impressions and pageviews report under the same page.

A labeled trackPageview(screen) takes precedence over the automatic pageview for the same navigation, so you can label only the screens you care about without double counting. Calling trackPageview() with no label still records a pageview under the current screen label.

Manual tracking only

If you would rather the SDK never guess, disable automatic tracking and label every screen yourself:

val config = EzoicConfiguration(
    domain = "example.com",
    autoTrackPageviews = false
)

Java Compatibility

The Android SDK is written in Kotlin, but the public API is designed for Java interoperability. Java apps can use the EzoicConfiguration.Builder, callback interfaces, Java-friendly banner size constants, and EzoicBannerViewAdapter.

Troubleshooting

SDK Not Initializing

  1. Confirm the configured domain matches your Ezoic dashboard.
  2. Confirm the app has network access.
  3. Enable debugEnabled = true and check Logcat for EzoicAds logs.

Ads Not Loading

  1. Initialize the SDK before calling loadAd().
  2. Confirm the Ezoic ad unit identifier is configured in Ezoic.
  3. Confirm the Google Mobile Ads application ID is present in AndroidManifest.xml.
  4. Check consent configuration if traffic is subject to privacy regulations.
  5. If ad loads fail with EzoicError.ConsentRequired, the built-in consent dialog is waiting for a decision. Call presentConsentIfRequired after initializing, or set cmpEnabled = false if you run your own CMP. See Built-in consent dialog.