本指南適用於使用 Google Cloud 控制台 Mobile Ads SDK
應用程式開啟頁面廣告是一種特殊廣告格式,適合希望藉由應用程式載入畫面賺取收益的發布商。應用程式開啟頁面廣告可以隨時關閉, 要在使用者將應用程式移至前景時顯示。
應用程式開啟頁面廣告會自動顯示一小塊品牌區域,方便使用者認出他們 以下是應用程式開啟頁面廣告的範例:
必要條件
- 完成入門指南。
一律使用測試廣告進行測試
建構及測試應用程式時,請務必使用測試廣告,而非 現場及正式環境廣告否則可能導致帳戶遭到停權。
要載入測試廣告,最簡單的方法就是使用應用程式專用的測試廣告單元 ID 開啟廣告:
ca-app-pub-3940256099942544/9257395921
這項機制經過特別設定,可針對每個請求傳回測試廣告 在您的程式設計、測試和偵錯時,可以免費使用應用程式。只需製作 務必先用廣告單元 ID 取代廣告單元,再發布應用程式。
若要進一步瞭解 Google Mobile Ads SDK 測試廣告的運作方式,請參閱: 啟用測試廣告。
擴充應用程式類別
建立擴充 Application
類別的新類別,然後新增以下內容
程式碼,在應用程式啟動時初始化 Google Mobile Ads SDK。
Java
/** Application class that initializes, loads and show ads when activities change states. */
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
new Thread(
() -> {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this, initializationStatus -> {});
})
.start();
}
}
Kotlin
/** Application class that initializes, loads and show ads when activities change states. */
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
val backgroundScope = CoroutineScope(Dispatchers.IO)
backgroundScope.launch {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this@MyApplication) {}
}
}
}
這個動作會初始化 SDK,並提供稍後會註冊的架構 用於應用程式前景事件。
接著,請在 AndroidManifest.xml
中加入下列程式碼:
<!-- TODO: Update to reference your actual package name. -->
<application
android:name="com.google.android.gms.example.appopendemo.MyApplication" ...>
...
</application>
實作公用程式元件
您的廣告會快速顯示,因此建議您在需要 顯示。這樣一來,使用者一進入應用程式,廣告就會立即放送。
導入公用程式元件 AppOpenAdManager
,提前發出廣告請求
在需要顯示廣告時特別操作
Java
public class MyApplication extends Application {
// ...
/** Inner class that loads and shows app open ads. */
private class AppOpenAdManager {
private static final String LOG_TAG = "AppOpenAdManager";
private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921";
private AppOpenAd appOpenAd = null;
private boolean isLoadingAd = false;
private boolean isShowingAd = false;
/** Constructor. */
public AppOpenAdManager() {}
/** Request an ad. */
private void loadAd(Context context) {
// We will implement this later.
}
/** Check if ad exists and can be shown. */
private boolean isAdAvailable() {
return appOpenAd != null;
}
}
}
Kotlin
private const val String LOG_TAG = "AppOpenAdManager"
private const val String AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921"
public class MyApplication extends Application {
// ...
/** Inner class that loads and shows app open ads. */
private inner class AppOpenAdManager {
private var appOpenAd: AppOpenAd? = null
private var isLoadingAd = false
var isShowingAd = false
/** Request an ad. */
fun loadAd(context: Context) {
// We will implement this later.
}
/** Check if ad exists and can be shown. */
private fun isAdAvailable(): Boolean {
return appOpenAd != null
}
}
}
建立公用程式類別後,您可以在自己的
MyApplication
類別:
Java
public class MyApplication extends Application {
private AppOpenAdManager appOpenAdManager;
@Override
public void onCreate() {
super.onCreate();
new Thread(
() -> {
// Initialize the Google Mobile Ads SDK 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 the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this@MyApplication) {}
}
appOpenAdManager = AppOpenAdManager()
}
}
載入廣告
下一步是填寫 loadAd()
方法並處理廣告載入量
回呼函式。
Java
private class AppOpenAdManager {
// ...
/** Request an ad. */
public void loadAd(Context context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
return;
}
isLoadingAd = true;
AdRequest request = new AdRequest.Builder().build();
AppOpenAd.load(
context, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
new AppOpenAdLoadCallback() {
@Override
public void onAdLoaded(AppOpenAd ad) {
// Called when an app open ad has loaded.
Log.d(LOG_TAG, "Ad was loaded.");
appOpenAd = ad;
isLoadingAd = false;
loadTime = (new Date()).getTime();
}
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
// Called when an app open ad has failed to load.
Log.d(LOG_TAG, loadAdError.getMessage());
isLoadingAd = false;
}
});
}
// ...
}
Kotlin
private inner class AppOpenAdManager {
// ...
/** Request an ad. */
fun loadAd(context: Context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
return
}
isLoadingAd = true
val request = AdRequest.Builder().build()
AppOpenAd.load(
context, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
object : AppOpenAdLoadCallback() {
override fun onAdLoaded(ad: AppOpenAd) {
// Called when an app open ad has loaded.
Log.d(LOG_TAG, "Ad was loaded.")
appOpenAd = ad
isLoadingAd = false
loadTime = Date().time
}
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
// Called when an app open ad has failed to load.
Log.d(LOG_TAG, loadAdError.message)
isLoadingAd = false;
}
})
}
// ...
}
顯示廣告並處理全螢幕回呼事件
最常見的應用程式開啟頁面廣告導入方式,就是嘗試顯示應用程式開啟頁面廣告 在應用程式啟動附近時,啟動應用程式內容 (如果廣告尚未就緒),並預先載入另一則廣告 ,把握下次的應用程式開放機會如需實作範例,請參閱「應用程式開啟頁面廣告指南」。
下方程式碼展示如何顯示並隨後重新載入廣告:
Java
public class MyApplication extends Application {
// ...
/** Interface definition for a callback to be invoked when an app open ad is complete. */
public interface OnShowAdCompleteListener {
void onShowAdComplete();
}
private class AppOpenAdManager {
// ...
/** Shows the ad if one isn't already showing. */
public void showAdIfAvailable(
@NonNull final Activity activity,
@NonNull OnShowAdCompleteListener onShowAdCompleteListener){
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(LOG_TAG, "The app open ad is already showing.");
return;
}
// If the app open ad is not available yet, invoke the callback then load the ad.
if (!isAdAvailable()) {
Log.d(LOG_TAG, "The app open ad is not ready yet.");
onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
return;
}
appOpenAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
@Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, "Ad dismissed fullscreen content.");
appOpenAd = null;
isShowingAd = false;
onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, adError.getMessage());
appOpenAd = null;
isShowingAd = false;
onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
}
@Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d(LOG_TAG, "Ad showed fullscreen content.");
}
});
isShowingAd = true;
appOpenAd.show(activity);
}
// ...
}
}
Kotlin
class MyApplication : Application() {
// ...
/** Interface definition for a callback to be invoked when an app open ad is complete. */
interface OnShowAdCompleteListener {
fun onShowAdComplete()
}
private inner class AppOpenAdManager {
// ...
/** Shows the ad if one isn't already showing. */
fun showAdIfAvailable(
activity: Activity,
onShowAdCompleteListener: OnShowAdCompleteListener) {
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(LOG_TAG, "The app open ad is already showing.")
return
}
// If the app open ad is not available yet, invoke the callback then load the ad.
if (!isAdAvailable()) {
Log.d(LOG_TAG, "The app open ad is not ready yet.")
onShowAdCompleteListener.onShowAdComplete()
loadAd(activity)
return
}
appOpenAd?.setFullScreenContentCallback(
object : FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
// Called when full screen content is dismissed.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, "Ad dismissed fullscreen content.")
appOpenAd = null
isShowingAd = false
onShowAdCompleteListener.onShowAdComplete()
loadAd(activity)
}
override fun onAdFailedToShowFullScreenContent(adError: AdError) {
// Called when fullscreen content failed to show.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, adError.message)
appOpenAd = null
isShowingAd = false
onShowAdCompleteListener.onShowAdComplete()
loadAd(activity)
}
override fun onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d(LOG_TAG, "Ad showed fullscreen content.")
}
})
isShowingAd = true
appOpenAd?.show(activity)
}
// ...
}
}
FullScreenContentCallback
處理事件,例如廣告顯示時、無法顯示廣告或
已關閉。
考慮廣告效期
為確保您不顯示已過期的廣告,請在 AppOpenAdManager
中加入方法
,檢查廣告參照載入至今已過多久。然後使用
方法檢查廣告是否仍然有效。
Java
private 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;
// ...
/** Utility method to check if ad was loaded more than n hours ago. */
private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
long dateDifference = (new Date()).getTime() - this.loadTime;
long numMilliSecondsPerHour = 3600000;
return (dateDifference < (numMilliSecondsPerHour * numHours));
}
/** Check if ad exists and can be shown. */
public boolean isAdAvailable() {
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}
}
Kotlin
private inner class 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;
// ...
/** Utility method to 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 {
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4)
}
}
追蹤目前活動
如要顯示廣告,您必須提供 Activity
結構定義。追蹤
使用目前的活動、註冊並實作
Application.ActivityLifecycleCallbacks
。
Java
public class MyApplication extends Application implements ActivityLifecycleCallbacks {
private Activity currentActivity;
@Override
public void onCreate() {
super.onCreate();
this.registerActivityLifecycleCallbacks(this);
// ...
}
/** ActivityLifecycleCallback methods. */
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityStarted(Activity activity) {
currentActivity = activity
}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
@Override
public void onActivityDestroyed(Activity activity) {}
}
Kotlin
class MyApplication : Application(), Application.ActivityLifecycleCallbacks {
private var currentActivity: Activity? = null
override fun onCreate() {
super.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) {}
}
registerActivityLifecycleCallbacks
敬上
可讓您監聽所有 Activity
事件。透過監聽活動
都能追蹤到目前版本
Activity
,以便您顯示應用程式開啟頁面廣告。
監聽應用程式前景事件
在 Gradle 檔案中加入程式庫
如要收到應用程式前景事件的通知,您必須註冊
DefaultLifecycleObserver
。將依附元件新增至應用程式層級的建構檔案:
Kotlin
dependencies { implementation("com.google.android.gms:play-services-ads:23.3.0") implementation("androidx.lifecycle:lifecycle-process:2.8.3") }
Groovy
dependencies { implementation 'com.google.android.gms:play-services-ads:23.3.0' implementation 'androidx.lifecycle:lifecycle-process:2.8.3' }
實作生命週期觀察器介面
您可以實作
DefaultLifecycleObserver
介面。
執行 onStart
事件以顯示應用程式開啟頁面廣告。
Java
public class MyApplication extends Application
implements ActivityLifecycleCallbacks, LifecycleObserver {
// ...
@Override
public void onCreate() {
super.onCreate();
this.registerActivityLifecycleCallbacks(this);
new Thread(
() -> {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this, initializationStatus -> {});
})
.start();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
appOpenAdManager = new AppOpenAdManager();
}
/** LifecycleObserver method that shows the app open ad when the app moves to foreground. */
@OnLifecycleEvent(Event.ON_START)
protected void onMoveToForeground() {
// Show the ad (if available) when the app moves to foreground.
appOpenAdManager.showAdIfAvailable(currentActivity);
}
/** Show the ad if one isn't already showing. */
private void showAdIfAvailable(@NonNull final Activity activity) {
showAdIfAvailable(
activity,
new OnShowAdCompleteListener() {
@Override
public void onShowAdComplete() {
// Empty because the user will go back to the activity that shows the ad.
}
});
}
}
Kotlin
class MyApplication : Application(),
Application.ActivityLifecycleCallbacks, LifecycleObserver {
// ...
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(this)
val backgroundScope = CoroutineScope(Dispatchers.IO)
backgroundScope.launch {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this@MyApplication) {}
}
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
appOpenAdManager = AppOpenAdManager()
}
/** LifecycleObserver method that shows the app open ad when the app moves to foreground. */
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onMoveToForeground() {
// Show the ad (if available) when the app moves to foreground.
currentActivity?.let {
appOpenAdManager.showAdIfAvailable(it)
}
}
/** Show the ad if one isn't already showing. */
fun showAdIfAvailable(activity: Activity) {
showAdIfAvailable(
activity,
object : OnShowAdCompleteListener {
override fun onShowAdComplete() {
// Empty because the user will go back to the activity that shows the ad.
}
})
}
}
冷啟動和載入畫面
目前為止,本說明文件假設您只有在使用者 前景。「冷啟動」發生在 應用程式已啟動,但之前未在記憶體中暫停。
舉例來說,使用者首次開啟應用程式時,就是冷啟動的例子。 如果選擇冷啟動,您就不會看到先前載入的應用程式開啟頁面廣告 就會立即顯示從送出廣告請求到收到廣告之間的延遲時間 讓使用者能先短暫使用您的應用程式 很容易讓人感到驚訝應避免這麼做,因為 使用者體驗不佳
如要在冷啟動時放送應用程式開啟頁面廣告,建議做法是使用載入畫面。 載入您的遊戲或應用程式素材資源,而且只在載入過程中顯示廣告 。如果您的應用程式已載入完成,並已將使用者導向主要應用程式 請不要顯示廣告
最佳做法
應用程式開啟頁面廣告可協助您在應用程式的載入畫面 (首次發生當下) 營利 因此在切換應用程式時,請務必遵循 讓使用者喜歡使用您的應用程式建議你採取以下做法:
- 等使用者用過應用程式幾次之後,再放送第一則應用程式開啟頁面廣告。
- 在使用者等待應用程式載入時,顯示應用程式開啟頁面廣告。
- 如果應用程式開啟頁面廣告下方顯示載入畫面,以及載入畫面
建議您在廣告關閉前就完成載入,建議您關閉
在
onAdDismissedFullScreenContent()
方法中載入畫面。
GitHub 上的範例
後續步驟
探索下列主題: