Quảng cáo xen kẽ là quảng cáo toàn màn hình, che phủ giao diện của ứng dụng lưu trữ.
Quảng cáo này thường xuất hiện ở các điểm chuyển tiếp tự nhiên trong quy trình hoạt động của ứng dụng,
chẳng hạn như giữa các hoạt động hoặc trong thời gian tạm dừng giữa các cấp độ của trò chơi.
Khi một ứng dụng hiển thị quảng cáo xen kẽ, người dùng sẽ có thể chọn nhấn vào
quảng cáo và tiếp tục chuyển đến trang đích của quảng cáo đó hoặc đóng quảng cáo và quay lại ứng dụng.
Nghiên cứu điển hình.
Tài liệu hướng dẫn này giải thích cách tích hợp quảng cáo xen kẽ vào một ứng dụng
Android.
Điều kiện tiên quyết
SDK quảng cáo trên thiết bị di động của Google phiên bản 19.7.0 trở lên.
Làm theo Hướng dẫn bắt đầu sử dụng
để nhập SDK quảng cáo trên thiết bị di động của Google và cập nhật tệp kê khai Android của bạn.
Luôn kiểm tra bằng quảng cáo thử nghiệm
Khi tạo và thử nghiệm ứng dụng, hãy đảm bảo rằng bạn sử dụng quảng cáo thử nghiệm thay vì
quảng cáo đang chạy thực tế. Chúng tôi sẽ tạm ngưng tài khoản của bạn nếu bạn không thực hiện việc này.
Cách đơn giản nhất để tải quảng cáo thử nghiệm là sử dụng mã đơn vị quảng cáo thử nghiệm
dành riêng cho quảng cáo xen kẽ trên Android:
ca-app-pub-3940256099942544/1033173712
Mã này được định cấu hình đặc biệt để trả về quảng cáo thử nghiệm cho mọi yêu cầu và bạn
có thể sử dụng mã này trong ứng dụng của mình khi lập trình, chạy thử nghiệm và gỡ lỗi. Bạn chỉ cần nhớ
thay thế mã này bằng mã đơn vị quảng cáo của mình trước khi xuất bản ứng dụng.
Để biết thêm thông tin về cách hoạt động của quảng cáo thử nghiệm của SDK quảng cáo trên thiết bị di động, hãy xem bài viết
Quảng cáo thử nghiệm.
Tải một quảng cáo
Để tải một quảng cáo xen kẽ, hãy gọi phương thức InterstitialAd
tĩnh
load() và nhập
InterstitialAdLoadCallback để nhận quảng cáo đã tải hoặc bất kỳ lỗi nào có thể xảy ra. Xin lưu ý rằng giống như các lệnh gọi lại tải định dạng khác,
InterstitialAdLoadCallback tận dụng
LoadAdError để cung cấp thông tin chi tiết về lỗi có độ trung thực cao hơn.
FullScreenContentCallback xử lý các sự kiện liên quan đến việc hiển thị
InterstitialAd của bạn. Trước khi hiển thị InterstitialAd, bạn hãy nhớ đặt
lệnh gọi lại:
Quảng cáo xen kẽ nên được hiển thị tại các điểm tạm dừng tự nhiên trong quy trình hoạt động của ứng dụng.
Bạn nên thiết lập để quảng cáo xuất hiện xen kẽ giữa các cấp độ của trò chơi hoặc sau khi người dùng hoàn thành một nhiệm vụ.
Để hiển thị một quảng cáo xen kẽ, hãy sử dụng phương thức
show().
Cân nhắc xem quảng cáo xen kẽ có phải là loại quảng cáo thích hợp cho ứng dụng của bạn hay không.
Quảng cáo xen kẽ hoạt động hiệu quả nhất trong những ứng dụng có các điểm chuyển tiếp tự nhiên.
Hãy tạo ra một điểm chuyển tiếp khi kết thúc một thao tác trong ứng dụng,
chẳng hạn như chia sẻ một hình ảnh hoặc hoàn tất một cấp độ trò chơi. Do người dùng mong đợi một khoảng nghỉ tạm thời,
nên bạn dễ dàng hiển thị một quảng cáo xen kẽ mà không làm gián đoạn
trải nghiệm của họ. Hãy nhớ cân nhắc thời điểm mà bạn muốn hiển thị quảng cáo xen kẽ trong
quy trình hoạt động của ứng dụng và khả năng phản hồi của người dùng.
Nhớ tạm dừng hành động khi hiển thị quảng cáo xen kẽ.
Có nhiều loại quảng cáo xen kẽ khác nhau: văn bản, hình ảnh, video và các loại khác. Điều quan trọng là phải đảm bảo rằng khi ứng dụng của bạn hiển thị quảng cáo xen kẽ, ứng dụng cũng sẽ tạm ngừng sử dụng một số tài nguyên để cho phép quảng cáo tận dụng các tài nguyên đó. Ví dụ: khi bạn thực hiện lệnh gọi để hiển thị
một quảng cáo xen kẽ, hãy nhớ tạm dừng phát mọi âm thanh trên ứng dụng của mình.
Cho phép đủ thời gian tải.
Bạn phải đảm bảo hiển thị quảng cáo xen kẽ
tại thời điểm phù hợp, nhưng cũng phải đảm bảo người dùng không phải
đợi quảng cáo tải. Việc tải quảng cáo trước bằng cách gọi
load() trước khi bạn dự định gọi
show() có thể đảm bảo rằng ứng dụng của bạn có quảng cáo xen kẽ đã tải đầy đủ
và sẵn sàng hiển thị tại thời điểm thích hợp.
Đừng hiển thị quá nhiều quảng cáo cho người dùng.
Mặc dù việc tăng tần suất hiển thị quảng cáo xen kẽ trong ứng dụng có thể là
một cách hay để tăng doanh thu, nhưng việc đó cũng có thể làm suy giảm trải nghiệm người dùng
và làm giảm tỷ lệ nhấp. Hãy đảm bảo rằng người dùng không bị gián đoạn thường xuyên
vì điều đó sẽ khiến họ không còn hứng thú khi sử dụng ứng dụng của bạn nữa.
Mã nguồn
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()
}
}