Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Interstitial ad after x actions

I am editing the code of an existing android application (not a game). I want to show an interstitial ad after a certain number of screens or actions taken (Respecting Google guidance).

This is how I normally load my interstitial ad:

// Prepare the Interstitial Ad
interstitial = new InterstitialAd(News_Detail.this);

// Insert the Ad Unit ID
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
AdRequest adRequest = new AdRequest.Builder().build();

// Load ads into Interstitial Ads
interstitial.loadAd(adRequest);

// Prepare an Interstitial Ad Listener

interstitial.setAdListener(new AdListener() {
        public void onAdLoaded() {
            // Call displayInterstitial() function
            displayInterstitial();
        }
    }); 

 

  public void displayInterstitial() {
    // If Ads are loaded, show Interstitial else show nothing.

 new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            //Your code to show add
            if (interstitial.isLoaded()) {
                interstitial.show();
            }
        }
    }, 20000);
    }

1 Answers

Keep track of actions using an int, make a method that increments it, and checks if you should show an ad. If yes, show an ad and reset it.

private static int x = 0;

public static void incrementActions() {
    x++;
    if(x >= 5) {
        x = 0;
        displayInterstital();
    }
}

Put it in your MainActivity for example, and call it like this: MainActivity.incrementActions(). Also make your displayInterstital() method static, or give the method an Object of the class it is in.

like image 77
Lóránt Viktor Gerber Avatar answered Dec 22 '25 11:12

Lóránt Viktor Gerber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!