如果發布商有意採用 Google Mobile Ads SDK (Beta 版) 整合應用程式開啟頁面廣告,歡迎參閱本指南。
應用程式開啟頁面廣告是一種特殊廣告格式,適合想藉由應用程式載入畫面賺取收益的發布商。應用程式開啟頁面廣告會在使用者將應用程式切換至前景時出現,而且使用者隨時可以關閉。
應用程式開啟頁面廣告會自動在一小塊區域內顯示品牌資訊,使用者一看就知道自己並未離開應用程式。以下是這類廣告的範例:
必要條件
- 完成入門指南的步驟。
一律使用測試廣告進行測試
建構及測試應用程式時,請務必使用測試廣告,而非實際的正式廣告。否則帳戶可能會遭到停權。
載入測試廣告最簡單的方法,是使用應用程式開啟頁面廣告專用的測試廣告單元 ID:
ca-app-pub-3940256099942544/9257395921
這個 ID 經過特別設定,每次請求都會傳回測試廣告。在編寫程式碼、測試及偵錯階段,您可以在應用程式中自由使用,發布應用程式前,請務必用自己的廣告單元 ID 替換這類 ID。
如要進一步瞭解 Google Mobile Ads SDK (Beta 版) 測試廣告的運作方式,請參閱「啟用測試廣告」。
擴充 Application 類別
建立延伸自 Application
類別的新類別,這樣就能根據生命週期階段,管理與應用程式狀態 (而不是單一 Activity
) 相關聯的廣告:
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 SDK on a background thread.
MobileAds.initialize(
MyApplication.this,
new InitializationConfig.Builder(APP_ID).build(),
initializationStatus -> {});
})
.start();
}
}
這個架構可供您稍後註冊應用程式前景事件。
接著,將下列程式碼加到 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 make sure 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
}
}
現在您有了公用程式類別,可以在 MyApplication
類別中執行個體化:
Java
public class MyApplication extends Application {
private AppOpenAdManager appOpenAdManager;
@Override
public void onCreate() {
super.onCreate();
new Thread(
() -> {
// Initialize Google Mobile Ads SDK (beta) on a background thread.
MobileAds.initialize(this, initializationStatus -> {});
})
.start();
appOpenAdManager = new AppOpenAdManager(this);
}
}
Kotlin
class MyApplication : Application() {
private lateinit var appOpenAdManager: AppOpenAdManager
override fun onCreate() {
super.onCreate()
val backgroundScope = CoroutineScope(Dispatchers.IO)
backgroundScope.launch {
// Initialize Google Mobile Ads SDK (beta) on a background thread.
MobileAds.initialize(this@MyApplication) {}
}
appOpenAdManager = AppOpenAdManager()
}
}
如要使用 AppOpenAdManager
,請在單例模式 MyApplication
執行個體呼叫公開的包裝函式方法。Application
類別會與程式碼其餘部分互動,並將廣告載入及顯示工作委派給管理工具。
載入廣告
下一步是填入 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);
}
});
}
將 AD_UNIT_ID 替換為廣告單元 ID。
顯示廣告
如要導入應用程式開啟頁面廣告,最常見的做法是在接近應用程式啟動時,就嘗試放送廣告。如果廣告尚未就緒,則顯示應用程式內容,並預先載入另一則廣告,待下次應用程式開啟時放送。如需導入範例,請參閱應用程式開啟頁面廣告指南。
下列程式碼可顯示並緊接著重新載入廣告:
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 make sure 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 make sure 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
執行情境,如要追蹤使用中的最新活動,請註冊並導入 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
的參照,然後用於顯示應用程式開啟頁面廣告。
監聽應用程式前景事件
如要監聽應用程式前景事件,請按照下列步驟操作:
將程式庫加到 Gradle 檔案
如要接收應用程式前景事件的通知,須註冊 DefaultLifecycleObserver
。將依附元件加到應用程式層級的建構檔:
Kotlin
dependencies { implementation("com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk:0.21.0-beta01") implementation("androidx.lifecycle:lifecycle-process:2.8.3") }
Groovy
dependencies { implementation 'com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk:0.21.0-beta01' 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 Mobile Ads SDK (Beta 版)。