Add the dependency in your app-level build.gradle.ktx file
dependencies {
implementation("com.google.android.gms:play-services-ads:23.3.0")
}
Add the dependency in your app-level build.gradle.ktx file
buildFeatures { viewBinding = true }
Add Dependency: Add the below code to your AndroidManifest.xml file.
Create a class name as ApplicationClass and enter below code :Â
package com.test.myapplication
import android.app.Application
import com.google.android.gms.ads.MobileAds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class ApplicationClass : Application(){
override fun onCreate() {
super.onCreate()
val backgroundScope = CoroutineScope(Dispatchers.IO)
backgroundScope.launch {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this@ApplicationClass) {}
}
}
}
Create a class name as AdManager and enter below code :Â
package com.test.myapplication
import android.app.Activity
import android.content.Context
import android.os.Build
import android.view.WindowMetrics
import android.widget.LinearLayout
import android.widget.Toast
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.LoadAdError
class AdManager(private val context: Context, private val adContainer: LinearLayout) {
private lateinit var adView: AdView
// Get the ad size with screen width.
private val adSize: AdSize
get() {
val displayMetrics = context.resources.displayMetrics
val adWidthPixels =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val windowMetrics: WindowMetrics =
(context as? Activity)?.windowManager?.currentWindowMetrics
?: return AdSize.BANNER
windowMetrics.bounds.width()
} else {
displayMetrics.widthPixels
}
val density = displayMetrics.density
val adWidth = (adWidthPixels / density).toInt()
return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(context, adWidth)
}
fun showBannerAd() {
// Create a new ad view.
val adView = AdView(context)
adView.adUnitId = "ca-app-pub-3940256099942544/9214589741"
adView.setAdSize(adSize)
this.adView = adView
// Replace ad container with new ad view.
adContainer.removeAllViews()
adContainer.addView(adView)
// Start loading the ad in the background.
val adRequest = AdRequest.Builder().build()
adView.loadAd(adRequest)
adView.adListener = object : AdListener() {
override fun onAdFailedToLoad(adError: LoadAdError) {
// Code to be executed when an ad request fails.
Toast.makeText(context, "Banner Ads Loading Failed", Toast.LENGTH_SHORT).show()
}
override fun onAdLoaded() {
// Code to be executed when an ad finishes loading.
Toast.makeText(context, "Banner Ads Loaded", Toast.LENGTH_SHORT).show()
}
}
}
}
Enter the below code in activity_main.xml :Â
Enter the below code in MainActivity.kt :Â
package com.test.myapplication
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
// Get the ad size with screen width.
private lateinit var adManager: AdManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
adManager = AdManager(this, findViewById(R.id.adContainer))
adManager.showBannerAd()
}
}
Then, you can just run your app on an android device.