插頁式廣告會全螢幕顯示,通常出現在應用程式的轉換點,例如畫面切換時,或遊戲關卡間的暫停時間。使用者可以輕觸廣告前往到達網頁,也可以關閉廣告返回應用程式。詳情請參閱插頁式廣告指南和個案研究。
本指南說明如何在 React Native 應用程式中整合插頁式廣告。
必要條件
- 設定 Google Mobile Ads SDK for React Native。
- 啟用測試廣告,並使用下列測試廣告單元 ID:
僅適用於搭載 Android
ca-app-pub-3940256099942544/1033173712
iOS
ca-app-pub-3940256099942544/4411468910
載入廣告
如要載入插頁式廣告,請呼叫 InterstitialAd 類別的 load 方法。
以下範例會在成功時載入插頁式廣告,失敗時則記錄錯誤:
export async function loadInterstitialAd(
adUnitId: string,
): Promise<InterstitialAd | null> {
try {
const ad = await InterstitialAd.load({adUnitId});
return ad;
} catch (error) {
const loadError = error as LoadAdError;
console.error('Failed to load interstitial ad:', loadError.message);
return null;
}
}
監聽廣告事件
顯示廣告前,請在載入的 InterstitialAd 執行個體上設定 adEventCallback 事件監聽器。這個事件監聽器會接收廣告生命週期事件的回呼,例如廣告顯示在畫面上,或使用者輕觸廣告。如要查看可用的回呼,請參閱 AdEventCallback。
以下範例設定了回呼,用於監聽廣告事件:
export function registerAdEvents(ad: InterstitialAd) {
ad.adEventCallback = {
// Called when the ad is presented on screen.
onAdShowedFullScreenContent: () => {
console.log('Interstitial ad showed full screen content.');
},
// Called when the ad is closed by the user.
onAdDismissedFullScreenContent: () => {
console.log('Interstitial ad dismissed full screen content.');
ad.destroy();
},
// Called when presentation fails.
onAdFailedToShowFullScreenContent: (error) => {
console.error('Failed to show interstitial ad:', error);
ad.destroy();
},
// Called when an impression is recorded.
onAdImpression: () => {
console.log('Interstitial ad recorded an impression.');
},
// Called when the user taps the ad.
onAdClicked: () => {
console.log('Interstitial ad was clicked.');
},
// Called when the ad is estimated to have earned money.
onAdPaid: (adValue) => {
console.log(
`Interstitial ad paid: ${adValue.amountMicros}` +
` ${adValue.currencyCode}`,
);
},
};
}
此外,當使用者關閉廣告或廣告無法顯示時,這個範例也會呼叫 destroy 方法。這個程序會釋出廣告使用的資源。
顯示廣告
如要顯示插頁式廣告,請在已載入的 InterstitialAd 執行個體上呼叫 show 方法。
以下是插頁式廣告範例:
export function showInterstitialAd(ad: InterstitialAd) {
ad.show();
}
查看完整範例
本節提供完整範例,說明如何將插頁式廣告整合至 React Native 應用程式。
以下範例將廣告整合至 React Native 元件、管理狀態中的廣告例項,並提供載入及顯示廣告的控制項:
後續步驟
插頁式廣告整合完成後,請參閱下列主題: