Search code examples
javaandroidandroid-studioadmobinterstitial

How to show interstitial Ad only once in an activity throughout App session


(My problem is when i comeback to the same activity i dont want show again an ineterstitial Ad.I want to show interstitial Ad only once throught the app session.) currently i'm using the default interstitial Ad code given by google admob.

    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() {

            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            }
                else {
                Log.d("TAG", "The interstitial wasn't loaded yet.");
            }


        }




    });

Solution

  • Just keep a static boolean variable. Once you load the app, make sure to set the boolean variable to false. Once the ad is loaded you can set it to true. When you exit the app make sure to set it back to false(since app process may not get destroyed as soon as you exit the app)

        public static isAdLoadedOnce = false;
        ----------------------------------------------
    
        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() {
    
                    if (!isAdLoadedOnce & mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                        isAdloadedOnce = true;
                    }
                        else {
                        Log.d("TAG", "The interstitial wasn't loaded yet.");
                    }
                }
            });