設定橫幅廣告

橫幅廣告會占據應用程式版面配置的固定位置,例如裝置畫面頂端或底部。使用者與應用程式互動時,這類廣告會固定顯示於畫面上,並在您設定的時間過後重新整理。錨定自動調整橫幅廣告會根據您指定的廣告寬度,為每部裝置調整廣告大小。

本頁說明如何將錨定自動調整橫幅廣告整合至 React Native 原生應用程式。

必要條件

請先完成下列事項,再繼續操作:

僅適用於搭載 Android

ca-app-pub-3940256099942544/9214589741

iOS

ca-app-pub-3940256099942544/2435281174

取得廣告大小

如要請求錨定自動調整橫幅廣告,請呼叫 AdSize.getLargeAnchoredAdaptiveBannerAdSize 方法,並以密度獨立像素 (dp) 為單位,指定可用的廣告容器寬度。這個方法會傳回一個承諾,解析為 AdSize 物件。

以下範例會取得並傳回錨定自動調整橫幅廣告的廣告大小:

export async function getAdaptiveAdSize(width: number): Promise<AdSize> {
  const adSize = await AdSize.getLargeAnchoredAdaptiveBannerAdSize(width);
  return adSize;
}

載入廣告

取得 AdSize 物件後,請使用廣告單元 ID 和廣告大小,在 BannerAd 類別上呼叫 load 方法。

以下範例會載入錨定自動調整橫幅廣告,並指定廣告大小和廣告單元 ID。載入成功時,會收到載入的 BannerAd 執行個體;載入失敗時,則會記錄錯誤:

export function loadBannerAd(
  adUnitId: string,
  adSize: AdSize,
  callback?: BannerAdLoadCallback,
): void {
  BannerAd.load(
    {adUnitId, adSize},
    {
      // Called when an ad has finished loading.
      onAdLoaded: (ad) => {
        console.log('Banner ad loaded successfully.');
        callback?.onAdLoaded?.(ad);
      },
      // Called when an ad request fails.
      onAdFailedToLoad: (error: LoadAdError) => {
        console.error('Failed to load banner ad:', error.message);
        callback?.onAdFailedToLoad?.(error);
      },
    },
  );
}

重新整理廣告

如已設定廣告單元重新整理功能,廣告載入失敗時,就不需要請求其他廣告。Google Mobile Ads SDK for React Native會套用您在 AdMob UI 指定的重新整理頻率。如果您未啟用這項功能,請發出新的請求。請參閱「為橫幅廣告使用自動重新整理功能」一文,進一步瞭解廣告單元重新整理功能 (例如設定重新整理頻率)。

顯示橫幅廣告

如要顯示已載入的 BannerAd 執行個體,請將廣告執行個體傳遞至檢視區塊階層中 BannerAdView 元件的 ad 屬性。

以下範例會顯示廣告,並在元件卸載時刪除廣告:

export function BannerAdViewComponent({ad}: {ad: BannerAd}): React.JSX.Element {
  useEffect(() => {
    // Destroy native resources when the component unmounts.
    return () => {
      ad.destroy();
    };
  }, [ad]);

  return <BannerAdView ad={ad} />;
}

這個範例會在元件卸載或廣告例項替換時,呼叫 destroy 方法。這個程序會釋出廣告使用的記憶體和資源。

監聽廣告事件

如要監聽廣告事件 (例如廣告曝光和點擊),請在 BannerAdView 元件上設定回呼。如需所有回呼,請參閱 BannerAdViewProps。

以下範例設定了回呼,用於監聽橫幅廣告事件:

export function BannerEventsExample({ad}: {ad: BannerAd}): React.JSX.Element {
  return (
    <BannerAdView
      ad={ad}
      // Called when an impression is recorded for an ad.
      onAdImpression={() => {
        console.log('Banner ad recorded an impression.');
      }}
      // Called when a click is recorded for an ad.
      onAdClicked={() => {
        console.log('Banner ad clicked.');
      }}
      // Called when the ad opens an in-app overlay or landing page.
      onAdShowedFullScreenContent={() => {
        console.log('Banner ad opened overlay content.');
      }}
      // Called when the user dismisses the ad overlay.
      onAdDismissedFullScreenContent={() => {
        console.log('Banner ad overlay dismissed.');
      }}
      // Called when the ad is estimated to have earned money.
      onAdPaid={(adValue) => {
        console.log(
          `Banner ad paid: ${adValue.amountMicros} ${adValue.currencyCode}`,
        );
      }}
      // Called when the ad automatically refreshes.
      onAdRefreshed={() => {
        console.log('Banner ad refreshed.');
      }}
      // Called when the ad fails to automatically refresh.
      onAdFailedToRefresh={(error) => {
        console.error('Banner ad failed to refresh:', error.message);
      }}
    />
  );
}

這個範例會監聽廣告事件,例如廣告關閉、曝光、點擊、全螢幕顯示、預估廣告收益,以及重新整理成功和失敗。

查看完整範例

本節將舉例完整說明如何將橫幅廣告整合至 React Native 元件。

以下範例將橫幅廣告整合至 React Native 元件,並在狀態中管理廣告例項:

export function BannerScreen() {
  const {width} = useWindowDimensions();
  const insets = useSafeAreaInsets();
  const [ad, setAd] = useState<BannerAd | null>(null);
  const [status, setStatus] = useState('Idle');

  useEffect(() => {
    return () => {
      ad?.destroy();
    };
  }, [ad]);

  const handleLoadAd = async () => {
    setStatus('Loading adaptive banner ad...');
    try {
      const adaptiveSize = await getAdaptiveAdSize(width);
      loadBannerAd(BANNER_AD_UNIT_ID, adaptiveSize, {
        onAdLoaded: (loadedAd) => {
          setAd(loadedAd);
          setStatus('Banner ad loaded successfully.');
        },
        onAdFailedToLoad: (error: LoadAdError) => {
          setStatus(`Failed to load banner ad: ${error.message}`);
        },
      });
    } catch (error) {
      setStatus(`Failed to get adaptive ad size: ${error}`);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Anchored Adaptive Banner Ad</Text>
      <Text style={styles.status}>Status: {status}</Text>
      <View style={styles.buttonGroup}>
        <Button title="Load Banner Ad" onPress={handleLoadAd} />
      </View>
      {ad ? (
        <View style={[styles.bannerContainer, {bottom: insets.bottom}]}>
          <BannerAdView
            ad={ad}
            onAdImpression={() => setStatus('Banner ad recorded impression.')}
            onAdClicked={() => setStatus('Banner ad clicked.')}
            onAdShowedFullScreenContent={() =>
              setStatus('Banner ad showed overlay content.')
            }
            onAdDismissedFullScreenContent={() =>
              setStatus('Banner ad overlay dismissed.')
            }
          />
        </View>
      ) : null}
    </View>
  );
}

將 BANNER_AD_UNIT_ID 替換為廣告單元 ID。

後續步驟

整合橫幅廣告後,請參閱下列主題: