All right, before we go into the code
of displaying an Interstitial Ad,
let's discuss this a little bit.
Because there are two important things
to think about with Interstitial Ads.
The first one, is about
the format of an Interstitial Ad.
As we know, the Interstitial Ad consumes
the entire screen of the device.
Therefore, it's important
not to interrupt the user
while they are engaging with your app.
So the first important things to think
about, is to display Interstitial Ads
with our natural breaks in your app,
for example, between levels in a game.
The second important thing with
Interstitial Ads is to prepare
the loading of the ad before showing it.
Why is this important?
Well, loading an Interstitial Ad
can take time, in particular,
if the network is slow.
When the time has come to display an
Interstitial Ad, you don't want the user
to sit there and wait for it to load,
you want it to be displayed immediately.
Therefore, we load it in advance.
We prepare the loading
before we're showing the ad.
So how do we do that.
Well, let's start by looking
at the class Interstitial Ad.
This is the class we use to load and
show an Interstitial Ad.
So it has a method called loadAd.
But this method is just requesting
the ad to be loaded and
to avoid blocking the UI thread,
it will return immediately
before the ad has been loaded.
So how do we know when
the ad has been loaded?
By setting an AdListener,
we can overload to onAdLoaded method.
So when the Interstitial Ad has finished
loading, this method will be called, and
we can then proceed to call
show on the Interstitial Ad.
So, this is the flow that we
will implement in our app.
You should also know that Interstitial
Ad has a method called isLoaded.
So if you're not interested in knowing
exactly when the ad has been loaded,
then you could simply call loadAd.
And when the time has come to show the
ad, you check if the ad has been loaded.
If it has been loaded,
then you call the show method.
Otherwise, you do not
show the ad at all.
Now let's check out the code
to implement this flow.
Let's open up
the InterstitialActivity Java file.
The first thing we've done here is to
add an InterstitialAd field called
mInterstital, there are no
changes to the onCreate method.
So let's go and
look at the loadInsterstitial method.
This code should already be there
because we set it in the previous
exercise.
So let's look at the other code.
First, we're creating an instance
of the InterstatialAd.
Then, we're setting the AdUnitId.
And we set it to this string that
will return test InterstitialAds.
And this string, we defined in our
resource string file, so we have to get
it using the getResources().getString
and then the resource ID.
And now comes the flow
that we talked about.
Here, you can see that we're setting
the listener for the InterstitialAd.
Let's talk about this in a little while.
But we're setting a listener here and
then the execution drops down here.
So now, you can see, we're creating
an AdRequest using the builder.
And then we're calling the loadAd
method on our InterstitialAd instance.
Providing the AdRequest as an argument,
and as we saw before,
this method will start
the ad loading process, but
it will return immediately
before the ad has been loaded.
That's where our listener comes
into play, and as you can see,
we're creating an anonymous class here
based on our ToastAdListener class.
And as you can see,
we're overloading the onAdLoaded method.
So since we're setting
the listener here,
this method will be called when
the ad has completed loading.
So we call our parent method that
will display the toast message,
since that is what we defined
in the ToastAdListener class.
And then we set the text of our
disable button to Show Interstitial.
And we also enabled that button.
That means that the user
can now press this button.
And when that happens,
the showInterstitial callback
method will be called.
So what are we doing
is showInterstitial.
Well, with simple check if
the Interstitial Ad has been loaded, and
this may seem like an unnecessary check,
since we know the ad has been
loaded since onAdLoaded was called.
But we're doing it any how.
And then the time has come to actually
show the Interstitial Ad, and
when this happens, the ad will actually
be displayed in full screen mode.
And for the button,
we go back to a previous state,
setting the text Interstitial Not Ready
and then disabling it.
And finally, going back to our listener.
If the ad could not be loaded, the
onAdFailedToLoad method will be called.
In that case, again,
we show the toast message and
then we set the ErrorReason
to the text of the button.
That's it, that's the code we have
to implement the Interstitial Ad.
حسنًا، قبل الذهاب إلى التعليمة البرمجية
لعرض إعلان بيني،
لنُناقش هذا قليلاً.
لوجود أمرين هامين يجب أن تفكر بهما
مع الإعلانات البينية.
الأمر الأول، حول تنسيق الإعلان البيني.
كما نعلم، يستخدم الإعلان البيني شاشة
الجهاز كاملة.
ولذلك، من الهام عدم مقاطعة المستخدمين
أثناء استخدامهم تطبيقك.
مايجب أن تفكر فيه أولاً، عرض الإعلان
البيني
مع فواصل طبيعية في تطبيقك، على سبيل
المثال، بين المستويات في لعبة.
الأمر الثاني الهام بالنسبة للإعلان البيني
هو إعداد
تحميل الإعلان قبل عرضه.
لماذا يعد هذا أمرًا هامًا؟
حسنًا، يمكن أن يستغرق تحميل
إعلان بيني وقتًا، خاصة،
في حالة بطئ الشبكة.
عندما يحين وقت عرض إعلان بيني، لا تريد
من المستخدم
انتظار تحميله، إنما تريد أن
يقوم بعرضه في الحال.
ولذلك نقوم بتحميلة مُسبقًا.
نقوم بإعداد التحميل قبل عرض
الإعلان.
كيف نُنفذ ذلك.
حسنًا، لنبدأ بالنظر على فئة الإعلان
البيني.
هذه هي الفئة التي نستخدمها لتحميل وعرض
الإعلان البيني.
لذلك لديه طريقه تسمى "تحميل الإعلان".
ولكن تتطلب هذه الطريقة فقط تحميل الإعلان
وتجنب.
حظر مؤشر ترابط واجهة المستخدم،
سوف يرجع في الحال قبل تحميل الإعلان.
كيف نعرف أن الإعلان قد
تم تحميله؟
بوضع مستمع إعلان، يمكننا تنفيذ تحميل زائد
إلى طريقة "تحميل إعلان"
عند إنتهاء تحميل الإعلان البيني، سوف تسمى
هذه الطريقة،
ويمكننا عندئذٍ التقدم لاستدعاء عرض
الإعلان البيني.
لذلك، هذه هو التدفق الذي سنُنفذه
في تطبيقنا.
أيضًا، يجب أن تعرف أن الإعلان البيني
لديه طريقة تسمى "انتهاء التحميل".
إذا لم تكن مهتم بمعرفة
وقت انتهاء التحميل ،
يمكنك استدعاء "تحميل إعلان".
عندما يحين وقت عرض الإعلان،
تحقق من تحميل الإعلان.
إذا تم تحميله، يمكنك استدعاء
طريقة العرض.
خلاف ذلك، لن تعرض الإعلان على الإطلاق.
لنتحقق من التعليمة البرمجية لتنفيذ التدفق.
لنبدأ فتح ملف Java للنشاطات البينية.
الشئ الأول الذي نفذناه هنا أن أضفنا
حقل إعلان بيني يُسمى
البيني m، لا يوجد تغييرات في
طريقة الإنشاء.
لنذهب ونلقي نظرة على
طريقة التحميل البيني.
حقيقةً يجب أن توجد هذه لتعليمة البرمجية
لأننا قمنا بوضعها
في التمرين السابق.
لننظر إلى التعريفة البرمجية الأخرى.
أولاً، نقوم بإنشاء مثيل الإعلان البيني.
بعد ذلك، نضع معرف وحدة الإعلان.
ونضعه في هذه السلسلة التي ستُرجع
اختبار إعلانات بينية.
وهذه السلسلة، قمنا بتعريفها في ملف
سلاسل المصدر، لذلك يجب أن
نحصل عليها باستخدام (الحصول على مصادر).
احصل على سلسلة ثم معرف المصدر.
والآن، يوجد التدفق الذي تحدثنا عنه.
هنا، يمكنك مشاهدة أننا نضع المستمع
إلى الإعلان البيني.
لنتحدث عن ذلك قليلاً.
ولكن نضع مستمع هنا وبعد ذلك
يقع التنفيذ هنا.
الآن، نقوم بإنشاء طلب إعلان باستخدام
المُنشئ.
ثم نستدعي طريقة تحميل الإعلان في
مثيل الإعلان البيني لدينا.
تقديم طلب الإعلان كوسيطة، كما
شاهدنا من قبل.
هذه الطريقة سوف تبدأ عملية تحميل
الإعلان، لكن
سوف ترجع في الحال قبل
تحميل الإعلان.
حيث يحين وقت تشغيل مستمع
لدينا، كما تشاهدون،
سنقوم بإنشاء فئة مجمهولة الاسم هنا وفقًا
لفئة مستمع إعلان إعلام منبثق لدينا.
كما تشاهدون، سوف نقوم بتحميل زائد
لطريقة تحميل الإعلان.
ولأننا نضع المستمع هنا،
سوف يتم استدعاء هذه الطريقة عند
انتهاء تحميل الإعلان.
لذلك سوف نستدعي الطريقة الأصلية لدينا
التي ستعرض رسالة الإعلام
المنبثق، وهذا ما وضحناه في فئة
مستمع الإعلان البيني.
بعد ذلك، نضع نص تعطيل الزر لدينا للعرض
البيني.
وأيضًا نقوم بتمكين هذا الزر.
ويعني هذا أنه يمكن للمستخدم الضغط
على الزر.
وعندما يحدث ذلك،
سيتم استدعاء طريقة استدعاء
العرض البيني.
لذلك ما نقوم بتنفيذه هو
عرض بيني.
حسنًا، من خلال تحقق بسيط في حالة تحميل
العرض البيني،
وهذا قد يبدو تحقق غير ضروري،
لأننا نعلم بتحميل الإعلان منذ
استدعاء طريقة "تحميل إعلان".
ولكننا نُنفذه على أي حال.
حان وقت عرض الإعلان البيني،
ومتى يحدث، بالتأكيد سيتم عرض الإعلان
في وضع ملء الشاشة.
وبالنسبة لهذا الزر، نرجع إلى
الحالة السابقة،
وضع النص البيني غير جاهز وعند ذلك نقوم
بتعطيله.
وأخيرًا، نرجع إلى المستمع لدينا.
في حالة عدم القدرة على تحميل الإعلان، سيتم
استدعاء طريقة "فشل في تحميل الإعلان".
في هذه الحالة، مرةً أخرى، نعرض رسالة
الإعلام المنبثق
بعد ذلك، نضع سبب الخطأ في
نص الزر.
وهذا مانريده، هذه التعريفة البرمجية لدينا
لتنفيذ الإعلان البيني.
좋습니다. 우리가 틈새 광고를 전시하는 코드를 배우기 전에
이것에 대해서 조금 더 논의해 봅시다.
틈새 광고를 생각해볼 때 두 가지 중요한 사실이 존재합니다.
첫 번째는 틈새 광고의 포맷에 관한 것입니다.
아시다시피, 틈새 광고는 자이의 전체 스크린을 차지합니다.
그러므로 사용자가 앱에 관여하고 있을 때
그들을 방해하지 않는 것이 중요합니다.
그러므로 생각해야 할 첫 번째 중요한 사실은 틈새 광고를 전시하는 일입니다.
이 경우 앱에서 자동적으로 꺼지는 기능이 있습니다. 예를 들어서 게임에서 사용하는 레벨 사이의 브레이크입니다.
틈새 광고에서 두 번째 중요한 기능은
이것을 보여주기 이전에 광고의 로딩을 준비하는 일입니다.
왜 이것이 중요한 것일까요?
글쎄 틈새 광고를 로딩하는데 시간이 틉니다. 특히
만약 네트워크가 느리다면 그렇습니다.
틈새 광고를 전시하기 위한 때가 올 때, 우리는 사용자가 저기에 앉아서
로딩되기를 기다리게 하기를 원치 않습니다. 우리는 광고가 즉시 전시되기를 바랍니다.
그러므로 우리는 사전에 이것을 로드하여야 합니다.
우리는 광고를 보기 전에 로딩할 준비를 합니다.
그러므로 우리가 어떻게 저것을 하는 걸까요?
글쎄, 계층 틈새 광고를 보면서 시작해 봅시다.
이것이 로드하고 틈새 광고를 보여주기 위해 사용하는 계층입니다.
그러므로 이것이 loadAd라고 불리는 방식입니다.
그러나 이 방식은 로딩하고 UI 스레드가 블로킹되는 일을 막기 위해서
요청하는 방식입니다.
이것은 광고를 로딩하기 이전에 즉시 돌아올 것입니다.
그러므로 광고를 로드할 때 우리가 어덯게 그것을 아는 것을까요?
AdListener를 설정함으로써, 우리는 onAdLoaded 방식으로 오버로드를 할 수 있습니다.
그러므로 틈새 광고가 로딩을 마치면, 이 방식을 호출합니다. 그리고
우리는 틈새 광고를 보여주기 위해 호출을 이어나갈 수 있습니다.
그러므로 이것이 우리가 앱에서 구현할 플로우입니다.
우리는 틈새 광고에 loaded라고 불리는 광고가 있음을 알아야 합니다.
그러므로 만약 우리가 광고가 로드되었을 때를 정확히 아는데 관심이 없다면
단순이 loadAd를 호출해야 합니다.
그리고 광고를 보여주기 위한 시각이 올 때, 우리는 광고가 로드되었는지를 확인합니다.
만약 로드되면 우리는 보기 방식을 호출합니다.
그렇지 않다면 우리는 광고를 결코 보지 못합니다.
이제 리 플로우를 구현하기 위해서 코드를 확인해 봅시다.
틈새 광고 활동 자바 파일을 열어봅시다.
여기에서 우리가 한 첫 번째는 mInterstital이라고 부르는 틈새광고 영역을 더하는 것입니다.
onCreate 방식에 어떤 변화가 존재하지 않습니다.
그러므로 loadInsterstitial 방식을 봅시다.
이 코드는 이미 저기에 있어야 합니다. 왜냐하면 우리가 이전에 활동에서 이것을
설정하였기 때문입니다.
그러므로 다른 코드를 봅시다.
첫째로 우리는 틈새광고의 예시를 만들어야 합니다.
그 뒤에 우리는 AdUnitld를 세틍합니다.
그리고 우리는 이 스트링을 설정합니다. 저것으로 InterstitialAds 시험으로 되돌아올 것입니다.
그리고 이 스트링은, 우리가 리소스 스트링 파일에서 정의한 것입니다. 그러므로 우리는
getResources(), getString을 사용하고 그 뒤에 자원 ID를 사용합니다.
그리고 이제 이야기한 프로우로 되돌아옵니다.
여기에서 우리가 틈새 광고를 위해 리스너를 설정한다는 사실을 볼 수 있습니다.
잠시 이것에 대해서 이야기해봅시다.
그러나 우리는 여기에서 리스너를 설정합니다. 그리고 그 뒤에 아래에서 드럽을 수행합니다.
이제, 빌더를 사용하여서 AdRequest를 만듭니다.
그 뒤에 우리는 틈새광고 예시에서 loadAd 방식을 호출합니다.
논의로서 AdRequest를 제공하고 우리가 이전에 보았던 바와 같이
이 방식으로 로딩 과정을 시작할 것입니다. 그러나 우리는
광고를 로딩하기 이전에 즉시 돌아올 것입니다.
저것이 우리의 리스너가 역할을 하는 지점입니다. 그리고 볼 수 있는 바와 같이
우리는 ToastAdListener 계층에 근거하여서 익명의 계층을 만듭니다.
그리고 볼 수 있는 바처럼, 우리는 onAdLoaded 방식을 업로드합니다.
그러므로 우리가 여기에서 리스너를 설정하기 때문에
광고가 완전히 로딩될 때 이 방식을 호출할 것입니다.
그러므로 우리는 토스트 메시지를 전시할 parent method를 호출합니다.
이것이 우리가 ToastAdListener 계층에서 정의할 것이기 때문입니다.
그리고 그 뒤에 우리는 틈새 광고를 보기 위해서 disabled 버튼의 텍스트를 설정합니다.
그리고 우리는 또한 저 버튼을 이용할 수 있습니다.
저것은 사용자가 이제 이 버턴을 누를 수 있다는 사실을 의미합니다.
그리고 저 일이 발생할 때
showInterstitial 콜백 방식을 호출할 것입니다.
그러므로 우리가 할 것은 showInterstitial입니다.
글쎄, 단순한 확인으로 만약 틈새 광고를 로드한다면,
그리고 이것이 아마도 불필요한 확인인 듯 보인다면,
onAdLoaded를 호출하기 위해서 로드한 광고를 알게 됩니다.
그러나 우리는 어떤 식으로든 이 일을 하고 있습니다.
그리고 그 뒤에 실제로 틈새 광고를 보여주기 위한 때가 다가옵니다. 그리고
이 일이 발생할 때, 실제로 전체 화면 모드에서 광고를 전시할 것입니다.
그리고 버튼 때문에 우리는 이전의 명제로 돌아갑니다.
그리고 Interstitial Nor Ready라는 문구를 설정합니다. 글고 그 뒤에 그것을 가능하지 않게 만듭니다.
그리고 마지막으로, 리스너도 돌아갑니다.
만약 광고를 로드할 수 없다면, onAdFailedToLoad 방식을 호출할 것입니다.
다시, 저 상황에서 우리는 토스트 메시지를 보여주고
그 뒤에 버튼의 텍스트에 ErrorReason을 설정합니다.
저것이 다입니다. 저것이 우리가 틈새 광고에서 구현해야 하는 코드입니다.
Certo, antes de mostrar o código
para exibir um anúncio intersticial,
vamos conversar um pouco.
Porque existem duas questões importantes
para se pensar sobre anúncios intersticiais.
A primeira é sobre
o formato de um anúncio intersticial.
O anúncio intersticial consome toda a tela
do dispositivo.
Portanto, é importante
não interromper o usuário
quando estão ocupados com seu aplicativo.
A primeira questão importante
para pensar, é exibir anúncios intersticiais
nos intervalos naturais do aplicativo,
por exemplo, entre níveis em um jogo.
A segunda questão relacionada
a anúncios intersticiais seria
a preparação do carregamento antes da exibição.
Por que isso é importante?
Esse carregamento
pode ser demorado,
principalmente se a rede for lenta.
No momento da exibição do anúncio
intersticial, você não quer que o usuário
pare e fique esperando
o carregamento,
você quer uma exibição
imediata.
Portanto, fazemos o carregamento antecipado.
Preparamos o carregamento
antes de mostrar o anúncio.
Como fazemos isso?
Começamos olhando
a classe Interstitial Ad.
Essa é a classe que usamos para
carregar e mostrar um anúncio intersticial.
Ela tem um método chamado loadAd.
Mas esse método só
pede o carregamento do anúncio
e para evitar bloquear o thread de IU,
ele retornará imediatamente
antes que o anúncio tenha sido carregado.
Como sabemos então
quando o anúncio foi carregado?
Definindo um AdListener,
podemos carregar um método onAdLoaded.
Quando o anúncio intersticial
tiver sido carregado,
esse método será chamado,
e poderemos chamar
Show no anúncio intersticial.
Esse será o fluxo
que implementaremos em nosso aplicativo.
Além disso, o anúncio intersticial tem
um método chamado isLoaded.
Se você não estiver interessado em saber
exatamente quando o anúncio
foi carregado, basta chamar loadAd.
E no momento da exibição do anúncio
você verifica se ele foi carregado.
Se foi carregado,
você chama o método Show.
Caso contrário você não
mostra o anúncio.
Vamos ver o código
para implementar esse fluxo.
Vamos abrir
o arquivo InterstitialActivity Java.
A primeira coisa que fizemos aqui
foi adicionar um campo InterstitialAd
chamado mInterstital, não há
mudanças no método onCreate.
Vamos dar uma olhada
no método loadInsterstitial.
Esse código já deve estar aqui,
porque o definimos
no último exercício.
Vamos ver o outro código.
Primeiro, estamos criando uma
instância do InterstatialAd.
Depois, estamos definindo o AdUnitId.
E o definimos nesta string
que retornará o teste InterstitialAds.
E essa string, definimos
em nosso arquivo resource string,
e temos de pegá-la
usando getResources().getString
e depois o ID do recurso.
E agora vem o fluxo
que conversamos.
Você pode ver aqui que estamos
definindo o ouvinte para o anúncio intersticial.
Falaremos sobre isso
mais pra frente.
Mas estamos definindo um ouvinte aqui
e a execução vem aqui para baixo.
Agora vemos que estamos criando
um AdRequest usando o compilador.
E estamos chamando o método loadAd
em nossa instância InterstitialAd.
Fornecendo o AdRequest como argumento,
e, como vimos antes,
o método começará
o carregamento do anúncio,
mas retornará imediatamente
antes do final do carregamento.
É onde o ouvinte entra
em ação, e como se vê,
estamos criando uma classe anônima aqui
com base em nossa classe ToastAdListener.
Como se vê,
estamos carregando o método onAdLoaded.
Como estamos definindo
o ouvinte aqui,
o método será chamado quando
o anúncio tiver sido carregado.
Chamamos nosso método pai
que exibirá a mensagem de notificação,
já que foi o que definimos
na classe ToastAdListener.
E definimos o texto de botão
de desativação como Show Interstitial.
E também habilitamos o botão.
Isso significa que o usuário
pode agora pressionar o botão.
E quando isso acontecer,
o método showInterstitial callback
será chamado.
O que estamos fazendo
no showInterstitial.
Estamos verificando
se o anúncio intersticial foi carregado,
e isso pode parecer
desnecessário,
já que sabemos que o anúncio foi carregado
já que onAdLoaded foi chamado.
Mas estamos fazendo isso de alguma forma.
E chegou o momento para de fato
exibir o anúncio intersticial.
E quando isso acontece, o anúncio
será de fato exibido
no modo tela cheia.
E para o botão,
voltamos para o status anterior,
definindo o texto Interstitial Not Ready
e desativando-o.
E finalmente,
voltando ao nosso ouvinte.
Se o anúncio não tiver sido carregado,
o método onAdFailedToLoad será chamado.
Nesse caso, novamente,
mostramos a mensagem de notificação
e definimos o ErrorReason
para o texto do botão.
Isso é tudo, esse é o código
para implementar o anúncio intersticial.
好,在了解显示插播式广告
的代码之前,
我们先简略讨论一下插播式广告。
使用插播式广告时,
有两件重要的事情需要考虑。
第一是
插播式广告的格式。
我们知道,插播式广告
会占用设备的整个屏幕。
因此,在用户专注使用
您的应用时,不要去打扰他,
这一点很重要。
所以,要考虑的第一件重要的事情,
是在应用的自然间隙
显示插播式广告,
例如在游戏的两个等级之间显示广告。
插播式广告的第二件重要事情,
是在显示插播式广告之前
准备加载。
为什么这件事很重要?
如果网络很慢,
加载插播式广告会
耗费很长时间。
到了要显示插播式广告
的时候,您不希望
用户坐等广告加载,
您希望广告能立即显示。
因此,我们会预先加载。
在显示广告之前,
我们会准备加载。
那么怎样准备呢?
首先,我们看一下
插播式广告类。
该类用于
加载与显示插播式广告。
它包含名为 loadAd 的方法,
但是该方法只会请求
加载广告,为了避免
阻止 UI 线程,
在广告加载之前,
该方法会立即返回。
那么我们怎么知道
广告什么时候加载呢?
通过设置 AdListener,
我们可以重载 onAdLoaded 方法。
在插播式广告完成加载时,
会调用此方法,
这样我们就可以调用
插播式广告的 show 方法了。
这就是我们将在应用中
实施的流程。
您还应该知道,
插播式广告包含名为 isLoaded 的方法。
如果您对确切了解
加载广告的时间没兴趣,
那么只调用 loadAd 就行了。
到了要显示广告的时候,
您可以检查是否已加载广告。
如果已经加载,
您可以调用 show 方法。
否则,完全不会
显示广告。
现在我们来检查
实施这个流程的代码。
打开
InterstitialActivity Java 文件。
首先,我们添加了名为 mInterstital
的 InterstitialAd 字段,
对 onCreate 方法
不做任何更改。
接下来我们看一下
loadInsterstitial 方法。
这段代码应该已经存在,
因为我们在之前的练习中
已经设置过。
然后我们看一下其他代码。
首先,我们将创建
InterstatialAd 的实例。
然后设置 AdUnitId。
我们将其设置为 this 字符串,
该字符串将返回测试 InterstitialAds。
我们已经在资源字符串文件中
定义了 this 字符串,因此必须
依次使用 getResources().getString
与资源 ID 来获得该字符串。
现在来看一下
我们谈论的流程。
在这里您可以看到,我们设置了
InterstitialAd 的侦听器。
我们稍后会谈论这个侦听器。
先在这里设置侦听器,
然后在这里执行。
现在您可以看到,我们
使用生成器创建 AdRequest。
然后在 InterstitialAd 实例上
调用 loadAd。
以自变量的形式提供 AdRequest,
我们之前曾知道,
该方法将启动
广告加载流程,但是
在广告加载之前,
该方法会立即返回。
在这里,侦听器开始运行,
您可以看到,
我们根据 ToastAdListener 类,
在这里创建匿名类。
您可以看到,
我们重载 onAdLoaded 方法。
由于我们在这里
设置了侦听器,
因此在完成广告加载时,
将调用该方法。
我们调用会显示烤面包消息
的父方法,
在此之后是我们在
ToastAdListener 类中定义的内容。
然后,我们将禁用按钮的文本
设置为“显示插播式广告”。
我们还启用了该按钮。
这意味着用户
现在可以按下该按钮。
按下该按钮时,
将调用 showInterstitial
回调方法。
因此会执行
showInterstitial。
简单检查一下
是否已经加载插播式广告,
这似乎是不必要的检查,
因为我们知道
自调用 onAdLoaded 后已加载广告,
但是我们还是要检查一下。
随后,真正显示插播式广告
的时候到了,
显示广告时,
实际上会以全屏模式显示。
对于按钮,
我们回到之前的状态,
将文本设置为“插播式广告未准备就绪”,
然后禁用。
最后,回到侦听器。
如果无法加载广告,将调用
onAdFailedToLoad 方法。
在这个示例中,我们会再次
显示烤面包的消息,
然后将 ErrorReason
设置为按钮的文本。
就是这些,这就是我们
实施插播式广告的代码。