import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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
import com.neco_desarrollo.videorewardcompose.ui.theme.VideoRewardComposeTheme
const val AD_ID = "ca-app-pub-3940256099942544/5224354917"
class MainActivity : ComponentActivity() {
private var rewardedAd: RewardedAd? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MobileAds.initialize(this)
loadAd()
setContent {
VideoRewardComposeTheme {
Box(
modifier = Modifier
.fillMaxSize()
.wrapContentHeight(align = Alignment.Bottom)
.wrapContentWidth(align = Alignment.CenterHorizontally)
){
Button(onClick = {
rewardedAd?.show(this@MainActivity){ item ->
Toast.makeText(
this@MainActivity,
"Reward: ${item.amount}",
Toast.LENGTH_SHORT
).show()
}
}) {
Text(text = "Show Ad")
}
}
}
}
}
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)
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()
}
}
}