Audience Network te permite monetizar tus apps para Android mediante anuncios de Facebook. Un anuncio intersticial es un anuncio a pantalla completa que puedes mostrar en tu app. En general, los anuncios intersticiales se muestran cuando hay una transición en la app. Por ejemplo, cuando finalizas un nivel en un juego o después de cargar un artículo en una app de noticias.
Asegúrate de completar las guías de primeros pasos para Audience Network y Android antes de continuar.
Este método se agregó en la versión 5.1 del SDK de Audience Network para Android.
La inicialización explícita del SDK de Audience Network para Android es obligatoria a partir de la versión 5.3.0. Consulta este documento sobre cómo inicializar el SDK de Audience Network para Android.
Antes de crear un objeto de anuncio y cargar anuncios, debes inicializar el SDK de Audience Network. Se recomienda hacerlo durante el inicio de la aplicación.
public class YourApplication extends Application {
...
@Override
public void onCreate() {
super.onCreate();
// Initialize the Audience Network SDK
AudienceNetworkAds.initialize(this);
}
...
}Agrega el siguiente código en la parte superior de la actividad para importar el SDK de anuncios de Facebook:
import com.facebook.ads.*;
Inicia el InterstitialAd.
private InterstitialAd interstitialAd;
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Instantiate an InterstitialAd object.
// NOTE: the placement ID will eventually identify this as your App, you can ignore it for
// now, while you are testing and replace it later when you have signed up.
// While you are using this temporary code you will only get test ads and if you release
// your code like this to the Google Play your users will not receive ads (you will get a no fill error).
interstitialAd = new InterstitialAd(this, "YOUR_PLACEMENT_ID");
... InterstitialAdListener, cargar el anuncio y mostrarlo en cuanto se haya cargado correctamente.public class InterstitialAdActivity extends Activity {
private final String TAG = InterstitialAdActivity.class.getSimpleName();
private InterstitialAd interstitialAd;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Instantiate an InterstitialAd object.
// NOTE: the placement ID will eventually identify this as your App, you can ignore it for
// now, while you are testing and replace it later when you have signed up.
// While you are using this temporary code you will only get test ads and if you release
// your code like this to the Google Play your users will not receive ads (you will get a no fill error).
interstitialAd = new InterstitialAd(this, "YOUR_PLACEMENT_ID");
// Create listeners for the Interstitial Ad
InterstitialAdListener interstitialAdListener = new InterstitialAdListener() {
@Override
public void onInterstitialDisplayed(Ad ad) {
// Interstitial ad displayed callback
Log.e(TAG, "Interstitial ad displayed.");
}
@Override
public void onInterstitialDismissed(Ad ad) {
// Interstitial dismissed callback
Log.e(TAG, "Interstitial ad dismissed.");
}
@Override
public void onError(Ad ad, AdError adError) {
// Ad error callback
Log.e(TAG, "Interstitial ad failed to load: " + adError.getErrorMessage());
}
@Override
public void onAdLoaded(Ad ad) {
// Interstitial ad is loaded and ready to be displayed
Log.d(TAG, "Interstitial ad is loaded and ready to be displayed!");
// Show the ad
interstitialAd.show();
}
@Override
public void onAdClicked(Ad ad) {
// Ad clicked callback
Log.d(TAG, "Interstitial ad clicked!");
}
@Override
public void onLoggingImpression(Ad ad) {
// Ad impression logged callback
// Please refer to Monetization Manager or Reporting API for final impression numbers
Log.d(TAG, "Interstitial ad impression logged!");
}
};
// For auto play video ads, it's recommended to load the ad
// at least 30 seconds before it is shown
interstitialAd.loadAd(
interstitialAd.buildLoadAdConfig()
.withAdListener(interstitialAdListener)
.build());
}
}Los anuncios intersticiales tienen contenido de gran tamaño, por lo que es una buena práctica llamar la función loadAd(...) de antemano y, luego, llamar show() en el momento adecuado.
En caso de no querer mostrar el anuncio inmediatamente después de que se haya cargado, el desarrollador es responsable de comprobar si el anuncio se invalidó o no. Una vez que el anuncio se haya cargado por completo, será válido por 60 minutos. No se te pagará si enseñas un anuncio invalidado.
Te recomendamos que sigas el modelo que aparece a continuación, pero no copies el código en tu proyecto, ya que es solo un ejemplo:
public class InterstitialAdActivity extends Activity {
private InterstitialAd interstitialAd ;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate an InterstitialAd object.
// NOTE: the placement ID will eventually identify this as your App, you can ignore it for
// now, while you are testing and replace it later when you have signed up.
// While you are using this temporary code you will only get test ads and if you release
// your code like this to the Google Play your users will not receive ads (you will get a no fill error).
interstitialAd = new InterstitialAd(this, "YOUR_PLACEMENT_ID");
InterstitialAdListener interstitialAdListener = new InterstitialAdListener() {
...
};
// load the ad
interstitialAd.loadAd(
interstitialAd.buildLoadAdConfig()
.withAdListener(interstitialAdListener)
.build());
}
private void showAdWithDelay() {
/**
* Here is an example for displaying the ad with delay;
* Please do not copy the Handler into your project
*/
// Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Check if interstitialAd has been loaded successfully
if(interstitialAd == null || !interstitialAd.isAdLoaded()) {
return;
}
// Check if ad is already expired or invalidated, and do not show ad if that is the case. You will not get paid to show an invalidated ad.
if(interstitialAd.isAdInvalidated()) {
return;
}
// Show the ad
interstitialAd.show();
}
}, 1000 * 60 * 15); // Show the ad after 15 minutes
}
}Por último, agrega el siguiente código a la función onDestroy() de tu actividad para soltar los recursos que utiliza InterstitialAd:
@Override
protected void onDestroy() {
if (interstitialAd != null) {
interstitialAd.destroy();
}
super.onDestroy();
}Si estás usando el emulador predeterminado de Google Android, debes agregar la siguiente línea de código antes de cargar un anuncio de prueba:AdSettings.addTestDevice("HASHED ID");.
Utiliza el identificador con hash que figura en el logcat la primera vez que realices una solicitud para cargar un anuncio en un dispositivo.
Genymotion y los dispositivos físicos no necesitan este paso. Si quieres probar con anuncios reales, consulta nuestra guía de pruebas.
Después de iniciar la app, deberías ver un anuncio intersticial:

