I have an application and I am using admob banners to it. Now I want to show interstitial ad on Button click. My application have 2 activity, and I want to show interstitial ad on the second activity. Second activity has a button which goes back to first activity, and I want to show the ad after the button click. I am able to show the ad on button click but when the user closes the ad or press the back button it remain on the second activity and thats the problem I am facing.
SecondActivity Code:-
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (interstitial.isLoaded()) {
interstitial.show();
}
else{
Intent i = new Intent();
i.setClass(SecondActivity.this, FirstActivity.class);
startActivity(i);
finish();
}
}
});
}
I want when the user clicks on button the ad should be seen and when he closes the ad he should return to first activity
What you need is a AdListener
for your interstitial
that utilizes the onAdClosed()
method to identify when the user closes the ad, so you can send them back to your first activity.
Your interstitial
setup:
// Create ad request
adRequest = new AdRequest.Builder().build();
// Attempt loading ad for interstitial
interstitial.loadAd(adRequest);
// Create and set AdListener for interstitial
interstitial.setAdListener(new AdListener() {
// Listen for when user closes ad
public void onAdClosed() {
// When user closes ad end this activity (go back to first activity)
finish();
}
});
And your btn
(button) setup:
// Create and set OnClickListener for button
btn.setOnClickListener(new OnClickListener() {
// Listen for when user presses button
public void onClick(View v) {
// If a interstitial is ready, show it
if(interstitial.isLoaded()) {
interstitial.show();
}
// Otherwise end this activity (go back to first activity)
else {
finish();
}
}
});
This way if the user clicks the button it will either:
Have an ad ready and display it. Wait for user to close ad.
Activity will then be closed through onAdClosed
-method.
Not have an ad ready.
Instantly close activity through the onClick
-method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With