HOW TO ADD ADMOB AD (BANNER/INTERSTITIAL/REWARDED) IN ANDROID/Kotlin

Share Post
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Please Subscribe Youtube| Like Facebook | Follow Twitter

For Java follow this article

Introduction

In this article we will learn how to implement Admob Banner/Interstitial/Rewarded Ads in android application. Admob allows you to monetize your app by displaying ads.

Our Example

In our example we have two button which will display Interstitial and Reward video Ads respectively on button click. At the bottom of app screen we will display banner ad.

Requirements:

  1. Android Project/App in which admob ads to be implemented
  2. Admob Account

Steps

Follow below steps

1) Create or Sign-in Admob Account and add application

2) Create Ad units in Admob account

3) Integrate and code Admob ads in your app

4) Run and test your application

1) Create or Sign-in Admob Account and add application

Sign into or sign up for an AdMob account.

After creating account select Apps->ADD APP

If your app is not published select no and add new app.

If your app is published click yes and provide app url and link app.

Now after adding app next step is to create ad unit id.

2) Create Ad units in Admob account

Select Apps -> Ad units -> ADD AD UNIT

Select Banner Add and write any unit name and then click on create ad unit.

After creating ad unit copy app id and banner ad unit id in a text file (we will need this later).

Similarly create Interstitial and Rewarded Ads unit ad id’s and copy them to text file. For demo purpose enter any reward amount in reward video ad, in production enter amount according to your requirements.

3) Integrate and code Admob ads in your app

First add play-services-ads library at app level build.gradle file and sync project

implementation 'com.google.android.gms:play-services-ads:19.1.0'

In manifest file inside application tag add meta-data tag and add your own app id which was saved earlier in text file in step 2. For demo purpose we have added sample app id “ca-app-pub-3940256099942544~3347511713”.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.programtown.example">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Below is the layout file code. Inside adview tag under ads:adUnitId enter your banner ad unit id which was copied in text file during step 2.

Here we have used sample test ad unit id “ca-app-pub-3940256099942544/6300978111” for testing.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Display InterstitialAd"
        android:onClick="displayInterstitialAd"
    />
    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Display Reward Video Ad"
        android:onClick="displayRewardVideoAd"
        />
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        />
    <com.google.android.gms.ads.AdView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/adView"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        ads:adSize="BANNER"
        xmlns:ads="http://schemas.android.com/apk/res-auto">
    </com.google.android.gms.ads.AdView>

</LinearLayout>

On app start we have initialized admob sdk in initAdmobSdk() method

private fun initAdmobSdk() {
	val configuration = RequestConfiguration.Builder().build()
	MobileAds.setRequestConfiguration(configuration)
	MobileAds.initialize(applicationContext) { }
}

After sdk initialization we have requested and loaded banner ad inside adView Object from xml layout. We have also defined ad listener which will be called on different event of ad life cycle, you can define any other required behaviour here.   

private fun initBannerAdmob() {
	val adRequest = AdRequest.Builder().build()
	adView.loadAd(adRequest)
	//define any required action in listener methods
	adView.setAdListener(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.
		}
	})
}

In initInterstitialAd() method we have created InterstitialAd object, which will request and load Interstitial ad. Inside setAdUnitId() enter your Interstitial Ad unit id which was copied in step 2. Here we have used sample test id “ca-app-pub-3940256099942544/1033173712” for testing. Listener is also define to define your custom action on particular ad event. onAdClosed() we have loaded next  Interstitial Ad.

private fun initInterstitialAd() {
	interstitialAd = InterstitialAd(applicationContext)
	interstitialAd!!.adUnitId = "ca-app-pub-3940256099942544/1033173712"
	interstitialAd!!.loadAd(AdRequest.Builder().build())
	interstitialAd!!.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.
			// Load the next interstitial or you can load acc to your requirements
			interstitialAd!!.loadAd(AdRequest.Builder().build())
		}
	}
}

displayInterstitialAd() will display Interstitial ad on button click. If ad is not loaded then it will display toast message.

fun displayInterstitialAd(view: View?) {
	if (interstitialAd!!.isLoaded) {
		interstitialAd!!.show()
	} else {
		Toast.makeText(applicationContext, "Interstitial Ad Is Not Loaded Yet", Toast.LENGTH_SHORT).show()
	}
}

initRewardedAd() method will request and load reward video ad. Inside rewardedAd constructor’s 2nd argument enter your reward ad unit id which was copied during step 2. Here we have used sample reward test unit Id “ca-app-pub-3940256099942544/5224354917”. RewardedAdLoadCallback is also defined to check ad Load status.

fun loadRewardedAd(): RewardedAd {
	val rewardedAd = RewardedAd(applicationContext,
			"ca-app-pub-3940256099942544/5224354917")
	val adLoadCallback: RewardedAdLoadCallback = object : RewardedAdLoadCallback() {
		override fun onRewardedAdLoaded() {
			// Ad successfully loaded.
		}

		override fun onRewardedAdFailedToLoad(errorCode: Int) {
			// Ad failed to load.
		}
	}
	rewardedAd.loadAd(AdRequest.Builder().build(), adLoadCallback)
	return rewardedAd
}

displayRewardVideoAd() method will show reward ad on button click. Listener is also define to define your custom action on particular ad event. onRewardedAdClosed () we have loaded next  rewarded video Ad. onUserEarnedReward() method will be called when user earns the reward after successfully watching reward video ad.

