Showing Interstitial Ads using counter - Android

I find this one interesting, lets say i made a count in article. In which every 5 read article there will be an interstitial ads. I made a simple example from the documentation where on click it will show the ads and that's working but not if you put it in activity, you'll need to post delay. If you just add interstitial.show(), this definitely not working. Below is the example of counting article if added to a number that we want, we'll show the ads.

/* Used sharepreference because the value needs to be everywhere */
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int counter = saved_values.getInt("count", 0);
SharedPreferences.Editor editor=saved_values.edit();

mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.ad_unit_intertitial_id));
AdRequest adRequest = new AdRequest.Builder().build();

mInterstitialAd.loadAd(adRequest);
if (counter == 5) {
	mInterstitialAd.setAdListener(new AdListener() {
	@Override
		public void onAdLoaded() {
			showInterstitial();
		}
	});
	editor.putInt("count", 0 );
} else {
	editor.putInt("count", counter + 1 );
}
editor.commit();
private void showInterstitial() {
        Random r = new Random();
        if (mInterstitialAd.isLoaded()) {
            new android.os.Handler().postDelayed(
                    new Runnable() {
                        public void run() {

                            mInterstitialAd.show();
                            AdRequest adRequest = new AdRequest.Builder().build();
                            mInterstitialAd.loadAd(adRequest);
                        }
                    },
                    r.nextInt(7000 - 5000) + 5000);
        }
    }

https://developers.google.com/admob/android/interstitial?hl=en-US

Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe