Admob interstitial code example

0 18
Avatar for jesusboyg
3 years ago

import android.widget.TextView;

import android.widget.Toast;

import com.google.android.gms.ads.AdListener;

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

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

import com.google.android.gms.ads.MobileAds;

import com.google.android.gms.ads.initialization.InitializationStatus;

import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

/**

* Main Activity. Inflates main activity xml.

*/

public class MyActivity extends AppCompatActivity {

private static final long GAME_LENGTH_MILLISECONDS = 3000;

private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712";

private InterstitialAd interstitialAd;

private CountDownTimer countDownTimer;

private Button retryButton;

private boolean gameIsInProgress;

private long timerMilliseconds;

Google AdMob

AdMob

Home

Products

Google AdMob

Mobile Ads SDK (Android)

Send feedback

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. Case study.

This guide explains how to integrate interstitial ads into an Android app.

Prerequisite

Import the Google Mobile Ads SDK, either by itself or as part of Firebase.

Create an interstitial ad object

Interstitial ads are requested and shown by InterstitialAd objects. The first step is instantiating InterstitialAd and setting its ad unit ID. This is done in the onCreate() method of an Activity:

Java

Kotlin

package ...

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

public class MainActivity extends Activity {

private InterstitialAd mInterstitialAd;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

MobileAds.initialize(this, new OnInitializationCompleteListener() {

@Override

public void onInitializationComplete(InitializationStatus initializationStatus) {}

});

mInterstitialAd = new InterstitialAd(this);

mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");

}

}

A single InterstitialAd object can be used to request and display multiple interstitial ads over the course of an activity's lifespan, so you only need to construct it once.

Always test with test ads

When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

The easiest way to load test ads is to use our dedicated test ad unit ID for Android interstitials:

ca-app-pub-3940256099942544/1033173712

It's been specially configured to return test ads for every request, and you're free to use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.

For more information about how the Mobile Ads SDK's test ads work, see Test Ads.

Load an ad

Note: Make all calls to the Mobile Ads SDK on the main thread.

To load an interstitial ad, call the InterstitialAd object's loadAd() method. This method accepts an AdRequest object as its single parameter:

Java

Kotlin

package ...

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

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

public class MainActivity extends Activity {

private InterstitialAd mInterstitialAd;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

MobileAds.initialize(this,

"ca-app-pub-3940256099942544~3347511713");

mInterstitialAd = new InterstitialAd(this);

mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");

mInterstitialAd.loadAd(new AdRequest.Builder().build());

}

}

Show the ad

Interstitial ads should be displayed during natural pauses in the flow of an app. Between levels of a game is a good example, or after the user completes a task. To show an interstitial, use the isLoaded() method to verify that it's done loading, then call show(). The interstitial ad from the previous code example could be shown in a button's OnClickListener like this:

Java

Kotlin

mMyButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (mInterstitialAd.isLoaded()) {

mInterstitialAd.show();

} else {

Log.d("TAG", "The interstitial wasn't loaded yet.");

}

}

});

Ad events

To further customize the behavior of your ad, you can hook onto a number of events in the ad's lifecycle: loading, opening, closing, and so on. You can listen for these events through the AdListener class.

To use an AdListener with an InterstitialAd object, simply call the setAdListener() method:

Java

Kotlin

mInterstitialAd.setAdListener(new AdListener() {

@Override

public void onAdLoaded() {

// Code to be executed when an ad finishes loading.

}

@Override

public void onAdFailedToLoad(int errorCode) {

// Code to be executed when an ad request fails.

}

@Override

public void onAdOpened() {

// Code to be executed when the ad is displayed.

}

@Override

public void onAdClicked() {

// Code to be executed when the user clicks on an ad.

}

@Override

public void onAdLeftApplication() {

// Code to be executed when the user has left the app.

}

@Override

public void onAdClosed() {

// Code to be executed when the interstitial ad is closed.

}

});

Each of the overridable methods in AdListener corresponds to an event in the lifecycle of an ad.

Overridable methods

onAdLoaded() The onAdLoaded() method is executed when an ad has finished loading.

onAdFailedToLoad() The onAdFailedToLoad() method includes an errorCode parameter that indicates what type of failure occurred. The possible values are defined as constants in the AdRequest class:

ERROR_CODE_INTERNAL_ERROR - Something happened internally; for instance, an invalid response was received from the ad server.

ERROR_CODE_INVALID_REQUEST - The ad request was invalid; for instance, the ad unit ID was incorrect.

ERROR_CODE_NETWORK_ERROR - The ad request was unsuccessful due to network connectivity.

ERROR_CODE_NO_FILL - The ad request was successful, but no ad was returned due to lack of ad inventory.

onAdOpened() This method is invoked when the ad is displayed, covering the device's screen.

onAdLeftApplication() This method is invoked when a user click opens another app (such as the Google Play), backgrounding the current app.

onAdClosed() This method is invoked when the interstitial ad is closed due to the user tapping on the close icon or using the back button. If your app paused its audio output or game loop, this is a great place to resume it.

Warning: Attempting to load a new ad from the onAdFailedToLoad() method is strongly discouraged. If you must load an ad from onAdFailedToLoad(), limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.

Using an AdListener to reload

The AdListener class's onAdClosed() method is a handy place to load a new interstitial after displaying the previous one:

Java

Kotlin

...

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

MobileAds.initialize(this,

"ca-app-pub-3940256099942544~3347511713");

mInterstitialAd = new InterstitialAd(this);

mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");

mInterstitialAd.loadAd(new AdRequest.Builder().build());

mInterstitialAd.setAdListener(new AdListener() {

@Override

public void onAdClosed() {

// Load the next interstitial.

mInterstitialAd.loadAd(new AdRequest.Builder().build());

}

});

}

...

Some best practices

Consider whether interstitial ads are the right type of ad for your app.

Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.

Remember to pause the action when displaying an interstitial ad.

There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app. You can resume playing sounds in the onAdClosed() event handler, which will be invoked when the user has finished interacting with the ad. In addition, consider temporarily halting any intense computation tasks (such as a game loop) while the ad is being displayed. This will make sure the user doesn't experience slow or unresponsive graphics or stuttered video.

Allow for adequate loading time.

Just as it's important to make sure you display interstitial ads at an appropriate time, it's also important to make sure the user doesn't have to wait for them to load. Loading the ad in advance by calling loadAd() before you intend to call show() can ensure that your app has a fully loaded interstitial ad at the ready when the time comes to display one.

Don't flood the user with ads.

While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.

Source code

MyActivity.java

/*

* Copyright (C) 2013 Google, Inc.

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

package com.google.android.gms.example.interstitialexample;

import android.os.Bundle;

import android.os.CountDownTimer;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;

import com.google.android.gms.ads.AdListener;

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

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

import com.google.android.gms.ads.MobileAds;

import com.google.android.gms.ads.initialization.InitializationStatus;

import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

/**

* Main Activity. Inflates main activity xml.

*/

public class MyActivity extends AppCompatActivity {

private static final long GAME_LENGTH_MILLISECONDS = 3000;

private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712";

private InterstitialAd interstitialAd;

private CountDownTimer countDownTimer;

private Button retryButton;

private boolean gameIsInProgress;

private long timerMilliseconds;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_my);

// Initialize the Mobile Ads SDK.

MobileAds.initialize(this, new OnInitializationCompleteListener() {

@Override

public void onInitializationComplete(InitializationStatus initializationStatus) {}

});

// Create the InterstitialAd and set the adUnitId.

interstitialAd = new InterstitialAd(this);

// Defined in res/values/strings.xml

interstitialAd.setAdUnitId(AD_UNIT_ID);

interstitialAd.setAdListener(new AdListener() {

@Override

public void onAdLoaded() {

Toast.makeText(MyActivity.this, "onAdLoaded()", Toast.LENGTH_SHORT).show();

}

@Override

public void onAdFailedToLoad(int errorCode) {

Toast.makeText(MyActivity.this,

"onAdFailedToLoad() with error code: " + errorCode,

Toast.LENGTH_SHORT).show();

}

@Override

public void onAdClosed() {

startGame();

}

});

@Override

public void onTick(long millisUnitFinished) {

timerMilliseconds = millisUnitFinished;

textView.setText("seconds remaining: " + ((millisUnitFinished / 1000) + 1));

}

@Override

public void onFinish() {

gameIsInProgress = false;

textView.setText("done!");

retryButton.setVisibility(View.VISIBLE);

}

};

}

@Override

public void onResume() {

// Start or resume the game.

super.onResume();

if (gameIsInProgress) {

resumeGame(timerMilliseconds);

}

}

Google AdMob

AdMob

Home

Products

Google AdMob

Mobile Ads SDK (Android)

Send feedback

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. Case study.

This guide explains how to integrate interstitial ads into an Android app.

Prerequisite

Import the Google Mobile Ads SDK, either by itself or as part of Firebase.

Create an interstitial ad object

Interstitial ads are requested and shown by InterstitialAd objects. The first step is instantiating InterstitialAd and setting its ad unit ID. This is done in the onCreate() method of an Activity:

Java

Kotlin

package ...

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

public class MainActivity extends Activity {

private InterstitialAd mInterstitialAd;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

MobileAds.initialize(this, new OnInitializationCompleteListener() {

@Override

public void onInitializationComplete(InitializationStatus initializationStatus) {}

});

mInterstitialAd = new InterstitialAd(this);

mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");

}

}

A single InterstitialAd object can be used to request and display multiple interstitial ads over the course of an activity's lifespan, so you only need to construct it once.

Always test with test ads

When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

The easiest way to load test ads is to use our dedicated test ad unit ID for Android interstitials:

ca-app-pub-3940256099942544/1033173712

It's been specially configured to return test ads for every request, and you're free to use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.

For more information about how the Mobile Ads SDK's test ads work, see Test Ads.

Load an ad

Note: Make all calls to the Mobile Ads SDK on the main thread.

To load an interstitial ad, call the InterstitialAd object's loadAd() method. This method accepts an AdRequest object as its single parameter:

Java

Kotlin

package ...

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

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

public class MainActivity extends Activity {

private InterstitialAd mInterstitialAd;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

MobileAds.initialize(this,

"ca-app-pub-3940256099942544~3347511713");

mInterstitialAd = new InterstitialAd(this);

mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");

mInterstitialAd.loadAd(new AdRequest.Builder().build());

}

}

Show the ad

Interstitial ads should be displayed during natural pauses in the flow of an app. Between levels of a game is a good example, or after the user completes a task. To show an interstitial, use the isLoaded() method to verify that it's done loading, then call show(). The interstitial ad from the previous code example could be shown in a button's OnClickListener like this:

Java

Kotlin

mMyButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (mInterstitialAd.isLoaded()) {

mInterstitialAd.show();

} else {

Log.d("TAG", "The interstitial wasn't loaded yet.");

}

}

});

Ad events

To further customize the behavior of your ad, you can hook onto a number of events in the ad's lifecycle: loading, opening, closing, and so on. You can listen for these events through the AdListener class.

To use an AdListener with an InterstitialAd object, simply call the setAdListener() method:

Java

Kotlin

mInterstitialAd.setAdListener(new AdListener() {

@Override

public void onAdLoaded() {

// Code to be executed when an ad finishes loading.

}

@Override

public void onAdFailedToLoad(int errorCode) {

// Code to be executed when an ad request fails.

}

@Override

public void onAdOpened() {

// Code to be executed when the ad is displayed.

}

@Override

public void onAdClicked() {

// Code to be executed when the user clicks on an ad.

}

@Override

public void onAdLeftApplication() {

// Code to be executed when the user has left the app.

}

@Override

public void onAdClosed() {

// Code to be executed when the interstitial ad is closed.

}

});

Each of the overridable methods in AdListener corresponds to an event in the lifecycle of an ad.

Overridable methods

onAdLoaded() The onAdLoaded() method is executed when an ad has finished loading.

onAdFailedToLoad() The onAdFailedToLoad() method includes an errorCode parameter that indicates what type of failure occurred. The possible values are defined as constants in the AdRequest class:

ERROR_CODE_INTERNAL_ERROR - Something happened internally; for instance, an invalid response was received from the ad server.

ERROR_CODE_INVALID_REQUEST - The ad request was invalid; for instance, the ad unit ID was incorrect.

ERROR_CODE_NETWORK_ERROR - The ad request was unsuccessful due to network connectivity.

ERROR_CODE_NO_FILL - The ad request was successful, but no ad was returned due to lack of ad inventory.

onAdOpened() This method is invoked when the ad is displayed, covering the device's screen.

onAdLeftApplication() This method is invoked when a user click opens another app (such as the Google Play), backgrounding the current app.

onAdClosed() This method is invoked when the interstitial ad is closed due to the user tapping on the close icon or using the back button. If your app paused its audio output or game loop, this is a great place to resume it.

Warning: Attempting to load a new ad from the onAdFailedToLoad() method is strongly discouraged. If you must load an ad from onAdFailedToLoad(), limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.

Using an AdListener to reload

The AdListener class's onAdClosed() method is a handy place to load a new interstitial after displaying the previous one:

Java

Kotlin

...

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

MobileAds.initialize(this,

"ca-app-pub-3940256099942544~3347511713");

mInterstitialAd = new InterstitialAd(this);

mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");

mInterstitialAd.loadAd(new AdRequest.Builder().build());

mInterstitialAd.setAdListener(new AdListener() {

@Override

public void onAdClosed() {

// Load the next interstitial.

mInterstitialAd.loadAd(new AdRequest.Builder().build());

}

});

}

...

Some best practices

Consider whether interstitial ads are the right type of ad for your app.

Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.

Remember to pause the action when displaying an interstitial ad.

There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app. You can resume playing sounds in the onAdClosed() event handler, which will be invoked when the user has finished interacting with the ad. In addition, consider temporarily halting any intense computation tasks (such as a game loop) while the ad is being displayed. This will make sure the user doesn't experience slow or unresponsive graphics or stuttered video.

Allow for adequate loading time.

Just as it's important to make sure you display interstitial ads at an appropriate time, it's also important to make sure the user doesn't have to wait for them to load. Loading the ad in advance by calling loadAd() before you intend to call show() can ensure that your app has a fully loaded interstitial ad at the ready when the time comes to display one.

Don't flood the user with ads.

While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.

Source code

MyActivity.java

/*

* Copyright (C) 2013 Google, Inc.

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

package com.google.android.gms.example.interstitialexample;

import android.os.Bundle;

import android.os.CountDownTimer;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;

import com.google.android.gms.ads.AdListener;

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

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

import com.google.android.gms.ads.MobileAds;

import com.google.android.gms.ads.initialization.InitializationStatus;

import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

/**

* Main Activity. Inflates main activity xml.

*/

public class MyActivity extends AppCompatActivity {

private static final long GAME_LENGTH_MILLISECONDS = 3000;

private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712";

private InterstitialAd interstitialAd;

private CountDownTimer countDownTimer;

private Button retryButton;

private boolean gameIsInProgress;

private long timerMilliseconds;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_my);

// Initialize the Mobile Ads SDK.

MobileAds.initialize(this, new OnInitializationCompleteListener() {

@Override

public void onInitializationComplete(InitializationStatus initializationStatus) {}

});

// Create the InterstitialAd and set the adUnitId.

interstitialAd = new InterstitialAd(this);

// Defined in res/values/strings.xml

interstitialAd.setAdUnitId(AD_UNIT_ID);

interstitialAd.setAdListener(new AdListener() {

@Override

public void onAdLoaded() {

Toast.makeText(MyActivity.this, "onAdLoaded()", Toast.LENGTH_SHORT).show();

}

@Override

public void onAdFailedToLoad(int errorCode) {

Toast.makeText(MyActivity.this,

"onAdFailedToLoad() with error code: " + errorCode,

Toast.LENGTH_SHORT).show();

}

@Override

public void onAdClosed() {

startGame();

}

});

// Create the "retry" button, which tries to show an interstitial between game plays.

retryButton = findViewById(R.id.retry_button);

retryButton.setVisibility(View.INVISIBLE);

retryButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

showInterstitial();

}

});

startGame();

}

private void createTimer(final long milliseconds) {

// Create the game timer, which counts down to the end of the level

// and shows the "retry" button.

if (countDownTimer != null) {

countDownTimer.cancel();

}

final TextView textView = findViewById(R.id.timer);

countDownTimer = new CountDownTimer(milliseconds, 50) {

@Override

public void onTick(long millisUnitFinished) {

timerMilliseconds = millisUnitFinished;

textView.setText("seconds remaining: " + ((millisUnitFinished / 1000) + 1));

}

@Override

public void onFinish() {

gameIsInProgress = false;

textView.setText("done!");

retryButton.setVisibility(View.VISIBLE);

}

};

}

@Override

public void onResume() {

// Start or resume the game.

super.onResume();

if (gameIsInProgress) {

resumeGame(timerMilliseconds);

}

}

@Override

public void onPause() {

// Cancel the timer if the game is paused.

countDownTimer.cancel();

super.onPause();

}

private void showInterstitial() {

// Show the ad if it's ready. Otherwise toast and restart the game.

if (interstitialAd != null && interstitialAd.isLoaded()) {

interstitialAd.show();

} else {

Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();

startGame();

}

}

private void startGame() {

// Request a new ad if one isn't already loaded, hide the button, and kick off the timer.

if (!interstitialAd.isLoading() && !interstitialAd.isLoaded()) {

AdRequest adRequest = new AdRequest.Builder().build();

interstitialAd.loadAd(adRequest);

}

retryButton.setVisibility(View.INVISIBLE);

resumeGame(GAME_LENGTH_MILLISECONDS);

}

private void resumeGame(long milliseconds) {

// Create a new timer for the correct length and start it.

gameIsInProgress = true;

timerMilliseconds = milliseconds;

createTimer(milliseconds);

countDownTimer.start();

}

}

1
$ 0.00
Avatar for jesusboyg
3 years ago

Comments