Search code examples
androidadmobinterstitial

How to load AdMob Interstitial ad only one activity?


Right now I am working on one app which is include Interstitial ad but I am facing one problem that is I want to show ad in only MainActivity after every 2 min and when I move on next activity it will be stop. for this implementation I do something like this,

prepareAd();
    ScheduledExecutorService scheduler =
            Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new Runnable() {

        public void run() {
            Log.i("hello", "world");
            runOnUiThread(new Runnable() {
                public void run() {
                    if (mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                    }
                    prepareAd();
                }
            });
        }
    }, 1, 120, TimeUnit.SECONDS);

public void  prepareAd(){
    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("ca-app-pub-xxxxxxxxxxxxxxxxx/xxxxxxxxxx");
    mInterstitialAd.loadAd(new AdRequest.Builder().build());
}

Solution

  • First create a global reference:

    boolean isActivityIsVisible = true;
    

    Then check this by overriding activity's life cycle:

    @Override
      protected void onPause() {
      super.onPause();
      isActivityIsVisible = false;
    }
    
    @Override
      protected void onResume() {
      super.onResume();
      isActivityIsVisible = true;
    }
    
    @Override
      protected void onStop() {
      super.onStop();
      isActivityIsVisible = false;
    }
    

    Check whether Activity is visible in interstitial ads call back, If visible show it.

    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdClosed() {
            prepareAd();
        }
        public void onAdLoaded(){
            if (isActivityIsVisible) { mInterstitialAd.show(); }
        }
    });
    

    Hope it helps.