按钮单击上的Admob插页式广告

时间:2018-01-09 05:58:37

标签: android-studio kotlin

我正在使用kotlin在Android工作室制作应用,我尝试在点击广告按钮时向其添加插页式广告,并使用onAdClosed()方法在广告关闭后显示第二个活动,问题是应用程序在主要活动2中有时会破碎3。 这就是我的代码的样子

private lateinit var mInterstitialAd: InterstitialAd
private lateinit var adRequest : AdRequest

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

    MobileAds.initialize(this,
            "ca-app-pub-3940256099942544~3347511713")

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


    requestNewInterstitial()
    button2.setOnClickListener{
        val intent1 = Intent(this,Main2Activity::class.java)
        startActivity(intent1)
        if (mInterstitialAd.isLoaded) {
            mInterstitialAd.show()
        } else {
        }
        mInterstitialAd.adListener = object : AdListener() {
            override fun onAdClosed() {
                requestNewInterstitial()
                //go to second activity or do something
            }
            override fun onAdLoaded() {
                requestNewInterstitial()

            }
            override fun onAdFailedToLoad(i: Int) {

                requestNewInterstitial()


            }

        }
    }
}
private fun requestNewInterstitial() {
    adRequest = AdRequest.Builder().build()
    mInterstitialAd.loadAd(adRequest)}

我希望当用户点击按钮时,应该看到广告,当他关闭广告时,他应该进入第二个活动

1 个答案:

答案 0 :(得分:0)

试试这个

class MainActivity : AppCompatActivity() {
lateinit var mInterstitialAd: InterstitialAd
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    MobileAds.initialize(this,
            "ca-app-pub-3940256099942544~3347511713")
    mInterstitialAd = InterstitialAd(this)
    mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712")
    mInterstitialAd.loadAd(AdRequest.Builder().build())
    mInterstitialAd.adListener = object : AdListener() {
        override fun onAdClicked() {
            super.onAdClicked()
        }

        override fun onAdClosed() {
            val intent = Intent(applicationContext, SecondActivity::class.java)
            startActivity(intent)
        }
    }
    btn.setOnClickListener {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show()
        } else {
            Log.d("TAG", "The interstitial wasn't loaded yet.")
        }
    }
}
}