How to create Android interstitial ads?
You cant implement AdListener anymore, I used it this way:
final InterstitialAd mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.interstitial_ad_unit_id));
AdRequest adRequestInter = new AdRequest.Builder().build();
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
mInterstitialAd.show();
}
});
mInterstitialAd.loadAd(adRequestInter);
Place your own ID in strings.xml named interstitial_ad_unit_id, or replace
getResources().getString(R.string.interstitial_ad_unit_id)
with your ID.
Unlike banners, insterstitial ads don't automatically show once their loaded. You'll have to listen for AdMob's onReceiveAd()
callback, and inside that callback, call interstital.show()
to show your interstitial.
public YourActivity extends Activity implements AdListener {
...
@Override
public void onReceiveAd(Ad ad) {
Log.d("OK", "Received ad");
if (ad == interstitial) {
interstitial.show();
}
}
}
Check out a code example here. This example will show the interstitial as soon as it is received. Alternatively, you may want to wait until a proper time to show the interstitial, such as at the end of a game level, and you could check interstitial.isReady()
to see if you can show the interstitial.
Using the last Android framework, I figured out that I need to call the load() function each time the ad is closed.
import com.google.android.gms.ads.*;
import android.os.Handler;
import android.os.Looper;
import android.app.Activity;
class MyActivity extends Activity implements AdListener {
private InterstitialAd adView; // The ad
private Handler mHandler; // Handler to display the ad on the UI thread
private Runnable displayAd; // Code to execute to perform this operation
@Override
public void onCreate(Bundle savedInstanceState) {
adView = new InterstitialAd(mContext);
adView.setAdUnitId("ca-app-pub-XXXXXXXXXX");
adView.setAdListener(this);
mHandler = new Handler(Looper.getMainLooper());
displayAd = new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (adView.isLoaded()) {
adView.show();
}
}
});
}
};
loadAd();
}
@Override
public void onAdClosed() {
loadAd(); // Need to reload the Ad when it is closed.
}
void loadAd() {
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
// Load the adView object witht he request
adView.loadAd(adRequest);
}
//Call displayInterstitial() once you are ready to display the ad.
public void displayInterstitial() {
mHandler.postDelayed(displayAd, 1);
}
}
I think this example code will help you out.
How to Add AdMob Interstitial Ads in Your Android Apps
In this example, it shows you the whole source code. And it also provides some solutions for common errors. For example, onFailedToReceiveAd error solution and no ad returned solution. You can also download the source code from there.