Adicionar anúncios intersticiais a um app Android

O Audience Network permite que você monetize os seus apps Android usando os anúncios do Facebook. Os anúncios intersticiais são anúncios em tela cheia que você pode exibir no seu app. Em geral, esse tipo de anúncio é exibido quando há uma transição no app. Por exemplo: depois de um nível ser concluído em um jogo ou depois de um artigo ser carregado em um app de notícias.

Certifique-se de ter concluído os guias de Introdução do Audience Network e Introdução do Android antes de continuar.

Passo a passo

Etapa 1: inicializar anúncios intersticiais na sua atividade

Etapa 2: exibir anúncios intersticiais

Inicialize o SDK do Audience Network

Este método foi adicionado ao SDK do Audience Network para Android versão 5.1.

A inicialização explícita do SDK do Audience Network para Android é exigida para a versão 5.3.0 e superiores. Consulte este documento sobre como inicializar o SDK do Audience Network para Android.

Inicialize o SDK do Audience Network antes de criar um objeto de anúncio e carregar anúncios. É recomendado fazer isso durante a inicialização do aplicativo.

public class YourApplication extends Application {
    ...
    @Override
    public void onCreate() {
        super.onCreate();
        // Initialize the Audience Network SDK
        AudienceNetworkAds.initialize(this);       
    }
    ...
}

Etapa 1: inicializar anúncios intersticiais na sua atividade

Adicione o seguinte código à parte superior da sua Atividade para importar o SDK de Anúncios do Facebook:

import com.facebook.ads.*;

Inicialize o 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");
...  

Etapa 2: exibir anúncios intersticiais

Cenário 1: criar um InterstitialAdListener, carregar o anúncio e exibi-lo imediatamente após o carregamento.

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
                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());
    }
}

Os anúncios intersticiais têm criativos com grandes tamanhos. Por isso, sugerimos fazer uma chamada a loadAd(...) com antecedência e, no momento apropriado, fazer uma chamada a show().

Cenário 2: exibir o anúncio poucos segundos ou minutos após o carregamento. Você deve verificar se o anúncio foi invalidado antes de exibi-lo.

Caso o anúncio não tenha sido exibido imediatamente depois de carregado, a responsabilidade de verificar se o anúncio foi invalidado é do desenvolvedor. Depois de carregado, o anúncio continuará válido por 60 minutos. Você não receberá pagamento pela exibição de anúncios inválidos.

É necessário seguir a ideia abaixo, mas não copie o código para o seu projeto, pois este é apenas um exemplo:

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 fim, adicione o código a seguir à função onDestroy() da atividade para liberar os recursos usados por InterstitialAd:

@Override
protected void onDestroy() {
    if (interstitialAd != null) {
        interstitialAd.destroy();
    }
    super.onDestroy();
}

Se estiver usando o emulador padrão de Android do Google, adicione a seguinte linha de código antes de carregar um anúncio de teste:
AdSettings.addTestDevice("HASHED ID");.

Use o ID convertido em hash que está impresso no catálogo de registros ao fazer uma solicitação para carregar um anúncio em um dispositivo pela primeira vez.

Genymotion e dispositivos físicos não precisam dessa etapa. Se você quiser testar com anúncios reais, consulte nosso Guia de Teste.

Inicialize o app e você verá o anúncio intersticial:

Aceleração de hardware para anúncios de vídeo

Os anúncios de vídeo no Audience Network exigem a ativação da exibição com aceleração de hardware, ou poderá haver uma tela preta na visualizações de vídeo. Isso se aplica a

  • Criativos de vídeo em anúncios nativos
  • Criativos de vídeo em anúncios intersticiais
  • Anúncios de vídeo in-stream
  • Vídeos com incentivo

A aceleração de hardware será ativada por padrão se o nível da sua API de destino for >=14 (Ice Cream Sandwich, Android 4.0.1), mas você pode também ativar esse recurso de forma explícita no nível de aplicativo ou no nível de atividade.

Nível de aplicativo

No arquivo de manifesto do Android, adicione o seguinte atributo à tag <application> para ativar a aceleração de hardware no aplicativo inteiro:

<application android:hardwareAccelerated="true" ...>

Nível de atividade

Caso você queira ativar o recurso somente para atividades específicas do seu aplicativo, no arquivo de manifesto do Android, é possível adicionar o seguinte recurso à tag <activity>. O exemplo a seguir ativará a aceleração de hardware de AudienceNetworkActivity, que é usada para renderizar anúncios intersticiais e vídeos com incentivo:

<activity android:name="com.facebook.ads.AudienceNetworkActivity" android:hardwareAccelerated="true" .../>

Próximas etapas