Skip to content

Steps to integrate AdMob in your Android App in Kotlin

Become a developer with our complete learning paths
Become a developer with our complete learning paths

Once your Android application is developed and ready to publish and you want to make some money from the application by integrating google Ads init, you need to learn how to do that. Then this article will help you. In this article, you will learn how to integrate AdMob in an Android application. By the end of this article, you will know how to integrate 3 different ads in android application, Banners ads, Interstitial Ads, and Rewarded Video Ads.

Integrating the Google Mobile Ads SDK into an app is the first step toward displaying ads and earning revenue. Once you’ve integrated the SDK, you can choose an ad format (such as native or rewarded video) and follow the steps to implement it.

If you are interested in becoming a professional software developer, make sure to check out our courses!

Setup AdMob for your android application

Prerequisites for AdMob integration

In the below image, we have added our android app.

AdMob
Android Application is added in the AdMob Account.

The form you have selected does not exist.

Import the Mobile Ads SDK

Apps can import the Google Mobile Ads SDK with a Gradle dependency that points to Google’s Maven repository. First, make sure that google() is referenced in the allprojects section of your project-level build.gradle file.

Example project-level build.gradle

allprojects {
    repositories {
        google()
    }
}
 

Next, open the app-level build.gradle file for your app, and look for a “dependencies” section.

Example app-level build.gradle

dependencies {

    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    // This is used for material components
    implementation 'com.google.android.material:material:1.0.0'

    // AdMob dependency
    implementation 'com.google.android.gms:play-services-ads:19.3.0'
}

Add the AdMob dependency above, which instructs Gradle to pull in the latest version of the Mobile Ads SDK and additional related dependencies. Once that’s done, save the file and perform a Gradle sync.

Update your AndroidManifest.xml

Add your AdMob App ID to your app’s AndroidManifest.xml file by adding a <meta-data> tag with name com.google.android.gms.ads.APPLICATION_ID, as shown below.

You can find your App ID in the AdMob UI. For android:value insert your own AdMob App ID in quotes, as shown below.

<manifest>
    <application>
        <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
    </application>
</manifest>

Above is an example of adding the <meta-data> tag in your AndroidManifest.xml, which should be added in the application tag.

Initialize Mobile Ads SDK

Before loading ads, have your app initialize the Mobile Ads SDK by calling MobileAds.initialize() which initializes the SDK and calls back a completion listener once initialization is complete (or after a 30-second timeout). This needs to be done only once, ideally at the app launch.

Here’s an example of how to call the initialize() method in an Activity:

package ...

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.ads.MobileAds

class MainActivity : AppCompatActivity() {

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

        MobileAds.initialize(this@MainActivity)
    }
....
}

If you’re using mediation, wait until the completion handler is called before loading ads, as this will ensure that all mediation adapters are initialized.

The form you have selected does not exist.

Implement Banner Ads

Banner ads occupy a spot within an app’s layout, either at the top or bottom of the device screen. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time.

Add AdView to the layout

The first step toward displaying a banner is to place AdView in the layout for the Activity or Fragment in which you’d like to display it. The easiest way to do this is to add one to the corresponding XML layout file. Here’s an example that shows an activity’s AdViewin the activity_main.xml:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

.......
.......
 
<com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" >
    </com.google.android.gms.ads.AdView>

</androidx.constraintlayout.widget.ConstraintLayout>

Note the following required attributes:

  • ads:adSize: Set this to the ad size you’d like to use. If you don’t want to use the standard size defined by the constant, you can set a custom size instead. See the banner size section below for details.
  • ads:adUnitId: Set this to the unique identifier given to the ad unit in your app where ads are to be displayed. If you show banner ads in different activities, each would require an ad unit.

You can alternatively create AdView programmatically:

val adView = AdView(this)
adView.adSize = AdSize.BANNER
adView.adUnitId = "ca-app-pub-3940256099942544/6300978111"

Always test Banner Ads with test ads

When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

The easiest way to load test ads is to use our dedicated test ad unit ID for Android banners:

ca-app-pub-3940256099942544/6300978111

It’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.

For more information about how the Mobile Ads SDK’s test ads work, see Test Ads.

Load a Banner ad

Once the AdView is in place, the next step is to load an ad. That’s done with the loadAd() method in the AdView class. It takes an AdRequest parameter, which holds runtime information (such as targeting info) about a single ad request.

Here’s an example that shows how to load an ad in the onCreate() method of an Activity:

.....

class MainActivity : AppCompatActivity() {

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

        MobileAds.initialize(this@MainActivity)

