Os anúncios intersticiais são anúncios em tela cheia que cobrem a interface do app host. Geralmente, eles são exibidos em pontos de transição naturais no fluxo de um app, como durante a pausa entre as fases de um jogo. Quando um app mostra um anúncio intersticial, o usuário tem a opção de tocar no anúncio e ir até o destino ou fechá-lo e retornar ao app. Estudo de caso.
Este guia explica como integrar anúncios intersticiais a um app Unity.
Pré-requisitos
- Leia o Guia explicativo.
务必用测试广告进行测试
以下示例代码包含一个广告单元 ID,可供您用来请求测试广告。该测试广告单元 ID 已经过专门配置,可为每个请求返回测试广告(而不是实际投放的广告),因此能安全地使用。
不过,在AdMob 网页界面中注册了应用并创建您自己的广告单元 ID 以在应用中使用后,请在开发期间明确将您的设备配置为测试设备。
Android
ca-app-pub-3940256099942544/1033173712
iOS
ca-app-pub-3940256099942544/4411468910
Initialize the Mobile Ads SDK
Before loading ads, have your app initialize the Mobile Ads SDK by calling
MobileAds.Initialize()
. This needs to be done only once, ideally at app launch.
using GoogleMobileAds;
using GoogleMobileAds.Api;
public class GoogleMobileAdsDemoScript : MonoBehaviour
{
public void Start()
{
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize((InitializationStatus initStatus) =>
{
// This callback is called once the MobileAds SDK is initialized.
});
}
}
If you're using mediation, wait until the callback occurs before loading ads as this will ensure that all mediation adapters are initialized.
Implementação
As principais etapas para integrar os anúncios intersticiais são:
- Carregar o anúncio intersticial
- Mostrar o anúncio intersticial
- Detectar eventos de anúncios intersticiais
- Limpe o anúncio intersticial
- Pré-carregar o próximo anúncio intersticial
Carregar o anúncio intersticial
É possível carregar um anúncio intersticial usando o método estático Load()
na
classe InterstitialAd
. O método de carregamento requer um ID do bloco de anúncios, um objeto AdRequest
e um gerenciador de conclusão que é chamado quando o carregamento do anúncio é concluído ou apresenta falha. O objeto InterstitialAd
carregado é fornecido como um parâmetro no gerenciador de conclusão. O exemplo abaixo mostra como carregar uma
InterstitialAd
.
// These ad units are configured to always serve test ads.
#if UNITY_ANDROID
private string _adUnitId = "ca-app-pub-3940256099942544/1033173712";
#elif UNITY_IPHONE
private string _adUnitId = "ca-app-pub-3940256099942544/4411468910";
#else
private string _adUnitId = "unused";
#endif
private InterstitialAd _interstitialAd;
/// <summary>
/// Loads the interstitial ad.
/// </summary>
public void LoadInterstitialAd()
{
// Clean up the old ad before loading a new one.
if (_interstitialAd != null)
{
_interstitialAd.Destroy();
_interstitialAd = null;
}
Debug.Log("Loading the interstitial ad.");
// create our request used to load the ad.
var adRequest = new AdRequest();
// send the request to load the ad.
InterstitialAd.Load(_adUnitId, adRequest,
(InterstitialAd ad, LoadAdError error) =>
{
// if error is not null, the load request failed.
if (error != null || ad == null)
{
Debug.LogError("interstitial ad failed to load an ad " +
"with error : " + error);
return;
}
Debug.Log("Interstitial ad loaded with response : "
+ ad.GetResponseInfo());
_interstitialAd = ad;
});
}
Mostrar o anúncio intersticial
Para mostrar um anúncio intersticial carregado, chame o método Show()
na instância InterstitialAd
. Os anúncios podem ser mostrados uma vez por carregamento. Use o método CanShowAd()
para verificar se o anúncio está pronto para ser mostrado.
/// <summary>
/// Shows the interstitial ad.
/// </summary>
public void ShowInterstitialAd()
{
if (_interstitialAd != null && _interstitialAd.CanShowAd())
{
Debug.Log("Showing interstitial ad.");
_interstitialAd.Show();
}
else
{
Debug.LogError("Interstitial ad is not ready yet.");
}
}
Detectar eventos de anúncios intersticiais
Para personalizar ainda mais o comportamento do seu anúncio, conecte-se a vários eventos do ciclo de vida dele. Detecte esses eventos registrando um delegado, conforme mostrado abaixo.
private void RegisterEventHandlers(InterstitialAd interstitialAd)
{
// Raised when the ad is estimated to have earned money.
interstitialAd.OnAdPaid += (AdValue adValue) =>
{
Debug.Log(String.Format("Interstitial ad paid {0} {1}.",
adValue.Value,
adValue.CurrencyCode));
};
// Raised when an impression is recorded for an ad.
interstitialAd.OnAdImpressionRecorded += () =>
{
Debug.Log("Interstitial ad recorded an impression.");
};
// Raised when a click is recorded for an ad.
interstitialAd.OnAdClicked += () =>
{
Debug.Log("Interstitial ad was clicked.");
};
// Raised when an ad opened full screen content.
interstitialAd.OnAdFullScreenContentOpened += () =>
{
Debug.Log("Interstitial ad full screen content opened.");
};
// Raised when the ad closed full screen content.
interstitialAd.OnAdFullScreenContentClosed += () =>
{
Debug.Log("Interstitial ad full screen content closed.");
};
// Raised when the ad failed to open full screen content.
interstitialAd.OnAdFullScreenContentFailed += (AdError error) =>
{
Debug.LogError("Interstitial ad failed to open full screen content " +
"with error : " + error);
};
}
Limpe o anúncio intersticial
Quando você terminar de usar um InterstitialAd
, chame o método Destroy()
antes de descartar a referência a ele:
_interstitialAd.Destroy();
Isso notifica o plug-in de que o objeto não é mais usado e que a memória que ele ocupa pode ser recuperada. A falha em chamar esse método resulta em vazamentos de memória.
Pré-carregar o próximo anúncio intersticial
Os anúncios intersticiais são objetos de uso único. Isso significa que, quando um anúncio intersticial é exibido, o objeto não pode ser usado novamente. Para solicitar outro anúncio intersticial, crie um novo objeto InterstitialAd
.
Para preparar um anúncio intersticial para a próxima oportunidade de impressão, pré-carregue o anúncio quando o evento de anúncio OnAdFullScreenContentClosed
ou OnAdFullScreenContentFailed
for gerado.
private void RegisterReloadHandler(InterstitialAd interstitialAd)
{
// Raised when the ad closed full screen content.
interstitialAd.OnAdFullScreenContentClosed += ()
{
Debug.Log("Interstitial Ad full screen content closed.");
// Reload the ad so that we can show another as soon as possible.
LoadInterstitialAd();
};
// Raised when the ad failed to open full screen content.
interstitialAd.OnAdFullScreenContentFailed += (AdError error) =>
{
Debug.LogError("Interstitial ad failed to open full screen content " +
"with error : " + error);
// Reload the ad so that we can show another as soon as possible.
LoadInterstitialAd();
};
}
Práticas recomendadas
- Determine se os anúncios intersticiais são o tipo certo de anúncio para seu app.
- Os anúncios intersticiais funcionam melhor em apps com pontos de transição naturais. Esses pontos são criados pela conclusão de uma tarefa em um app, como o compartilhamento de uma imagem ou a conclusão de um nível do jogo. Considere em quais pontos do fluxo do seu app os anúncios intersticiais são exibidos da melhor forma e como o usuário provavelmente vai responder.
- Pause a ação ao exibir um anúncio intersticial.
- Há vários tipos diferentes de anúncios intersticiais, como de texto, gráficos ou em vídeo. É importante garantir que, quando o app exibir um
anúncio intersticial, ele também suspenda o uso de alguns recursos para permitir
que o anúncio os aproveite. Por exemplo, ao fazer a chamada para mostrar um
anúncio intersticial, pause qualquer saída de áudio produzida pelo app.
É possível retomar a reprodução de sons no evento
OnAdFullScreenContentClosed()
, que pode ser invocado quando o usuário termina de interagir com o anúncio. Além disso, considere interromper temporariamente qualquer tarefa de computação intensa, como um loop de jogo, enquanto o anúncio estiver sendo exibido. Isso garante que o usuário não esteja com gráficos lentos ou sem resposta nem vídeos travados. - Não sobrecarregue o usuário com anúncios.
- Embora aumentar a frequência de anúncios intersticiais no app possa parecer uma ótima maneira de aumentar a receita, também pode prejudicar a experiência do usuário e reduzir as taxas de cliques. Garanta que os usuários não sejam interrompidos com tanta frequência de modo que não possam mais aproveitar o app.
Outros recursos
- Exemplo do HelloWorld: uma implementação mínima de todos os formatos de anúncio.