Limiting the number of interstitial ads per session

Hello everyone!

I’ve recently received help here and had pleasing results; I have one last question and I should finally be good to go!
I have recently posted this on stackoverflow, but results have been stagnant.

Basically, I have an app that displays an interstitial after a certain number of actions (button clicks) on a few pages of my app. I am afraid that a user may wander around my app and have a whole bunch of interstitials smacked in their face.

So, I am trying to limit the number of interstitial ads per session.
And my plan of action is to use SharedPrerences to tell android that I do not want more than 2 interstitial ads to pop up per session (unless there are better ideas out there?)

My code is below:
The problem with the code is that when using the SharedPreferences, no interstitial ads are showing up. The logcat doesn’t tell me that my interstitials are loading or even failing to load. Almost like they are nonexistent.
However without the SharedPreferences my interstitials load perfectly.

Without the SharedPreferences, I’m telling android that I would like to have a banner ad loaded every time and that I would like to load an interstitial once every 5 times. I hope that using the SharedPreferences will make the app only deliver two interstitials to load per session for this app.

Thank you very much in advance!

package com.xxxxx.xxxxxxx;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.xxxxx.xxxxxxx.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Commonproblemsmenuclass extends Activity{

	private InterstitialAd interstitial;
	private int counter = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.commonproblemsmenu);
		
		//Prepare the Interstitial Ad
		interstitial = new InterstitialAd(Commonproblemsmenuclass.this);

		//Insert the Ad Unit ID
		interstitial.setAdUnitId("xxxxxxxxxxxxxx/xxxxxxxxxxxxxx");

		//Locate the Banner Ad in xml
		AdView adView = (AdView) this.findViewById(R.id.adView);

		//Request for Ads
		AdRequest adRequest = new AdRequest.Builder()

		//Add a test device to show Test Ads
		.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
		.addTestDevice("xxxxxxxxxxxxxx")
		.build ();

		//Load ads into Banner Ads
		adView.loadAd(adRequest);

		//Load ads into Interstitial Ads
		loadInterstitial();
		
	
		//setting up buttons
				Button cp1 = (Button) findViewById(R.id.commonproblems1);
				Button cp2 = (Button) findViewById(R.id.commonproblems2);
				Button cp3 = (Button) findViewById(R.id.commonproblems3);
				Button cp4 = (Button) findViewById(R.id.commonproblems4);
				Button cp5 = (Button) findViewById(R.id.commonproblems5);
				
				
		// On Click Listener and counters
				
				cp1.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(Commonproblemsmenuclass.this, Commonproblem1class.class));
						
						counter++;
						displayInterstitial();
						
					}
				});
				
				cp2.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(Commonproblemsmenuclass.this, Commonproblem2class.class));
						
						counter++;
						displayInterstitial();
					}
				});
				cp3.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(Commonproblemsmenuclass.this, Commonproblem3class.class));
						
						counter++;
						displayInterstitial();
					}
				});
				cp4.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(Commonproblemsmenuclass.this, Commonproblem4class.class));
						
						counter++;
						displayInterstitial();
					}
				});
				cp5.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(Commonproblemsmenuclass.this, Commonproblem5class.class));
						
						counter++;
						displayInterstitial();
					}
				});
		
	}

//SHAREDPREFERENCES INITIATED HERE

	private void displayInterstitial(){

		//sharedpreferences
		SharedPreferences sp = getSharedPreferences("preference name", MODE_PRIVATE);
		if(sp.getInt("key", 0) < 5){ // the zero is the default value if it's empty, the if statement checks if your sp integer is less than 5.
		    // and continues if it checks true, if not, skip the whole statement, that's the logic here
		   Editor ed = sp.edit(); 
		   ed.putInt("key",sp.getInt("key", 0) +1);
		   ed.commit();
		   //do ads work
		   if (interstitial.isLoaded() && counter < 5){ // that's your counter, the && checks if your first argument is true before it moves on to the 
		  //second argument.. if it checks false, all is false & checks 
		  // checks both arguments regardless of their outcome
		        interstitial.show(); 
		        loadInterstitial(); 
		   } 
		 }
		  //end shared preferences, end of if-statement, end of logic code
		} // end of method 

private void loadInterstitial()
{
AdRequest adRequest = new AdRequest.Builder().
addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("xxxxxxxxxxxxxx")
.build(); 
interstitial.loadAd(adRequest);
}

}


You increment the value in shared preferences, but you never clear it. It probably worked the first time, but now it doesn’t. You really need to either start using debug, or System.out.println.
Your code does not do what you want it to do because sp.getInt(“key”, 0) > 5.
Values in sharedpreferences are not cleaned between sessions - only if the user clicks “clear data” in Settings -> Applications, which is quite rare, unless the user thinks he could profit that way.
Also, it is problematic what do you mean by “session”. If you mean from launch to exit (no matter if the user will get back to the application just after he quit), then don’t use shared preferences, just global variable.
Anyway, I would not limit iterstitials like this unless I had the banner too…

Yep, there are. But since you’re learning, I’ll give you just the idea how to do it yourself, not the code to copy-paste.
In sharedpreferences, when you show interstitial, store the time of last shown interstitial. You can store it as a Long (use System.currentTimeMillis() ). Then, before showing the interstitial, you get this date from sharedpreferences and check how long ago it appeared.
pseudo-code (note: copy-paste on this code won’t work, you need to write it yourself):

long x = sharedpreferences.get(lastInterstitialDate);
if (x < System.currentTimeMillis() - 3 * 60 * 1000 )  //3 * 60 * 1000 milliseconds = 3 minutes. it checks if the last interstitial was shown more than 3 minutes ago
showInterstitial()
else
do not show interstitial

