import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
const val AD_ID = "ca-app-pub-3940256099942544/5224354917"
class MainActivity : AppCompatActivity() {
private var rewardedAd: RewardedAd? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val showAd = findViewById<Button>(R.id.showAd)
MobileAds.initialize(this){}
loadAd()
showAd.setOnClickListener {
rewardedAd?.show(this){ rewardItem ->
Toast.makeText(this, "Reward: ${rewardItem.amount}", Toast.LENGTH_SHORT).show()
}
}
}
private fun loadAd(){
val adRequest = AdRequest.Builder().build()
RewardedAd.load(this, AD_ID, adRequest, object : RewardedAdLoadCallback(){
override fun onAdFailedToLoad(p0: LoadAdError) {
super.onAdFailedToLoad(p0)
}
override fun onAdLoaded(ad: RewardedAd) {
super.onAdLoaded(ad)
Toast.makeText(this@MainActivity, "Ad Loaded", Toast.LENGTH_SHORT).show()
rewardedAd = ad
rewardedAd?.fullScreenContentCallback = adListener()
}
})
}
private fun adListener() = object : FullScreenContentCallback(){
override fun onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent()
rewardedAd = null
loadAd()
}
override fun onAdFailedToShowFullScreenContent(p0: AdError) {
super.onAdFailedToShowFullScreenContent(p0)
rewardedAd = null
loadAd()
}
}
}