anecdote is an open-source Android SDK that detects whether the user is blocking ads — without coupling itself to any particular ad network. Instead of trusting a single signal, it fuses three independent sources of evidence (HTTP reachability probes, ad SDK callbacks, and network-environment telemetry) into a weighted score, and exposes the verdict as a StateFlow<BlockState>.
The project exists because the alternatives — guessing from onAdFailedToLoad alone, or paying for a closed-source detector that ships its own ad logic — both produce too many false positives to drive UX on. anecdote aims for a calibrated, debuggable verdict that an app team actually feels comfortable wiring into a reward gate or analytics funnel.
The SDK comprises three independent layers:
Core (anecdote-core): the detection engine. Owns the Active Probe runner, the network-environment watcher, the policy/scoring config, and the StateFlow<BlockState> exposed to host code. Has zero dependency on any ad SDK.
Adapters (anecdote-adapter-admob, …): bind a specific ad SDK's failure callbacks into the detector as additional signals. Adapters are completely optional — the Core works without any of them — but a connected adapter gives the detector a much sharper view of reality than HTTP probes alone. The bundled AdMob adapter additionally decomposes mediation chains so AppLovin / Unity / ironSource fills are recorded as separate signals.
Reporters (anecdote-reporter-firebase, anecdote-reporter-logcat, …): receive state-change and per-signal events for analytics or debugging. Multiple reporters can be registered side-by-side and run independently of each other.
Six load-bearing principles anchor the SDK:
- Ad-SDK independence — the Core has no compile-time knowledge of any ad network; everything network-specific lives in an opt-in adapter module.
- Multi-signal fusion — no single failure mode (a flaky probe, one unlucky
onAdFailedToLoad) can trip a verdict by itself. - Score-based verdict with confidence — the public surface is
Unknown / NotBlocked / Suspected / Blocked, eachBlockedcarrying aConfidenceso host UX can stay quiet onLOWand act onHIGH. - False-positive defense by default — cold-start grace period, network-transition session reset, and automatic exclusion of regions where Google ads are unavailable (China, etc.) are built in.
- Consent-aware — when the host uses UMP, consent-denial-induced load failures are filtered out before they enter the score, so GDPR/CCPA flows don't get mislabeled as ad-blocking.
- Detection only, response is the host's — the SDK does not nag, gate, or modify any UI. How (and whether) to react to
Blockedis left entirely to the host app, which keeps Play Store policy risk on the host's side of the line.
Signal sources out of the box:
- Active Probe — HEAD requests against configurable ad domains (default:
pagead2.googlesyndication.com, etc.) vs. control domains (www.google.com,www.gstatic.com). The delta in failure rate, not the absolute failure rate, is what feeds the score — so subway/elevator outages don't trigger Blocked. - DNS-level evidence — each probe records why it failed (
DNS_SINKHOLE,DNS_NXDOMAIN,DNS_FAILURE,TLS_FAILURE,HTTP_UNREACHABLE). An ad domain resolving to0.0.0.0/ loopback / a LAN address while control domains resolve normally is treated as near-certain evidence. - Network environment — VPN, Private DNS, and a Private DNS server matching a known ad-blocking resolver (AdGuard, NextDNS, Control D, Mullvad…).
- Installed ad-blocker apps — checked at start and re-checked when a candidate package is installed or removed.
- AdMob adapter — wraps
AdListener,InterstitialAdLoadCallback,RewardedAdLoadCallback, classifies errors (NO_FILLvs. real network failure), and decomposes mediation chains. - CustomSignalSource — a public hook for any non-AdMob network, so a host app's existing AppLovin / Unity / ironSource callbacks can emit
emitLoadFailed/emitLoadSucceededwithout writing a full adapter.
Reporters out of the box:
LogcatBlockEventReporter—Log.d("anecdote", …)for development.FirebaseBlockEventReporter— emitsadblock_state_changedand (optionally)adblock_signalto Firebase Analytics; signal events are off-by-default-friendly so production traffic stays bounded.
Score model
Signals are split into direct evidence (did ad traffic actually get through?) and ambient signals (does the environment look like a blocker?).
| Tier | Signal | Default points |
|---|---|---|
| Direct | probe delta (ad − control failure rate) | × 80, scaled down until minAdProbeSamples (4) / minControlProbeSamples (2) are reached; 0 with no control probe |
| Direct | ad domain DNS sinkhole / NXDOMAIN (control DNS healthy) | +60 / +30 |
| Direct | avg ad load failure rate | × 60 — only NETWORK_ERROR / TIMEOUT / DNS_RESOLUTION_FAILED count as failures; NO_FILL counts as a reached attempt |
| Ambient | VPN / Private DNS / known ad-blocker DNS / installed blocker app | +10 / +15 / +60 / +50 |
- When the probe has enough samples and ad domains are reachable (failure rate ≤ 20%, no DNS block), ambient points are multiplied by
ambientDiscountWhenAdsReachable(0.2) — an installed-but-disabled blocker can't outvote ads that load. - A verdict built from ambient signals alone is capped at
Confidence.MEDIUM; a strong signal (DNS block, known DNS, installed blocker) next to direct evidence lifts confidence one step. - Final score clamped to
0..100; default thresholds40 (Suspected)/70 (Blocked). Suspected/Blockedcarry aScoreBreakdownwith every contribution, so you can see why a user was flagged.
The detector runs an evaluation loop while start() is in scope. On each tick it asks every registered SignalSource for fresh data, recomputes the score, and only emits a new BlockState when the verdict actually changes — onStateChanged is therefore inexpensive to wire up, while onSignalReceived reflects the raw firehose for hosts that want it.
Two guards reduce false positives without dampening real detections:
- Grace period (
gracePeriodMs, default 5s) — after cold start or after a network change, the detector staysUnknownuntil enough evidence has accumulated. - Per-session re-evaluation cap (
maxEvaluationsPerSession, default 3) — counts verdict changes (kind + confidence). A confirmedBlockedwithConfidence.HIGHstops re-evaluating until the network environment or policy changes; lower-confidence verdicts keep re-evaluating up to the cap.
Network transitions (VPN toggle, Private DNS on/off or server change) automatically reset the session and drop probe/load evidence gathered on the old network path, so a brief in-tunnel outage — or a blocker the user just turned off — cannot persistently flip a user to Blocked.
val detector = AdBlockDetector.Builder(applicationContext)
.addReporter(LogcatBlockEventReporter())
.build()
detector.start()
lifecycleScope.launch {
detector.state.collect { state ->
when (state) {
is BlockState.Blocked -> handleBlocked(state.confidence)
else -> Unit
}
}
}For AdMob hosts, wire the adapter into the existing ad lifecycle:
val gmaSource = GmaSignalSource(consentChecker = UmpConsentChecker(consent))
detector.registerSignalSource(gmaSource)
adView.adListener = gmaSource.adListener(delegate = myExistingListener)
InterstitialAd.load(ctx, unitId, request, gmaSource.interstitialLoadCallback())
RewardedAd.load(ctx, unitId, request, gmaSource.rewardedLoadCallback())Requirement: your app must already depend on
com.google.android.gms:play-services-ads. The adapter declares the GMA SDK ascompileOnly, so addinganecdote-adapter-admobwill not pull in (or override) any version of the ad SDK that your app is already using — this is what keeps the adapter compatible with hosts that ship their own ad stack, mediation setup, or lite/full GMA variants.
AdBlockDetector.Builder(context)
.policy {
thresholdSuspected = 40 // 0..100, default 40
thresholdBlocked = 70 // 0..100, default 70
maxEvaluationsPerSession = 3 // state transitions per session
disabledRegionMccs = setOf(460) // CN by default; add more as needed
minAdProbeSamples = 4 // probe counts at full weight from here
minControlProbeSamples = 2
}
.probe {
timeoutMs = 3_000
gracePeriodMs = 5_000
// intervalMs = 60_000 // optional shortcut for a fixed cadence
// intervalSequenceMs = listOf(...) // adaptive backoff; default ramps 5s→5min
// Defaults probe the dominant global mobile ad networks
// (AdMob/DoubleClick, Meta, Unity, AppLovin, ironSource, Pangle).
// adDomains = ProbeConfig.DEFAULT_AD_DOMAINS
// controlDomains = ProbeConfig.DEFAULT_CONTROL_DOMAINS
}
.build()DEFAULT_AD_DOMAINS covers the dominant global mobile ad networks but intentionally excludes region-specific ones to avoid probing irrelevant endpoints. Apps targeting a specific market can opt into additional packs:
.probe {
adDomains = ProbeConfig.DEFAULT_AD_DOMAINS + ProbeConfig.AdNetworkPacks.KOREA
}Currently available: KOREA (Buzzvil, TNK Factory, Adpopcorn, Kakao AdFit, Naver GFA — common in 앱테크 reward apps). Contributions for additional regions are welcome.
The built-in registry of ad-blocking DNS providers and installed ad-blocker packages can be extended at the call site — no fork needed:
AdBlockDetector.Builder(context)
.addAdBlockerDnsSuffix(".my-private-dns.example") // suffix pattern
.addAdBlockerDnsSuffix("dns.my-specific-blocker.com") // exact match
.addInstalledAdBlockerPackage("com.example.myblocker") // also list in AndroidManifest <queries>
.build()Each signal contributes to the 0..100 score via SignalWeights. Defaults are tuned conservatively; override per detector:
.policy {
weights = SignalWeights.DEFAULT.copy(
knownAdBlockerDnsBonus = 80.0, // heavier weight for Private-DNS match
installedAdBlockerBonus = 30.0, // lighter — installed ≠ active
ambientDiscountWhenAdsReachable = 0.0, // ignore ambient signals once ads load
)
}Thresholds and weights can be changed after build() — e.g. from Remote Config — without restarting the detector. Only the fields you set change; the session lock is reset and the latest evidence is re-evaluated immediately:
detector.updatePolicy {
thresholdBlocked = remoteConfig.getLong("adblock_threshold_blocked").toInt()
weights = weights.copy(installedAdBlockerBonus = 30.0)
}An invalid combination throws IllegalArgumentException and the previous policy stays in effect.
val appLovin = CustomSignalSource(networkId = "applovin")
detector.registerSignalSource(appLovin)
// in your existing AppLovin listener:
override fun onAdLoadFailed(adUnitId: String, error: MaxError) {
appLovin.emitLoadFailed(
errorType = ErrorType.NO_FILL,
rawErrorCode = error.code,
rawErrorMessage = error.message,
)
}
override fun onAdLoaded(ad: MaxAd) {
appLovin.emitLoadSucceeded()
}class MyBackendReporter(private val api: MyApi) : BlockEventReporter {
override fun onStateChanged(state: BlockState) { /* state transitions only */ }
override fun onSignalReceived(signal: AdNetworkSignal) { /* every raw signal */ }
}
AdBlockDetector.Builder(context)
.addReporter(MyBackendReporter(api))
.build()onStateChanged fires only when the verdict actually changes; onSignalReceived fires for every incoming signal and can be chatty under default probe cadence.
Every module is opt-in; nothing you don't depend on lands in the final APK.
| Situation | Modules |
|---|---|
| Detection only, no host response | anecdote-core + anecdote-reporter-logcat |
| Production analytics | anecdote-core + anecdote-reporter-firebase |
| AdMob host (with or without mediation) | add anecdote-adapter-admob |
| Non-AdMob network | use CustomSignalSource, or write a dedicated adapter |
| Custom analytics backend | implement BlockEventReporter directly |
JDK 17+ is required. On macOS:
brew install openjdk@17
export JAVA_HOME=/opt/homebrew/opt/openjdk@17Common targets:
# tests + sample APK
./gradlew assembleDebug testDebugUnitTest
# distributable AAR set
./gradlew collectAars
# → build/artifacts/anecdote-*-<version>.aaranecdote-core/— detector, probe runner, policy/scoring, network watcher, publicStateFlow<BlockState>surfaceanecdote-adapter-admob/— Google Mobile Ads bindings, mediation chain decomposition, optional UMP-based consent filteringanecdote-reporter-firebase/— Firebase Analytics reporter (adblock_state_changed,adblock_signal)anecdote-reporter-logcat/— debug reportersample/— runnable sample app, including "Fail" / "Success" buttons that drive aCustomSignalSourcefor end-to-end manual testingbuild-logic/— Gradle convention plugins, including the publishing convention
- Detection only. The SDK does not show a dialog, gate a feature, or attempt to disable the user's blocker. Any such response is the host app's call, and any Play Store policy risk lives with the host.
- Android only. iOS is out of scope; the ad ecosystem there is different enough that a port would be a separate project, not a port.
- Internal validation first. The SDK is being validated on real reward-app traffic before any decision about external promotion.
Apache-2.0.
Issues and pull requests are welcome. The public interfaces (SignalSource, BlockEventReporter) are deliberately small — new adapters and reporters should fit through them rather than expanding the Core's surface area.