fun displayRewardVideoAd(view: View?) {
	if (rewardedAd!!.isLoaded) {
		val adCallback: RewardedAdCallback = object : RewardedAdCallback() {
			override fun onRewardedAdOpened() {
				// Ad opened.
			}

			override fun onRewardedAdClosed() {
				// Ad closed.
				// Load the next reward ad or you can load acc to your requirements
				rewardedAd = loadRewardedAd()
			}

			override fun onUserEarnedReward(reward: RewardItem) {
				// User earned reward.
			}

			override fun onRewardedAdFailedToShow(errorCode: Int) {
				// Ad failed to display.
			}
		}
		rewardedAd!!.show(this, adCallback)
	} else {
		Toast.makeText(applicationContext, "Reward Ad Is Not Loaded Yet", Toast.LENGTH_SHORT).show()
	}
}

Whole Code

project level build.gradle file

buildscript {
    ext.kotlin_version = '1.4.0-rc'
    repositories {
        jcenter()
        google()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app level build.gradle file

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 28
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.programtown.example"
        minSdkVersion 17
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'com.google.android.gms:play-services-ads:19.1.0'
    implementation "androidx.core:core-ktx:+"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

}
repositories {
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    mavenCentral()
}

manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.programtown.example">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Display InterstitialAd"
        android:onClick="displayInterstitialAd"
    />
    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Display Reward Video Ad"
        android:onClick="displayRewardVideoAd"
        />
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        />
    <com.google.android.gms.ads.AdView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/adView"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        ads:adSize="BANNER"
        xmlns:ads="http://schemas.android.com/apk/res-auto">
    </com.google.android.gms.ads.AdView>

</LinearLayout>

MainActivity.kt

package com.programtown.example

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.ads.*
import com.google.android.gms.ads.rewarded.RewardItem
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdCallback
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private var interstitialAd: InterstitialAd? = null
    private var rewardedAd: RewardedAd? = null

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

        initAdmobSdk()
        initBannerAdmob()
        initInterstitialAd()
        initRewardedAd()
    }

    private fun initAdmobSdk() {
        val configuration = RequestConfiguration.Builder().build()
        MobileAds.setRequestConfiguration(configuration)
        MobileAds.initialize(applicationContext) { }
    }

    private fun initBannerAdmob() {
        val adRequest = AdRequest.Builder().build()
        adView.loadAd(adRequest)
        //define any required action in listener methods
        adView.setAdListener(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.
            }
        })
    }

    private fun initInterstitialAd() {
        interstitialAd = InterstitialAd(applicationContext)
        interstitialAd!!.adUnitId = "ca-app-pub-3940256099942544/1033173712"
        interstitialAd!!.loadAd(AdRequest.Builder().build())
        interstitialAd!!.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.
                // Load the next interstitial or you can load acc to your requirements
                interstitialAd!!.loadAd(AdRequest.Builder().build())
            }
        }
    }

    private fun initRewardedAd() {
        rewardedAd = loadRewardedAd()
    }

    fun loadRewardedAd(): RewardedAd {
        val rewardedAd = RewardedAd(applicationContext,
                "ca-app-pub-3940256099942544/5224354917")
        val adLoadCallback: RewardedAdLoadCallback = object : RewardedAdLoadCallback() {
            override fun onRewardedAdLoaded() {
                // Ad successfully loaded.
            }

            override fun onRewardedAdFailedToLoad(errorCode: Int) {
                // Ad failed to load.
            }
        }
        rewardedAd.loadAd(AdRequest.Builder().build(), adLoadCallback)
        return rewardedAd
    }

    fun displayInterstitialAd(view: View?) {
        if (interstitialAd!!.isLoaded) {
            interstitialAd!!.show()
        } else {
            Toast.makeText(applicationContext, "Interstitial Ad Is Not Loaded Yet", Toast.LENGTH_SHORT).show()
        }
    }

    fun displayRewardVideoAd(view: View?) {
        if (rewardedAd!!.isLoaded) {
            val adCallback: RewardedAdCallback = object : RewardedAdCallback() {
                override fun onRewardedAdOpened() {
                    // Ad opened.
                }

                override fun onRewardedAdClosed() {
                    // Ad closed.
                    // Load the next reward ad or you can load acc to your requirements
                    rewardedAd = loadRewardedAd()
                }

                override fun onUserEarnedReward(reward: RewardItem) {
                    // User earned reward.
                }

                override fun onRewardedAdFailedToShow(errorCode: Int) {
                    // Ad failed to display.
                }
            }
            rewardedAd!!.show(this, adCallback)
        } else {
            Toast.makeText(applicationContext, "Reward Ad Is Not Loaded Yet", Toast.LENGTH_SHORT).show()
        }
    }
}

4) Run and test your application

Make sure you are connected to internet and then run app. If you have used real ad unit id then it will take some time to display ad on your app. However it is recommended to use test ad unit id during development to see test ad quickly and to prevent accidental click. Replace test ad unit id with real ad unit id during production.  

After Running app at the bottom banner ad will be shown.

On Display InterstitialAd button click will show Interstitial Ad

On Display Reward Video Ad button click will show Reward Ad

Conclusion

In this post we have learned how to implement Admob ads in android application.

Please Subscribe Youtube| Like Facebook | Follow Twitter


Share Post
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Leave a Reply

Your email address will not be published. Required fields are marked *