How to add AdMob Interstitial Ads to your Android App
In this Android tutorial, you will learn How to add AdMob Interstitial Ads to your Android App. This is a Google AdMob tutorial in Android Studio that will show you how to start monetizing your apps.
Once your Android application is developed and ready to publish and you want to make some money from the application by integrating Google AdMob in it, you need to learn how to do that.
Read Previous Article: How to insert AdMob Banner Ad in your Android App
How to add AdMob Interstitial Ads to your Android App
Interstitial ads
Interstitial ads are full-screen ads that cover the interface of their host app. They’re typically displayed at natural transition points in the flow of an app, such as between activities or during the pause between levels in a game. When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.
How to add AdMob Interstitial Ads to your Android App
1. in MainActivity add this code.
private InterstitialAd mInterstitialAd;
2. Add the following code inside oncreate method.
//Interstitial Ads AdRequest adRequest1 = new AdRequest.Builder().build(); InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest1, new InterstitialAdLoadCallback() { @Override public void onAdLoaded(@NonNull InterstitialAd interstitialAd) { // The mInterstitialAd reference will be null until // an ad is loaded. mInterstitialAd = interstitialAd; Log.i(TAG, "onAdLoaded"); if (mInterstitialAd != null) { mInterstitialAd.show(MainActivity.this); } else { Log.d("TAG", "The interstitial ad wasn't ready yet."); } } @Override public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) { // Handle the error Log.i(TAG, loadAdError.getMessage()); mInterstitialAd = null; } });
3. in build.Gradle(: app) add the following dependencies.
implementation 'com.google.android.gms:play-services-ads:20.1.0'
How to add AdMob Interstitial Ads to your Android App
Here is the full code. (MainActivity.java)
package com.techedutricks.techedutricks; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.DownloadManager; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.telephony.euicc.EuiccInfo; import android.util.Log; import android.view.Gravity; import android.view.View; import android.webkit.CookieManager; import android.webkit.DownloadListener; import android.webkit.URLUtil; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.Toast; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.FullScreenContentCallback; import com.google.android.gms.ads.LoadAdError; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.OnPaidEventListener; import com.google.android.gms.ads.ResponseInfo; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import com.google.android.gms.ads.interstitial.InterstitialAd; import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback; import com.google.firebase.messaging.FirebaseMessaging; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import static android.content.ContentValues.TAG; public class MainActivity extends AppCompatActivity { private WebView myWebView; private boolean doubleTap; private final static int MY_PERMISSION_CODE = 1; private Activity mActivity; SwipeRefreshLayout swipe; private ValueCallback<Uri> mUploadMessage; public ValueCallback<Uri[]> uploadMessage; public static final int REQUEST_SELECT_FILE = 100; private final static int FILECHOOSER_RESULTCODE = 1; private InterstitialAd mInterstitialAd; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Context mContext = getApplicationContext(); mActivity = MainActivity.this; FirebaseMessaging.getInstance().setAutoInitEnabled(true); swipe = (SwipeRefreshLayout) findViewById(R.id.swipe); swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { myWebView.reload(); } }); myWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); //improve WebView Performance myWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH); myWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webSettings.setDomStorageEnabled(true); webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); webSettings.setUseWideViewPort(true); webSettings.setSavePassword(true); webSettings.setSaveFormData(true); webSettings.setEnableSmoothTransition(true); webSettings.setAllowFileAccess(true); webSettings.setAllowContentAccess(true); webSettings.setMediaPlaybackRequiresUserGesture(false); //AdMob Banner Ads MobileAds.initialize(this, initializationStatus -> { }); AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); AdRequest adRequest1 = new AdRequest.Builder().build(); InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest1, new InterstitialAdLoadCallback() { @Override public void onAdLoaded(@NonNull InterstitialAd interstitialAd) { // The mInterstitialAd reference will be null until // an ad is loaded. mInterstitialAd = interstitialAd; Log.i(TAG, "onAdLoaded"); if (mInterstitialAd != null) { mInterstitialAd.show(MainActivity.this); } else { Log.d("TAG", "The interstitial ad wasn't ready yet."); } } @Override public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) { // Handle the error Log.i(TAG, loadAdError.getMessage()); mInterstitialAd = null; } }); myWebView.setWebViewClient(new MyWebViewClient() { public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) { try { webView.stopLoading(); } catch (Exception ignored) { } if (webView.canGoBack()) { webView.goBack(); } webView.loadUrl("#"); AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle("Error"); alertDialog.setMessage("Check Your internet Connection And Try Again"); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); startActivity(getIntent()); } }); alertDialog.show(); super.onReceivedError(webView, errorCode, description, failingUrl); } public void onPageFinished(WebView view, String url) { swipe.setRefreshing(false); findViewById(R.id.webview).setVisibility(View.VISIBLE); } } ); myWebView.setWebChromeClient(new MyWebClient() { // For 3.0+ Devices (Start) // onActivityResult attached before constructor protected void openFileChooser(ValueCallback uploadMsg, String acceptType) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("/*"); startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE); } // For Lollipop 5.0+ Devices @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (uploadMessage != null) { uploadMessage.onReceiveValue(null); uploadMessage = null; } uploadMessage = filePathCallback; Intent intent = fileChooserParams.createIntent(); try { startActivityForResult(intent, REQUEST_SELECT_FILE); } catch (ActivityNotFoundException e) { uploadMessage = null; Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show(); return false; } return true; } //For Android 4.1 only protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { mUploadMessage = uploadMsg; Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("/*"); startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE); } protected void openFileChooser(ValueCallback<Uri> uploadMsg) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("/*"); startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE); } }); //Load Website myWebView.loadUrl("https://www.techedutricks.com"); swipe.setRefreshing(true); checkPermission(); myWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { DownloadDialog(url, userAgent, contentDisposition, mimetype); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } } else { DownloadDialog(url, userAgent, contentDisposition, mimetype); } } }); } private void DownloadDialog(String url, String userAgent, String contentDisposition, String mimetype) { final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Downloading...") .setMessage("Do you want to download" + ' ' + " " + filename + "" + ' ') .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); String cookie = CookieManager.getInstance().getCookie(url); request.addRequestHeader("Cookie", cookie); request.addRequestHeader("User-Agent", userAgent); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); manager.enqueue(request); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); } }) .show(); } private void checkPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { //show dialog AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setMessage("Write External Storage Permission is Required"); builder.setTitle("Please Grant Permission"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ActivityCompat.requestPermissions( mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_CODE ); } }); builder.setNegativeButton("Cancel", null); AlertDialog dialog = builder.create(); dialog.show(); } else { //request permission ActivityCompat.requestPermissions( mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_CODE ); } } } } private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals("techedutricks.com")) { //Content urls open in app return false; } else { //Open external links in external browser or apps Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } } } public class MyWebClient extends WebChromeClient { private View mCustomView; private WebChromeClient.CustomViewCallback mCustomViewCallback; protected FrameLayout mFullscreenContainer; private int mOriginalOrientation; private int mOriginalSystemUiVisibility; public MyWebClient() {} public Bitmap getDefaultVideoPoster() { if (MainActivity.this == null) { return null; } return BitmapFactory.decodeResource(MainActivity.this.getApplicationContext().getResources(), 2130837573); } public void onHideCustomView() { ((FrameLayout)MainActivity.this.getWindow().getDecorView()).removeView(this.mCustomView); this.mCustomView = null; MainActivity.this.getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility); MainActivity.this.setRequestedOrientation(this.mOriginalOrientation); this.mCustomViewCallback.onCustomViewHidden(); this.mCustomViewCallback = null; } public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback) { if (this.mCustomView != null) { onHideCustomView(); return; } this.mCustomView = paramView; this.mOriginalSystemUiVisibility = MainActivity.this.getWindow().getDecorView().getSystemUiVisibility(); this.mOriginalOrientation = MainActivity.this.getRequestedOrientation(); this.mCustomViewCallback = paramCustomViewCallback; ((FrameLayout)MainActivity.this.getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1)); MainActivity.this.getWindow().getDecorView().setSystemUiVisibility(3846); } } public void onBackPressed() { if (myWebView.canGoBack()) { myWebView.goBack(); } else if (doubleTap) { super.onBackPressed(); } else { Toast toast = Toast.makeText(this, "Press Again To Exit", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.BOTTOM, 0, 0); toast.show(); doubleTap = true; Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { doubleTap = false; } }, 2000); } } }
How to add AdMob Interstitial Ads to your Android App
This lesson (How to add AdMob Interstitial Ads to your Android App) is combined with How to insert an AdMob Banner Ad in your Android App article. So please read that article also.
All done. In this lesson, I have shown How to add AdMob Interstitial Ads to your Android App. If you have any problem related to How to add AdMob Interstitial Ads to your Android App article, please comment below. (How to add AdMob Interstitial Ads to your Android App)