本指南面向希望使用 Google 移动广告 SDK 集成开屏广告的发布商。
开屏广告是一种特殊的广告格式,适合希望通过应用加载页面创收的发布商。开屏广告在用户将您的应用切换为在前台运行时展示,用户可随时关闭。
开屏广告会自动在一个较小的区域内展示您的品牌信息,让用户知道他们是在您的应用中。以下是一个开屏广告示例:
前提条件
- 完成入门指南。
务必用测试广告进行测试
在构建和测试应用时,请确保使用的是测试广告,而不是实际投放的广告。否则,可能会导致您的账号被中止。
对于开屏广告,加载测试广告最简便的方法就是使用下面的测试专用广告单元 ID:
/21775744923/example/app-open
该测试广告单元 ID 已经过专门配置,可确保每个请求返回的都是测试广告。您可以在自己应用的编码、测试和调试过程中随意使用该测试广告单元 ID。只需确保您会在发布应用前用自己的广告单元 ID 替换该测试广告单元 ID 即可。
如需详细了解 Google 移动广告 SDK 的测试广告如何运作,请参阅启用测试广告。
扩展 Application 类
创建一个扩展 Application
类的新类,并添加以下代码,以便在应用启动时初始化 Google 移动广告 SDK。
Kotlin
/** Application class that initializes, loads and show ads when activities change states. */
class MyApplication : Application() {
override fun onCreate() {
super<Application>.onCreate()
CoroutineScope(Dispatchers.IO).launch {
// Initialize the Mobile Ads SDK synchronously on a background thread.
MobileAds.initialize(this@MyApplication, InitializationConfig.Builder(APP_ID).build()) {}
}
}
private companion object {
// Sample AdMob App ID.
const val APP_ID = "ca-app-pub-3940256099942544~3347511713"
}
}
Java
/** Application class that initializes, loads and show ads when activities change states. */
public class MyApplication extends Application {
// Sample AdMob App ID.
private static final String APP_ID = "ca-app-pub-3940256099942544~3347511713";
@Override
public void onCreate() {
super.onCreate();
new Thread(
() -> {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(
MyApplication.this,
new InitializationConfig.Builder(APP_ID).build(),
initializationStatus -> {});
})
.start();
}
}
这会初始化 SDK 并提供一个框架,供您稍后在其中注册应用前台事件。
接下来,将以下代码添加到您的 AndroidManifest.xml
中:
<!-- TODO: Update to reference your actual package name. -->
<application
android:name="com.google.android.gms.example.appopendemo.MyApplication" ...>
...
</application>
实现实用程序组件
您的广告应该要快速展示,因此最好先加载广告,以备需要展示时使用。这样一来,用户进入您的应用后,广告便可以立即展示。
实现实用工具组件 AppOpenAdManager
,以便在需要展示广告之前发出广告请求。
Kotlin
/**
* Interface definition for a callback to be invoked when an app open ad is complete (i.e. dismissed
* or fails to show).
*/
fun interface OnShowAdCompleteListener {
fun onShowAdComplete()
}
/** Singleton object that loads and shows app open ads. */
object AppOpenAdManager {
private var appOpenAd: AppOpenAd? = null
private var isLoadingAd = false
var isShowingAd = false
/**
* Load an ad.
*
* @param context a context used to perform UI-related operations (e.g. display Toast messages).
* Showing the app open ad itself does not require a context.
*/
fun loadAd(context: Context) {
// We will implement this later.
}
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad.
* @param onShowAdCompleteListener the listener to be notified when an app open ad is complete.
*/
fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener?) {
// We will implement this later.
}
/** Check if ad exists and can be shown. */
private fun isAdAvailable(): Boolean {
return appOpenAd != null
}
}
Java
/** Singleton object that loads and shows app open ads. */
public class AppOpenAdManager {
/**
* Interface definition for a callback to be invoked when an app open ad is complete (i.e.
* dismissed or fails to show).
*/
public interface OnShowAdCompleteListener {
void onShowAdComplete();
}
private static AppOpenAdManager instance;
private AppOpenAd appOpenAd;
private boolean isLoadingAd = false;
private boolean isShowingAd = false;
/** Keep track of the time an app open ad is loaded to ensure you don't show an expired ad. */
private long loadTime = 0;
public static synchronized AppOpenAdManager getInstance() {
if (instance == null) {
instance = new AppOpenAdManager();
}
return instance;
}
/**
* Load an ad.
*
* @param context a context used to perform UI-related operations (e.g. display Toast messages).
* Loading the app open ad itself does not require a context.
*/
public void loadAd(@NonNull Context context) {
// We will implement this later.
}
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad.
* @param onShowAdCompleteListener the listener to be notified when an app open ad is complete.
*/
public void showAdIfAvailable(
@NonNull Activity activity, @Nullable OnShowAdCompleteListener onShowAdCompleteListener) {
// We will implement this later.
}
/** Check if ad exists and can be shown. */
private boolean isAdAvailable() {
return appOpenAd != null
}
}
加载广告
下一步是填充 loadAd()
方法并处理广告加载回调。
Kotlin
/**
* Load an ad.
*
* @param context a context used to perform UI-related operations (e.g. display Toast messages).
* Loading the app open ad itself does not require a context.
*/
fun loadAd(context: Context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
Log.d(Constant.TAG, "App open ad is either loading or has already loaded.")
return
}
isLoadingAd = true
AppOpenAd.load(
AdRequest.Builder(AppOpenFragment.AD_UNIT_ID).build(),
object : AdLoadCallback<AppOpenAd> {
/**
* Called when an app open ad has loaded.
*
* @param ad the loaded app open ad.
*/
override fun onAdLoaded(ad: AppOpenAd) {
// Called when an ad has loaded.
appOpenAd = ad
isLoadingAd = false
Log.d(Constant.TAG, "App open ad loaded.")
}
/**
* Called when an app open ad has failed to load.
*
* @param loadAdError the error.
*/
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
isLoadingAd = false
Log.w(Constant.TAG, "App open ad failed to load: $loadAdError")
}
},
)
}
Java
/**
* Load an ad.
*
* @param context a context used to perform UI-related operations (e.g. display Toast messages).
* Loading the app open ad itself does not require a context.
*/
public void loadAd(@NonNull Context context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
Log.d(Constant.TAG, "App open ad is either loading or has already loaded.");
return;
}
isLoadingAd = true;
AppOpenAd.load(
new AdRequest.Builder(AppOpenFragment.AD_UNIT_ID).build(),
new AdLoadCallback<AppOpenAd>() {
@Override
public void onAdLoaded(@NonNull AppOpenAd ad) {
appOpenAd = ad;
isLoadingAd = false;
Log.d(Constant.TAG, "App open ad loaded.");
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
isLoadingAd = false;
Log.w(Constant.TAG, "App open ad failed to load: " + loadAdError);
}
});
}
展示广告并处理全屏回调事件
最常见的开屏广告实现方式是尝试在应用启动时附近展示开屏广告,如果广告尚未准备就绪,则启动应用内容,并预加载另一个广告以便在下次应用打开时展示。如需查看实现示例,请参阅开屏广告指南。
以下代码演示了如何展示广告以及随后重新加载广告:
Kotlin
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad.
* @param onShowAdCompleteListener the listener to be notified when an app open ad is complete.
*/
fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener?) {
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(Constant.TAG, "App open ad is already showing.")
onShowAdCompleteListener?.onShowAdComplete()
return
}
// If the app open ad is not available yet, invoke the callback.
if (!isAdAvailable()) {
Log.d(Constant.TAG, "App open ad is not ready yet.")
onShowAdCompleteListener?.onShowAdComplete()
return
}
appOpenAd?.adEventCallback =
object : AppOpenAdEventCallback {
override fun onAdShowedFullScreenContent() {
Log.d(Constant.TAG, "App open ad showed.")
}
override fun onAdDismissedFullScreenContent() {
Log.d(Constant.TAG, "App open ad dismissed.")
appOpenAd = null
isShowingAd = false
onShowAdCompleteListener?.onShowAdComplete()
loadAd(activity)
}
override fun onAdFailedToShowFullScreenContent(
fullScreenContentError: FullScreenContentError
) {
appOpenAd = null
isShowingAd = false
Log.w(Constant.TAG, "App open ad failed to show: $fullScreenContentError")
onShowAdCompleteListener?.onShowAdComplete()
loadAd(activity)
}
override fun onAdImpression() {
Log.d(Constant.TAG, "App open ad recorded an impression.")
}
override fun onAdClicked() {
Log.d(Constant.TAG, "App open ad recorded a click.")
}
}
isShowingAd = true
appOpenAd?.show(activity)
}
Java
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad.
* @param onShowAdCompleteListener the listener to be notified when an app open ad is complete.
*/
public void showAdIfAvailable(
@NonNull Activity activity, @Nullable OnShowAdCompleteListener onShowAdCompleteListener) {
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(Constant.TAG, "App open ad is already showing.");
if (onShowAdCompleteListener != null) {
onShowAdCompleteListener.onShowAdComplete();
}
return;
}
// If the app open ad is not available yet, invoke the callback.
if (!isAdAvailable()) {
Log.d(Constant.TAG, "App open ad is not ready yet.");
if (onShowAdCompleteListener != null) {
onShowAdCompleteListener.onShowAdComplete();
}
return;
}
appOpenAd.setAdEventCallback(
new AppOpenAdEventCallback() {
@Override
public void onAdShowedFullScreenContent() {
Log.d(Constant.TAG, "App open ad shown.");
}
@Override
public void onAdDismissedFullScreenContent() {
Log.d(Constant.TAG, "App open ad dismissed.");
appOpenAd = null;
isShowingAd = false;
if (onShowAdCompleteListener != null) {
onShowAdCompleteListener.onShowAdComplete();
}
loadAd(activity);
}
@Override
public void onAdFailedToShowFullScreenContent(
@NonNull FullScreenContentError fullScreenContentError) {
appOpenAd = null;
isShowingAd = false;
Log.w(Constant.TAG, "App open ad failed to show: " + fullScreenContentError);
if (onShowAdCompleteListener != null) {
onShowAdCompleteListener.onShowAdComplete();
}
loadAd(activity);
}
@Override
public void onAdImpression() {
Log.d(Constant.TAG, "App open ad recorded an impression.");
}
@Override
public void onAdClicked() {
Log.d(Constant.TAG, "App open ad recorded a click.");
}
});
isShowingAd = true;
appOpenAd.show(activity);
}
AppOpenAdEventCallback
会处理各种事件,例如广告展示、广告无法展示或者用户关闭广告。
考虑广告有效期
为确保您不会展示过期的广告,请在 AppOpenAdManager
中添加一个方法,用于检查广告引用加载后经过了多长时间。然后,使用该方法检查广告是否仍然有效。
Kotlin
object AppOpenAdManager {
// ...
/** Keep track of the time an app open ad is loaded to ensure you don't show an expired ad. */
private var loadTime: Long = 0;
/**
* Load an ad.
*
* @param context a context used to perform UI-related operations (e.g. display Toast messages).
* Loading the app open ad itself does not require a context.
*/
fun loadAd(context: Context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
Log.d(Constant.TAG, "App open ad is either loading or has already loaded.")
return
}
isLoadingAd = true
AppOpenAd.load(
AdRequest.Builder(AppOpenFragment.AD_UNIT_ID).build(),
object : AdLoadCallback<AppOpenAd> {
/**
* Called when an app open ad has loaded.
*
* @param ad the loaded app open ad.
*/
override fun onAdLoaded(ad: AppOpenAd) {
// Called when an ad has loaded.
appOpenAd = ad
isLoadingAd = false
loadTime = Date().time
Log.d(Constant.TAG, "App open ad loaded.")
}
/**
* Called when an app open ad has failed to load.
*
* @param loadAdError the error.
*/
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
isLoadingAd = false
Log.w(Constant.TAG, "App open ad failed to load: $loadAdError")
}
},
)
}
// ...
/** Check if ad was loaded more than n hours ago. */
private fun wasLoadTimeLessThanNHoursAgo(numHours: Long): Boolean {
val dateDifference: Long = Date().time - loadTime
val numMilliSecondsPerHour: Long = 3600000
return dateDifference < numMilliSecondsPerHour * numHours
}
/** Check if ad exists and can be shown. */
private fun isAdAvailable(): Boolean {
// App open ads expire after four hours. Ads rendered more than four hours after request time
// are no longer valid and may not earn revenue.
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4)
}
}
Java
public class AppOpenAdManager {
// ...
/** Keep track of the time an app open ad is loaded to ensure you don't show an expired ad. */
private long loadTime = 0;
/**
* Load an ad.
*
* @param context a context used to perform UI-related operations (e.g. display Toast messages).
* Loading the app open ad itself does not require a context.
*/
public void loadAd(@NonNull Context context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
Log.d(Constant.TAG, "App open ad is either loading or has already loaded.");
return;
}
isLoadingAd = true;
AppOpenAd.load(
new AdRequest.Builder(AppOpenFragment.AD_UNIT_ID).build(),
new AdLoadCallback<AppOpenAd>() {
@Override
public void onAdLoaded(@NonNull AppOpenAd ad) {
appOpenAd = ad;
isLoadingAd = false;
loadTime = new Date().getTime();
Log.d(Constant.TAG, "App open ad loaded.");
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
isLoadingAd = false;
Log.w(Constant.TAG, "App open ad failed to load: " + loadAdError);
}
});
}
// ...
/** Check if ad was loaded more than n hours ago. */
private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
long dateDifference = new Date().getTime() - loadTime;
long numMilliSecondsPerHour = 3600000L;
return dateDifference < numMilliSecondsPerHour * numHours;
}
/** Check if ad exists and can be shown. */
private boolean isAdAvailable() {
// App open ads expire after four hours. Ads rendered more than four hours after request time
// are no longer valid and may not earn revenue.
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}
}
跟踪当前 activity
您需要 Activity
上下文才能展示广告。如需跟踪用户使用的最新 activity,请注册并实现 Application.ActivityLifecycleCallbacks
。
Kotlin
class MyApplication : Application(), Application.ActivityLifecycleCallbacks {
private var currentActivity: Activity? = null
override fun onCreate() {
super<Application>.onCreate()
registerActivityLifecycleCallbacks(this)
}
/** ActivityLifecycleCallback methods. */
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
override fun onActivityStarted(activity: Activity) {
currentActivity = activity
}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
override fun onActivityDestroyed(activity: Activity) {}
// ...
}
Java
public class MyApplication extends Application
implements Application.ActivityLifecycleCallbacks {
private Activity currentActivity;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
/** ActivityLifecycleCallback methods. */
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {}
@Override
public void onActivityStarted(@NonNull Activity activity) {
currentActivity = activity;
}
@Override
public void onActivityResumed(@NonNull Activity activity) {}
@Override
public void onActivityPaused(@NonNull Activity activity) {}
@Override
public void onActivityStopped(@NonNull Activity activity) {}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {}
// ...
}
registerActivityLifecycleCallbacks
可用于监听所有 Activity
事件。通过监听 activity 启动和销毁的时间,您可以跟踪对当前 Activity
的引用,然后根据该 activity 展示您的开屏广告。
监听应用前台事件
将库添加到 gradle 文件中
如需接收应用前台事件的通知,您需要注册 DefaultLifecycleObserver
。将其依赖项添加到应用级 build 文件中:
Kotlin
dependencies { implementation("com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk:0.17.0-alpha01") implementation("androidx.lifecycle:lifecycle-process:2.8.3") }
Groovy
dependencies { implementation 'com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk:0.17.0-alpha01' implementation 'androidx.lifecycle:lifecycle-process:2.8.3' }
实现生命周期观察器接口
您可以通过实现 DefaultLifecycleObserver
接口来监听前台事件。
实现 onStart
事件以展示开屏广告。
Kotlin
class MyApplication :
Application(), Application.ActivityLifecycleCallbacks, DefaultLifecycleObserver {
private var currentActivity: Activity? = null
override fun onCreate() {
super<Application>.onCreate()
registerActivityLifecycleCallbacks(this)
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
/**
* DefaultLifecycleObserver method that shows the app open ad when the app moves to foreground.
*/
override fun onStart(owner: LifecycleOwner) {
currentActivity?.let { activity ->
AppOpenAdManager.showAdIfAvailable(activity, null)
}
}
// ...
}
Java
public class MyApplication extends Application
implements Application.ActivityLifecycleCallbacks, DefaultLifecycleObserver {
private Activity currentActivity;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
/**
* DefaultLifecycleObserver method that shows the app open ad when the app moves to foreground.
*/
@Override
public void onStart(@NonNull LifecycleOwner owner) {
if (currentActivity == null) {
return;
}
AppOpenAdManager.getInstance().showAdIfAvailable(currentActivity, null);
}
// ...
}
冷启动和加载屏幕
到现在为止,本文档都假定您仅在以下情况下展示开屏广告:用户将在内存中挂起的应用切换为在前台运行。用户启动您的应用,但该应用之前未在内存中挂起,这种情况就称为“冷启动”。
例如,用户首次打开您的应用便属于冷启动。对于冷启动,您没有之前已加载的开屏广告可供立即展示。请求广告和收到相应广告之间的延迟会导致出现以下情况:用户能够暂时使用您的应用,然后突然看到一条无关广告。应避免出现这种情况,因为这会导致用户体验不佳。
在冷启动时使用开屏广告的首选方法是,使用加载屏幕来加载游戏或应用素材资源,并且仅在加载屏幕展示广告。如果您的应用已加载完毕,并且用户已经看到应用的主要内容,则不要展示广告。
最佳做法
借助开屏广告,您可以在用户首次启动应用和切换应用期间通过应用的加载屏幕变现,不过,还请务必考虑一些最佳做法,以便保持良好的应用使用体验。最佳做法如下所示:
- 在用户使用几次您的应用后展示第一个开屏广告。
- 利用用户等待您应用加载的那段时间,展示开屏广告。
- 如果有加载屏幕位于开屏广告之下,并且加载屏幕在用户关闭广告之前已加载完毕,您可能需要通过
onAdDismissedFullScreenContent()
方法关闭加载屏幕。
示例
下载并运行示例应用,演示如何使用新一代 Google 移动广告 SDK。