问题
I use option menu button to go to second activity. When user click on that menu button interstitial Ad show after launching second activity. But I want to show interstitial Ad before launching second activity and when user click on close button of interstitial Ad, second activity should launch.
I'm using the code below to show interstitial Ad.
case R.id.button_id:
startActivity(new Intent(this, secondactivity.class ));
interstitial = new InterstitialAd(getApplicationContext());
interstitial.setAdUnitId(getString(R.string.admob_interstetial_ad));
AdRequest adRequest9 = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
interstitial.loadAd(adRequest9);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
});
return true;
回答1:
Maybe something Like this? Use the onAdClosed
function to start activity
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
@Override
public void onAdClosed() {
startActivity(new Intent(this, secondactivity.class ));
// Code to be executed when when the interstitial ad is closed.
Log.i("Ads", "onAdClosed");
}
});
Read more about this here: https://developers.google.com/admob/android/interstitial
回答2:
The answer suggested by @user8240773 is correct but there is a more efficient way of handling your problem. Here is my code:
// Has the interstitial loaded successfully?
// If it has loaded, perform these actions
if(mInterstitialAd.isLoaded()) {
// Step 1: Display the interstitial
mInterstitialAd.show();
// Step 2: Attach an AdListener
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
// Step 2.1: Load another ad
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_EMULATOR_ID)
.build();
mInterstitialAd.loadAd(adRequest);
// Step 2.2: Start the new activity
startActivity(new Intent(Activity1.this, Activity2.class));
}
});
}
// If it has not loaded due to any reason simply load the next activity
else {
startActivity(new Intent(Activity1.this, Activity2.class));
}
That way you will also do not have to worry about the ad not loading due to no internet connection or anything else. Everything would be handled by this code in the way you described your problem.
来源:https://stackoverflow.com/questions/44859920/how-to-show-interstitial-ad-before-launching-new-activity-after-click-a-button