Los anuncios intersticiales son anuncios a pantalla completa que cubren la interfaz de la aplicación que los aloja. Suelen mostrarse en los puntos de transición naturales de una aplicación. Por ejemplo, entre distintas actividades o al pasar de un nivel a otro en un juego.
Cuando una aplicación muestra un anuncio intersticial, el usuario tiene la opción de tocarlo e ir a la página de destino, o de cerrarlo y volver a la aplicación.
Consulta este caso de éxito.
En esta guía se explica cómo puedes integrar anuncios intersticiales en aplicaciones Android.
Requisitos previos
Tener la versión 19.7.0 del SDK de anuncios de Google para móviles o una posterior.
Seguir la guía de introducción para importar el SDK de anuncios de Google para móviles y actualizar el archivo de manifiesto de Android.
Comprobar siempre las aplicaciones con anuncios de prueba
Cuando crees y pruebes tus aplicaciones, utiliza siempre anuncios de prueba en lugar de anuncios reales que se estén publicando. De lo contrario, podríamos suspender tu cuenta.
La forma más sencilla de cargar anuncios de prueba es usar nuestro ID de bloque de anuncios de prueba para intersticiales de Android:
ca-app-pub-3940256099942544/1033173712
Lo hemos configurado especialmente para que devuelva anuncios de prueba en cada solicitud, y puedes usarlo mientras programas, evalúas y depuras tus propias aplicaciones. Solo tienes que sustituirlo por el ID de tu bloque de anuncios antes de publicar la aplicación.
Para cargar un anuncio intersticial, llama al método InterstitialAd estático load() y transfiere una InterstitialAdLoadCallback para recibir el anuncio cargado o cualquier error. Ten en cuenta que, al igual que otras retrollamadas de carga de formato, InterstitialAdLoadCallback utiliza LoadAdError para proporcionar detalles de los errores de mayor fidelidad.
FullScreenContentCallback gestiona eventos relacionados con la visualización de tu InterstitialAd. Antes de mostrar InterstitialAd, asegúrate de configurar la retrollamada:
Los anuncios intersticiales deben mostrarse durante las pausas naturales de una aplicación, por ejemplo, entre los diferentes niveles de un juego o después de que el usuario complete una tarea.
Para mostrar un anuncio intersticial, utiliza el método show().
Plantéate si los intersticiales son el tipo de anuncio más adecuado para tu aplicación.
Los anuncios intersticiales funcionan mejor en las aplicaciones con puntos de transición naturales.
Por ejemplo, al finalizar una tarea en la aplicación, como compartir una imagen o completar un nivel de un juego. En esos momentos, como el usuario espera que se produzca una interrupción en la acción, es fácil presentar un anuncio intersticial sin que su experiencia se vea afectada. Decide en qué puntos del flujo de trabajo de la aplicación se mostrarán anuncios intersticiales y analiza cómo crees que responderán los usuarios.
Recuerda pausar la acción cuando se muestra un anuncio intersticial.
Hay distintos tipos de anuncios intersticiales, como los de texto, de imagen y de vídeo. Es importante que, cuando la aplicación muestre un anuncio intersticial, se suspenda el uso de algunos recursos para que el anuncio pueda aprovecharlos. Por ejemplo, cuando realices la llamada para mostrar un anuncio intersticial, pausa todo el audio que se esté reproduciendo en la aplicación.
Define un tiempo de carga adecuado.
Evitar que el usuario tenga que esperar a que los anuncios intersticiales se carguen es igual de importante que mostrarlos en el momento adecuado. Para que la aplicación tenga un anuncio intersticial completamente cargado y listo cuando llegue el momento de mostrarlo, cárgalo por adelantado. Para ello, llama a load() antes de llamar a show().
No satures al usuario con anuncios.
Aunque aumentar la frecuencia de los anuncios intersticiales en tu aplicación te parezca una excelente forma de aumentar los ingresos, también puede degradar la experiencia de usuario y provocar que disminuya el porcentaje de clics. Si interrumpes a los usuarios con demasiada frecuencia, no disfrutarán de la experiencia de utilizar tu aplicación.
Código fuente
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.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
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.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;
/**
* 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 static final String TAG = "MyActivity";
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) {}
});
loadAd();
// 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();
}
public void loadAd() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(
this,
AD_UNIT_ID,
adRequest,
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
MyActivity.this.interstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
Toast.makeText(MyActivity.this, "onAdLoaded()", Toast.LENGTH_SHORT).show();
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
@Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Make sure to set your reference to null so you don't
// show it a second time.
MyActivity.this.interstitialAd = null;
Log.d("TAG", "The ad was dismissed.");
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Make sure to set your reference to null so you don't
// show it a second time.
MyActivity.this.interstitialAd = null;
Log.d("TAG", "The ad failed to show.");
}
@Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d("TAG", "The ad was shown.");
}
});
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
interstitialAd = null;
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();
}
});
}
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.show(this);
} 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 == null) {
loadAd();
}
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.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.ads.*
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
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 var mInterstitialAd: InterstitialAd? = null
private var mCountDownTimer: CountDownTimer? = null
private var mGameIsInProgress = false
private var mAdIsLoading: Boolean = false
private var mTimerMilliseconds = 0L
private var TAG = "MainActivity"
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 "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()
}
private fun loadAd() {
var adRequest = AdRequest.Builder().build()
InterstitialAd.load(
this, AD_UNIT_ID, adRequest,
object : InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.d(TAG, adError?.message)
mInterstitialAd = null
mAdIsLoading = false
val error = "domain: ${adError.domain}, code: ${adError.code}, " +
"message: ${adError.message}"
Toast.makeText(
this@MainActivity,
"onAdFailedToLoad() with error $error",
Toast.LENGTH_SHORT
).show()
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
Log.d(TAG, "Ad was loaded.")
mInterstitialAd = interstitialAd
mAdIsLoading = false
Toast.makeText(this@MainActivity, "onAdLoaded()", Toast.LENGTH_SHORT).show()
}
}
)
}
// 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 != null) {
mInterstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
Log.d(TAG, "Ad was dismissed.")
// Don't forget to set the ad reference to null so you
// don't show the ad a second time.
mInterstitialAd = null
loadAd()
}
override fun onAdFailedToShowFullScreenContent(adError: AdError?) {
Log.d(TAG, "Ad failed to show.")
// Don't forget to set the ad reference to null so you
// don't show the ad a second time.
mInterstitialAd = null
}
override fun onAdShowedFullScreenContent() {
Log.d(TAG, "Ad showed fullscreen content.")
// Called when ad is dismissed.
}
}
mInterstitialAd?.show(this)
} 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 (!mAdIsLoading && mInterstitialAd == null) {
mAdIsLoading = true
loadAd()
}
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()
}
}