I think if you limit interstitials not to show up more often than once per 3 or 5 minutes, you’ll be fine. You could also create a variable that tells you how many interstitials have been shown since the launch (it will be cleared when the user kills the app and launches it again, but if I were yoI wouldn’t care). Create a static variable, lets say
public static int interval = 60 * 1000 * 3; //3 minutes
when you show interstitial, increase it by 1 minute:
interval += 60000; //it adds 60000 (1 minute) to interval
now use this variable in the condition from my pseudo-code

Thank you for the reply!

And also that ‘time’ idea is a much better idea than I had initially! What I meant previously by “session” is if the user turns off their phone and turns it back on, or if they leave the app and return to it later the “total interstitials that popped up previously” would reset to zero (which I see why that didn’t happen, I didn’t initialize a line that would zero it).

But yeah I definitely would rather pursue your time idea.

I have been fiddling around with your pseudo-code yesterday and today, but I feel like I’m climbing up a wall here. Doesn’t help that my winter break is over and I’m back in school so I have a lot less time on my hands heh…

Here is my train of thought at the moment (my sdk doesn’t like the line with the “t.getTime” part in it so I’m researching as much as I can with the available time I have at the moment…)
I’ll be editing this post as I’m researching

//SHARED PREFERNCES HERE

private void displayInterstitial(){

  SharedPreferences prefs = this.getSharedPreferences(
  	      "com.xxxx.xxxxxx", Context.MODE_PRIVATE);
  long x = t.getTime();
  System.out.println("_____fecha de pref"+x);
  if (x &lt; System.currentTimeMillis() - 3 * 60 * 1000 )
     if (interstitial.isLoaded() && counter &lt; 5){ 
          interstitial.show(); 
          loadInterstitial(); 
     } 
   }

// END SHARED PREFERENCES

I have no idea what this t.getTime is. You probably copy-pasted some code from someone who had initialised Date object before this code.
like: Date t = new Date();


private static String LAST_INTERSTITIAL_DATE_KEY = "lastInterstitialDate";
private void displayInterstitial(){

SharedPreferences prefs = this.getSharedPreferences(
"com.xxxx.xxxxxx", Context.MODE_PRIVATE);
long x = prefs.getLong(LAST_INTERSTITIAL_DATE_KEY, 0);
System.out.println("_____fecha de pref"+x);
if (x < System.currentTimeMillis() - 3 * 60 * 1000 )
if (interstitial.isLoaded() && counter < 5){ 
//here you need to put System.currentTimeMillis() in sharedPreferences under the key LAST_INTERSTITIAL_DATE_KEY
interstitial.show(); 
loadInterstitial(); 
} 
}

Thank you again for the help! It is extremely appreciated!

As for your note of putting System.currentTimeMillis() in sharedPreferences under the key:
After doing research, my best guess is what I highlighted in green; it doesn’t exactly work but am I on the right track?


private static String LAST_INTERSTITIAL_DATE_KEY = "lastInterstitialDate";
private void displayInterstitial(){

SharedPreferences prefs = this.getSharedPreferences(
"com.xxxx.xxxxxx", Context.MODE_PRIVATE);
long x = prefs.getLong(LAST_INTERSTITIAL_DATE_KEY, 0);
System.out.println("_____fecha de pref"+x);
if (x < System.currentTimeMillis() - 3 * 60 * 1000 )
if (interstitial.isLoaded() && counter < 5){ 
//here you need to put System.currentTimeMillis() in sharedPreferences under the key LAST_INTERSTITIAL_DATE_KEY
string LAST_INTERSTITIAL_DATE_KEY  = System.currentTimeMillis();
interstitial.show(); 
loadInterstitial(); 
} 
}

Quick bump, after much google searching, I’m unfortunately still at a roadblock =/

Anyone have any suggestions to not allow interstitial ads to show up within 3 minutes after an interstitial ad has already been shown somewhere in the app?
I do realize that this type of code (using sharedpreferences) must be used during every interstitial instance in the code

Well, if Eclipse says something is wrong with the code even before running it on the device, it means its wrong. In your green code, System.currentTimeMillis returns a long, and LAST_INTERSTITIAL_DATE_KEY is a string. Furthermore, you already dedicated it as String, so “string” before the field name is syntax error. Writing it with small letter is even bigger error, as it could never work.

Sharedpreferences is like a map. You can read about the maps in java. It has the key and value. In your case, the key will be LAST_INTERSTITIAL_DATE_KEY, and the value will be the date of last displayed interstitial (in milliseconds).

long x = prefs.getLong(LAST_INTERSTITIAL_DATE_KEY, 0);

Here you get a long variable from shared preferences by the key LAST_INTERSTITIAL_DATE_KEY. But if you want a variable to be there, you must put something in there. Google how to put a variable into sharedpreferences.
Yeah, in every place where you try to show interstitial, you have to do it like this. It would be best if you wrapped it in a static method, but for now I think its best to focus on making it work at all.

Sorry I’m really late on this, I had tons of work on my plate because I’m in my last semester of school =/

But thank you! I actually got it to work! The interstitial I have pops up every >3 minutes, it’s perfect!

Sometime tomorrow or Friday, I want to try implementing another interstitial and see if these interstitials will know if other interstitials have appeared already. Which, of course, should; but I want to witness it firsthand.
I’ll probably just copy/paste the whole entire java code that I used and give it a shot.

Again, thank you! It works like a charm :slight_smile: