-2

How to show Interstitial ads every 20 seconds in Kotlin?

i used this steps to load ad after 20 seconds i want to load ad every 20 seconds in my app please help

    //ads

    // Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713")
    mAdView = findViewById(R.id.adView)
    val adRequest = AdRequest.Builder().build()
    mAdView.loadAd(adRequest)
    mInterstitialAd = InterstitialAd(this)
    mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
    mInterstitialAd.loadAd(AdRequest.Builder().build())

    val adsHandler = object : Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message?) {
            mInterstitialAd.show()
        }
    }

    fun scheduleAd(){
        adsHandler.sendEmptyMessageDelayed(0, 20)
    }
    mInterstitialAd.setAdListener(object : AdListener() {
        override fun onAdLoaded() {
            scheduleAd()
        }

        override fun onAdClosed() {
            // reschedule
            scheduleAd()
        }
    })

    fun loadAd() {
        adsHandler.post {
            mInterstitialAd.loadAd(AdRequest.Builder().build())
            adsHandler.postDelayed(refresh, 20 * 1000) //called every 20 seconds
        }
    }
    //ads over
Rcnithi
  • 1
  • 1

1 Answers1

0

You can use

private val refresh = Runnable { loadAd() }

private fun loadAd() {
        adsHandler.post {
            mInterstitialAd.loadAd(AdRequest.Builder().build())
            adsHandler.postDelayed(refresh, 20 * 1000) //called every 20 seconds
        }
}

and you can start your timer with loadAd()

diAz
  • 478
  • 4
  • 16