Android Studio Interstitial Ads
Interstitial ads are full-screen ads that appear at natural transition points in your app, such as between activities or during the pause between levels in a game. These ads can be used to display video ads and image ads. In this tutorial, we will learn how to use interstitial ads in Android Studio.
Syntax
private InterstitialAd mInterstitialAd;
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("your_ad_unit_id");
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
Example
public class MainActivity extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("your_ad_unit_id");
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);
Button btnShowAd = (Button) findViewById(R.id.btn_show_ad);
btnShowAd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
});
}
}
Output
- When the app loads, the interstitial ad is loaded in the background.
- When the button "Show Ad" is clicked, the interstitial ad is displayed in full-screen mode.
Explanation
- First, we declare a variable
mInterstitialAd
of typeInterstitialAd
and initialize it in theonCreate
method. - We set the ad unit ID for our interstitial ad.
- Then, we create an instance of
AdRequest
and call theloadAd
method to load the ad in the background. - When the button is clicked, we check whether the ad is loaded or not by calling the
isLoaded
method. If the ad is loaded, we call theshow
method to display the ad. - If the ad is not loaded, we simply log a message to the console.
Use
Interstitial ads are a great way to monetize your mobile app and earn revenue. They are typically used to display a full-screen ad between activities or during natural pauses in gameplay.
Important Points
- You must have a valid AdMob account and an ad unit ID to use interstitial ads.
- Interstitial ads should not be displayed too frequently or at inappropriate times.
- Make sure to follow Google's policies and guidelines for displaying ads in your app.
Summary
- Interstitial ads are full-screen ads that can be used to monetize your mobile app.
- You can use the
InterstitialAd
class in Android Studio to display interstitial ads. - Interstitial ads should be used sparingly and at appropriate times to avoid user frustration.