Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 104 ยท Shipping to Users

Ads in Android Apps: AdMob and Other Networks

Add ads to an Android app: AdMob banner, interstitial, rewarded and native formats, test IDs, consent, frequency capping, mediation and the Meta Audience Network, with runnable logic stand-ins.

Many free apps pay their bills with advertising. The ad business is a network: publishers (you) place ad slots in an app, advertisers bid to fill them, and an ad network runs the auction and pays you per view, click or completed video. For Android, the largest network is Google AdMob. Others include the Meta Audience Network, AppLovin, Unity Ads and ironSource. Each ships an SDK, and mediation lets one SDK ask several networks and take the best bid.

This lesson covers the four common formats, the AdMob setup, the rules that keep your account alive and the app-side logic around ads (when to show, how often, how to grant a reward). The ad SDKs cannot run on this site, so the Android snippets are read-only. The TryIts are plain-Kotlin stand-ins for the logic you write yourself: load states, a frequency cap and the rewarded-ad flow. Always read each network's current documentation before shipping, because SDK class names change between versions.

The four formats

Format What the user sees Typical use
Banner A strip pinned to the top or bottom of the screen Persistent, low revenue per view
Interstitial A full-screen ad shown at a natural break Between levels, after finishing a task
Rewarded A full-screen video the user chooses to watch for a reward Extra lives, hints, unlocking a feature
Native An ad drawn with your layout so it looks like content Inside feeds and lists

Others exist (app open ads, rewarded interstitials), but these four teach the model. The rule of thumb: ads that interrupt the user must happen at a natural pause, and ads the user opts into (rewarded) earn the most goodwill.

Setting up AdMob

  1. Create an AdMob account, then register your app. AdMob gives you an app ID (ca-app-pub-XXXX~YYYY) and lets you create ad units, each with its own ID (ca-app-pub-XXXX/ZZZZ).
  2. Add the SDK dependency in the module's build.gradle.kts (see Gradle for Android).
  3. Put the app ID in the manifest as metadata. The SDK crashes at start-up if it is missing.
  4. Initialize the SDK once, on a background thread, in your Application class or the first activity.
Kotlin
// read-only example: dependency, manifest and initialization
// build.gradle.kts (module)
dependencies {
    implementation("com.google.android.gms:play-services-ads:<version>")
}
XML
<!-- read-only example: AndroidManifest.xml, inside <application> -->
<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-3940256099942544~3347511713" />
Kotlin
// read-only example: initialize once
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        CoroutineScope(Dispatchers.IO).launch {
            MobileAds.initialize(this@MyApp) { /* ready to load ads */ }
        }
    }
}

Use test ads during development. Google publishes sample app and ad unit IDs for every format (for example ca-app-pub-3940256099942544~3347511713 for the app ID above). Clicking your own real ads, or even loading them in a debug build, can get your AdMob account suspended for invalid traffic. Switch to real IDs only in the release build type, for instance through buildConfigField per build type.

A banner is an AdView with a size and an ad unit ID. In XML you add it like any other view; in Compose you wrap it in AndroidView.

XML
<!-- read-only example -->
<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-3940256099942544/6300978111" />
Kotlin
// read-only example: load the banner
binding.adView.loadAd(AdRequest.Builder().build())

binding.adView.adListener = object : AdListener() {
    override fun onAdFailedToLoad(error: LoadAdError) {
        binding.adView.visibility = View.GONE       // do not leave an empty gap
    }
}

Forward the lifecycle for banners (pause(), resume(), destroy()) so the SDK stops refreshing when the screen is hidden. Prefer adaptive banners, which choose a height that fits the screen width, over fixed BANNER sizes.

Interstitial ads

An interstitial is loaded ahead of time and shown later. Loading takes a network round trip, so you never load and show in one tap. The typical pattern is: load when the screen opens, show at a pause, load the next one right after the user dismisses.

Kotlin
// read-only example: interstitial lifecycle
private var interstitial: InterstitialAd? = null

private fun loadInterstitial() {
    InterstitialAd.load(
        this, "ca-app-pub-3940256099942544/1033173712", AdRequest.Builder().build(),
        object : InterstitialAdLoadCallback() {
            override fun onAdLoaded(ad: InterstitialAd) { interstitial = ad }
            override fun onAdFailedToLoad(error: LoadAdError) { interstitial = null }
        }
    )
}

private fun showInterstitialThen(next: () -> Unit) {
    val ad = interstitial
    if (ad == null) { next(); return }                  // never block the user
    ad.fullScreenContentCallback = object : FullScreenContentCallback() {
        override fun onAdDismissedFullScreenContent() {
            interstitial = null
            loadInterstitial()                          // prepare the next one
            next()
        }
        override fun onAdFailedToShowFullScreenContent(error: AdError) { interstitial = null; next() }
    }
    ad.show(this)
}

Two design rules matter more than the API. Always continue the user's flow when no ad is ready; an ad must never make a feature fail. And do not show an interstitial on app start, on back press or in the middle of an action: this annoys users and violates policy.

Rewarded ads

A rewarded ad is a deal: the user watches a short video and gets something. The reward is granted in OnUserEarnedRewardListener, which fires only if the user watched enough, not when the ad merely closed.

Kotlin
// read-only example: show a rewarded ad and grant a hint
rewarded?.show(this) { reward ->
    // reward.amount and reward.type come from your AdMob ad-unit settings
    viewModel.addHints(reward.amount)
}

Because a client can be tampered with, valuable rewards should be confirmed by server-side verification (SSV): AdMob calls your server with a signed callback, and you grant the reward there.

Native ads

A native ad gives you the assets (headline, body, icon, media, call-to-action button) and you lay them out inside a NativeAdView. They blend into feeds, but each asset must be placed with its own registered view, the "Ad" label must remain visible and you may not alter the assets' text.

The Meta Audience Network and mediation

The Meta Audience Network (the old "Facebook Audience Network") follows the same structure as AdMob: you create a placement ID per slot (banner, interstitial, rewarded video, native), add the SDK, load a placement, and show it from a listener callback when it reports onAdLoaded. Every network repeats that pattern, which is why mediation exists: one AdView or InterstitialAd asks AdMob, and AdMob's mediation layer asks the other networks through adapters and picks the best bid. You configure networks and their placement IDs in the AdMob console, so your app code stays the same. Network availability, SDK names and policies change over time, so check the current status of each network before building on it.

  • User consent. In the EEA and the UK you must collect consent for personalized ads, typically through Google's User Messaging Platform (UMP) SDK, before requesting ads. Other regions have their own laws.
  • Children. Apps aimed at children must use child-directed settings and only certified ad networks.
  • Data safety form. Declare ad SDK data collection on Play Console (see Publishing on Google Play).
  • Placement. Never place ads where they are easy to tap by accident, never label non-ads as ads and never encourage clicks.

Logic you own: load state and frequency cap

The SDK shows the ad. You decide whether to show it. Here is a stand-in for an interstitial controller: it tracks the load state, enforces a minimum gap between ads and a per-session cap, and always lets the user continue.

Kotlin Interstitial controller with frequency cap (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the output: the ad appears at 10 s, is skipped at 30 s (too soon), shown again at 75 s, and then the session cap of two stops further ads. The real SDK enforces none of this for you.

The rewarded flow

The second stand-in models the contract that matters for rewarded ads: the reward is granted only if the user earned it, and only once per ad.

Kotlin Rewarded ad: grant only on earn (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Using real ad unit IDs while testing. Use the sample IDs.
  • Loading and showing an interstitial in the same click handler. It will not be ready yet.
  • Showing ads at launch, on back press or after every tap.
  • Forgetting to handle a failed load, so the user is blocked by a missing ad.
  • Granting a reward in onAdDismissed instead of the earned-reward callback.
  • Not forwarding lifecycle methods to banners, which keeps them refreshing in the background and drains battery.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you use Google's sample ad unit IDs while developing?

    Invalid traffic, including your own clicks on live ads, can lead to a suspended AdMob account. Test IDs show safe test ads.
  2. 2. An interstitial ad is not ready when the user finishes a level. What should the app do?

    Ads must never stop a feature from working. Continue the flow and keep loading so a later break can show an ad.
  3. 3. Where should the reward for a rewarded ad be granted?

    The earned-reward listener fires only when the user watched enough. Dismissal alone proves nothing.
  4. 4. What does mediation do?

    A mediation layer asks multiple networks and takes the best bid, so your app code uses one SDK.

Summary

  • Banner, interstitial, rewarded and native are the main ad formats; interrupting formats belong at natural pauses.
  • Register an app ID in the manifest, initialize the SDK once and use test IDs until release.
  • Interstitials and rewarded ads are loaded ahead of time, shown once and replaced.
  • Your own logic controls frequency, fallbacks and reward granting; verify valuable rewards on a server.
  • Mediation lets AdMob and other networks such as the Meta Audience Network compete for each slot.
  • Collect consent where required and declare ad SDK data in the Play Console.

Next: Continuous integration for Android.