Here is mine MainActivity -
class MainActivity() : AppCompatActivity() {
private var btn1: Button? = null
private var mRewardedAd: RewardedAd? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn1 = findViewById<View>(R.id.button1) as Button
btn1?.setOnClickListener {
loadAd()
showAd()
if (mRewardedAd != null) {
val intent: Intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
Toast.makeText(this, " Ad completed", Toast.LENGTH_SHORT).show()
}
}
}
private fun showAd() {
if (mRewardedAd != null) {
mRewardedAd?.show(this, OnUserEarnedRewardListener() {
fun onUserEarnedReward(rewardItem: RewardItem) {
var rewardAmount = rewardItem.getAmount()
var rewardType = rewardItem.getType()
Log.d(TAG, "User earned the reward.")
Toast.makeText(this, "User earned the reward.", Toast.LENGTH_SHORT).show()
}
})
} else {
Log.d(TAG, "The rewarded ad wasn't ready yet.")
Toast.makeText(this, "The rewarded ad wasn't ready yet.", Toast.LENGTH_SHORT).show()
}
}
private fun loadAd() {
var adRequest = AdRequest.Builder().build()
RewardedAd.load(
this,
"ca-app-pub-3940256099942544/5224354917",
adRequest,
object : RewardedAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.d(TAG, adError?.message)
mRewardedAd = null
}
override fun onAdLoaded(rewardedAd: RewardedAd) {
Log.d(TAG, "Ad was loaded.")
mRewardedAd = rewardedAd
}
})
}
}
MainActivity.xml -
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="224dp"
android:backgroundTint="#9C27B0"
android:text="Button main Screen"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.589"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Reward ad is not loading everything. Sometime when I press back then ads come. No idea How it work. I want when I press button in MainActivity , then It will show rewarded ads & after it goes to next Activity. please help me on this.
I am using Android Intent to go to nextActivity. sometimes its go to nextActivity without showing Ads. rewarded ads not loading everytime. Rightnow I am checking with text ads.