Hari
Hari

Reputation: 3

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.");
            }


        }




    });

Upvotes: 0

Views: 2215

Answers (2)

Anjana
Anjana

Reputation: 933

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.");
                }
            }
        });

Upvotes: 2

Maulik Togadiya
Maulik Togadiya

Reputation: 591

Hi Actually i have an patch for doing that,We will be Using sharedpreferences for that,

  1. First thing you have to do is before loading ads just check in sharedpreferences that is ad is already been loaded once?.if not then just load/show ads and set flag to true.

    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putBoolean("isAdsLoaded", true);
    editor.commit();
    
  2. Okay so for Now whenever this activity open it will not load ads again but to load it again when app is killed and opened again we should have to reset flag.
  3. To reset flag, In application class we will be setting this flag to false

    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putBoolean("isAdsLoaded", false);
    editor.commit();
    

Here Application class is the class which one be called every time you opened apps.I hope you know how to create it and mention in manifest file.and if you donn't please comment i will explain it in brief.

Upvotes: 0

Related Questions