How To Show Interstitial Ads After Every Desired Seconds In Android Studio?

interstitial ads android

In this tutorial, we will learn how we can show interstitial ads after every any number of seconds. For that, you have to follow following steps.


Step 1.

Open Gradle.build(app) and add following code in it.

compile 'com.google.android.gms:play-services-ads:11.2.0'

Step 2.

Open MainActivity.java and add following code


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

private InterstitialAd mInterstitialAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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();
} else {
Log.d("TAG"," Interstitial not loaded");
}

prepareAd();

}
});

}
}, 10, 10, TimeUnit.SECONDS);

}

public void prepareAd(){

mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
}

Replace ad unit id with your own.


Conclusion

This is how we can show interstitial ads after some seconds. Please don’t show too many ads because it can be against Admob policies. 

Gaurav singla

Founder of Techyunk.com. I write blogs about android tutorials, blogging tips, programming etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

seventeen + eleven =