        val adRequest = AdRequest.Builder().build()
        adView.loadAd(adRequest)
   }

.....
}

That’s it! Your app is now ready to display banner ads.

Ad events of Banner Ad

To further customize the behavior of your ad, you can hook onto a number of events in the ad’s lifecycle: loading, opening, closing, and so on. You can listen for these events through the AdListener class.

To use an AdListener with AdView, simply call the setAdListener() method:

adView.adListener = object: AdListener() {
    override fun onAdLoaded() {
        // Code to be executed when an ad finishes loading.
    }

    override fun onAdFailedToLoad(errorCode : Int) {
        // Code to be executed when an ad request fails.
    }

    override fun onAdOpened() {
        // Code to be executed when an ad opens an overlay that
        // covers the screen.
    }

    override fun onAdClicked() {
        // Code to be executed when the user clicks on an ad.
    }

    override fun onAdLeftApplication() {
        // Code to be executed when the user has left the app.
    }

    override fun onAdClosed() {
        // Code to be executed when the user is about to return
        // to the app after tapping on an ad.
    }
}

Each of the overridable methods in AdListener corresponds to an event in the lifecycle of an ad

Out of Banner Ad

.

Implement Interstitial Ads with AdMob

Interstitial ads are full-screen ads that cover the interface of their host app. They’re typically displayed at natural transition points in the flow of an app, such as between activities or during the pause between levels in a game. When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.

Create an interstitial ad object

Interstitial ads are requested and shown by InterstitialAd objects. The first step is instantiating InterstitialAd and setting its ad unit ID. This is done in the onCreate() method of an Activity:

class MainActivity : AppCompatActivity() {

    private lateinit var mInterstitialAd: InterstitialAd

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

        MobileAds.initialize(this@MainActivity)

        mInterstitialAd = InterstitialAd(this)
        mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
    }
}

A single InterstitialAd object can be used to request and display multiple interstitial ads over the course of an activity’s lifespan, so you only need to construct it once.

Always test Interstitial Ad with test ads

The easiest way to load test ads is to use our dedicated test ad unit ID for Android interstitials:

ca-app-pub-3940256099942544/1033173712

Load an Interstitial ad

To load an interstitial ad, call the InterstitialAd object’s loadAd() method. This method accepts an AdRequest object as its single parameter:

class MainActivity : AppCompatActivity() {

    private lateinit var mInterstitialAd: InterstitialAd

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

        MobileAds.initialize(this@MainActivity)

        mInterstitialAd = InterstitialAd(this)
        mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
        mInterstitialAd.loadAd(AdRequest.Builder().build())
    }
}

Show the Interstitial ad

Interstitial ads should be displayed during natural pauses in the flow of an app. To show an interstitial, use the isLoaded() method to verify that it’s done loading, then call show(). The interstitial ad example could be shown in a button’s OnClickListener like this:

btn_start.setOnClickListener {

                if (mInterstitialAd.isLoaded) {
                    mInterstitialAd.show()
                } else {
                    Log.d("TAG", "The interstitial wasn't loaded yet.")
                }
        }

Output of Intertitial Ad

Intertitial Ad will launched once you click on the start button.

Ad events of Interstitial Ad

To further customize the behavior of your ad, you can hook onto a number of events in the ad’s lifecycle: loading, opening, closing, and so on. You can listen for these events through the AdListener class.

To use an AdListener with an InterstitialAd object, simply call the setAdListener() method:

 
mInterstitialAd.adListener = object: AdListener() {
    override fun onAdLoaded() {
        // Code to be executed when an ad finishes loading.
    }

    override fun onAdFailedToLoad(errorCode: Int) {
        // Code to be executed when an ad request fails.
    }

    override fun onAdOpened() {
        // Code to be executed when the ad is displayed.
    }

    override fun onAdClicked() {
        // Code to be executed when the user clicks on an ad.
    }

    override fun onAdLeftApplication() {
        // Code to be executed when the user has left the app.
    }

    override fun onAdClosed() {
        // Code to be executed when the interstitial ad is closed.
    }
}

Each of the overridable methods in AdListener corresponds to an event in the lifecycle of an ad.

Using an AdListener to reload the Interstitial Ad

The AdListener class’s onAdClosed() method is a handy place to load a new interstitial after displaying the previous one:

class MainActivity : AppCompatActivity() {

    private lateinit var mInterstitialAd: InterstitialAd

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

        MobileAds.initialize(this@MainActivity)

        mInterstitialAd = InterstitialAd(this)
        mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
        mInterstitialAd.adListener = object : AdListener() {
        override fun onAdClosed() {
            mInterstitialAd.loadAd(AdRequest.Builder().build())
        }
      }
    }
}

That’s it! This is all about displaying interstitial ads.

The form you have selected does not exist.

Rewarded Video Ads

Rewarded video ads are full-screen video ads that users have the option of watching in full in exchange for in-app rewards.

Initialize rewarded video ads

class MainActivity : AppCompatActivity(), RewardedVideoAdListener {

    private lateinit var mRewardedVideoAd: RewardedVideoAd

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

        MobileAds.initialize(this@MainActivity)

        // Use an activity context to get the rewarded video instance.
        mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this)
        mRewardedVideoAd.rewardedVideoAdListener = this
    }
}

A RewardedVideoAd object can be retrieved using MobileAds.getRewardedVideoAdInstance().

Request rewarded video ad

class MainActivity : AppCompatActivity(), RewardedVideoAdListener {

    private lateinit var mRewardedVideoAd: RewardedVideoAd

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

        MobileAds.initialize(this@MainActivity)

        // Use an activity context to get the rewarded video instance.
        mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this)
        mRewardedVideoAd.rewardedVideoAdListener = this

       loadRewardedVideoAd()
    }

    private fun loadRewardedVideoAd() {
     mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
            AdRequest.Builder().build())
    }
}

Adhering to the singleton design of RewardedVideoAd, requests to load an ad should be made to the shared instance.

It is highly recommended that you call loadAd() as early as possible (for example, in the onCreate() method of your Activity) to allow videos to be preloaded.

Always test Rewarded Video with test ads

The easiest way to load test ads is to use our dedicated test ad unit ID for Android rewarded video:

ca-app-pub-3940256099942544/5224354917

Set up event notifications for Rewarded Video Ad

The SDK provides the RewardedVideoAdListener interface, which has methods corresponding to the events in a rewarded video ad’s lifecycle. Have your app define a class that implements this interface and pass it to setRewardedVideoAdListener prior to loading an ad.

The code example in Initialize rewarded video ads already shows how to declare that your class implements RewardedVideoAdListener and set the listener on the RewardedVideoAd object. Here is a sample implementation of the listener methods:

override fun onRewarded(reward: RewardItem) {
    Toast.makeText(this, "onRewarded! currency: ${reward.type} amount: ${reward.amount}",
            Toast.LENGTH_SHORT).show()
    // Reward the user.
}

override fun onRewardedVideoAdLeftApplication() {
    Toast.makeText(this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show()
}

override fun onRewardedVideoAdClosed() {
    Toast.makeText(this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show()
}

override fun onRewardedVideoAdFailedToLoad(errorCode: Int) {
    Toast.makeText(this, "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT).show()
}

override fun onRewardedVideoAdLoaded() {
    Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show()
}

override fun onRewardedVideoAdOpened() {
    Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show()
}

override fun onRewardedVideoStarted() {
    Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show()
}

override fun onRewardedVideoCompleted() {
    Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show()
}

Display a rewarded video ad

if (mRewardedVideoAd.isLoaded) {
    mRewardedVideoAd.show()
}

We recommend that you ensure that a rewarded video ad has finished loading before attempting to display it. The isLoaded() method indicates if the rewarded video ad request has been successfully fulfilled.

Output of RewardedVideo Ad

Using a RewardedVideoAdListener to reload a Rewarded Video ad

The RewardedVideoAdListener class’s onRewardedVideoAdClosed() method is a handy place to load a new rewarded video ad after displaying the previous one:

override fun onRewardedVideoAdClosed() {
    loadRewardedVideoAd()
}

Forward lifecycle events for Rewarded Video Ad

To forward the parent Activity’s lifecycle events to the RewardedVideoAd object, call the resume()pause(), and destroy() methods in the parent Activity’s onResume()onPause(), and onDestroy() methods respectively.

Here is an example of the Activity lifecycle event forwarding:

override fun onPause() {
    super.onPause()
    mRewardedVideoAd.pause(this)
}

override fun onResume() {
    super.onResume()
    mRewardedVideoAd.resume(this)
}

override fun onDestroy() {
    super.onDestroy()
    mRewardedVideoAd.destroy(this)
}

That’s it! This is all about displaying Rewarded Video Ads.

Useful Link for AdMob: Mobile Ads SDK (Android)

Summary after successfully using AdMob

In this article, you have learned how to integrate AdMob in the android application. Now, you know how to integrate 3 different ads in android application, Banners ads, Interstitial Ads, and Rewarded Video Ads.

The form you have selected does not exist.

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide