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.
}
});
Kotlin
mInterstitialAd.adListener = object: AdListener() {
override fun onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
override fun onAdFailedToLoad(errorCode: Int) {
// Code to be executed when an ad request fails.
}
override fun onAdOpened() {
// Code to be executed when the ad is displayed.
}
override fun onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
override fun onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
override fun onAdClosed() {
// Code to be executed when the interstitial ad is closed.
}
}
/*
* 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.LoadAdError;
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(LoadAdError loadAdError) {
String error =
String.format(
"domain: %s, code: %d, message: %s",
loadAdError.getDomain(), loadAdError.getCode(), loadAdError.getMessage());
Toast.makeText(
MyActivity.this, "onAdFailedToLoad() with error: " + error, 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();
}
}
MainActivity.kt
package com.google.android.gms.example.interstitialexample
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
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.LoadAdError
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.RequestConfiguration
import kotlinx.android.synthetic.main.activity_main.*
const val GAME_LENGTH_MILLISECONDS = 3000L
const val AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712"
class MainActivity : AppCompatActivity() {
private lateinit var mInterstitialAd: InterstitialAd
private var mCountDownTimer: CountDownTimer? = null
private var mGameIsInProgress = false
private var mTimerMilliseconds = 0L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this) {}
// Set your test devices. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("ABCDEF012345"))
// to get test ads on this device."
MobileAds.setRequestConfiguration(
RequestConfiguration.Builder()
.setTestDeviceIds(listOf("ABCDEF012345"))
.build()
)
// Create the InterstitialAd and set it up.
mInterstitialAd = InterstitialAd(this).apply {
adUnitId = AD_UNIT_ID
adListener = (
object : AdListener() {
override fun onAdLoaded() {
Toast.makeText(this@MainActivity, "onAdLoaded()", Toast.LENGTH_SHORT).show()
}
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
val error = "domain: ${loadAdError.domain}, code: ${loadAdError.code}, " +
"message: ${loadAdError.message}"
Toast.makeText(
this@MainActivity,
"onAdFailedToLoad() with error $error",
Toast.LENGTH_SHORT
).show()
}
override fun onAdClosed() {
startGame()
}
}
)
}
// Create the "retry" button, which triggers an interstitial between game plays.
retry_button.visibility = View.INVISIBLE
retry_button.setOnClickListener { showInterstitial() }
// Kick off the first play of the "game."
startGame()
}
// Create the game timer, which counts down to the end of the level
// and shows the "retry" button.
private fun createTimer(milliseconds: Long) {
mCountDownTimer?.cancel()
mCountDownTimer = object : CountDownTimer(milliseconds, 50) {
override fun onTick(millisUntilFinished: Long) {
mTimerMilliseconds = millisUntilFinished
timer.text = "seconds remaining: ${ millisUntilFinished / 1000 + 1 }"
}
override fun onFinish() {
mGameIsInProgress = false
timer.text = "done!"
retry_button.visibility = View.VISIBLE
}
}
}
// Show the ad if it's ready. Otherwise toast and restart the game.
private fun showInterstitial() {
if (mInterstitialAd.isLoaded) {
mInterstitialAd.show()
} else {
Toast.makeText(this, "Ad wasn't loaded.", Toast.LENGTH_SHORT).show()
startGame()
}
}
// Request a new ad if one isn't already loaded, hide the button, and kick off the timer.
private fun startGame() {
if (!mInterstitialAd.isLoading && !mInterstitialAd.isLoaded) {
// Create an ad request.
val adRequest = AdRequest.Builder().build()
mInterstitialAd.loadAd(adRequest)
}
retry_button.visibility = View.INVISIBLE
resumeGame(GAME_LENGTH_MILLISECONDS)
}
private fun resumeGame(milliseconds: Long) {
// Create a new timer for the correct length and start it.
mGameIsInProgress = true
mTimerMilliseconds = milliseconds
createTimer(milliseconds)
mCountDownTimer?.start()
}
// Resume the game if it's in progress.
public override fun onResume() {
super.onResume()
if (mGameIsInProgress) {
resumeGame(mTimerMilliseconds)
}
}
// Cancel the timer if the game is paused.
public override fun onPause() {
mCountDownTimer?.cancel()
super.onPause()
}
}