Los anuncios con video en Audience Network requieren que se active la función de aceleración de hardware, ya que, de lo contrario, las reproducciones de video podrían mostrar una pantalla negra. Esto se aplica a:
La aceleración de hardware se activa de forma predeterminada si el nivel de API objetivo es mayor o igual a 14 (Ice Cream Sandwich, Android 4.0.1), pero también puedes activar explícitamente esta función en la aplicación o actividad.
En tu archivo de manifiesto de Android, agrega el siguiente atributo a la etiqueta <application> para activar la aceleración de hardware para toda la aplicación:
<application android:hardwareAccelerated="true" ...>
Si solo quieres activar la función para actividades concretas de tu aplicación, puedes agregar la siguiente función a la etiqueta <activity> en el archivo de manifiesto de Android. El siguiente ejemplo activará la aceleración de hardware para AudienceNetworkActivity, que se usa para mostrar anuncios intersticiales y videos con premio:
<activity android:name="com.facebook.ads.AudienceNetworkActivity" android:hardwareAccelerated="true" .../>
Los códigos de ejemplo relevantes en Swift y Objective-C están disponibles en nuestro repositorio de apps de ejemplo de GitHub.
Prueba la integración de tus anuncios con tu app.
Tan pronto como recibamos una solicitud de anuncio de parte de tu app o sitio web, la revisaremos para asegurarnos de que cumpla con las políticas de Audience Network y las Normas comunitarias de Facebook.