Search code examples
androidadmobinterstitial

Interstitial AdMob opens after closing


I have created an app with Interstitial AdMob, but, when it opens the ad and I close it, it reopens again and so on... What I want to do is to throw the ad after 5 launch count app. Here's my code.

    sharedPreferences = getPreferences(0);
    int count = sharedPreferences.getInt("numRun", 0);
    count++;
    sharedPreferences.edit().putInt("numRun", count).commit();

    MobileAds.initialize(this, "ADMOB_ID");
    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId(getString(R.string.INTERSTITIAL_ID));

    mInterstitialAd.loadAd(new AdRequest.Builder().build());

    mInterstitialAd.setAdListener(new AdListener(){
        @Override
        public void onAdLoaded() {
            int count = sharedPreferences.getInt("numRun", 0);

            if (count == INTERSTITIAL_LAUNCH) {
                count = 0;
                sharedPreferences.edit().putInt("numRun", count).commit();
                mInterstitialAd.show();
            }
        }
        @Override
        public void onAdClosed() {
            // Code to be executed when the interstitial ad is closed.
            mInterstitialAd.loadAd(new AdRequest.Builder().build());
        }
    });

Where INTERSTITIAL_LAUNCH is an int of 4.


Solution

  • You said that INTERSTITIAL_LAUNCH is an int of 4.

    When you check variable count against this value then according to the code if its value is greater than 4 then also the ad will be shown.

    Replace that with:

    if (count == 5)