设置横幅广告

横幅广告在应用布局中占据固定位置,例如设备屏幕的顶部或底部。用户与您的应用互动时,这类广告会停留在屏幕上,并且会在您设置的一段时间后刷新。锚定自适应横幅广告会按照您指定的广告宽度,针对每台设备使用相应的广告尺寸。

本页介绍了如何将锚定自适应横幅广告植入到 React Native 应用中。

前提条件

在继续操作之前,请确保满足以下条件:

Android

ca-app-pub-3940256099942544/9214589741

iOS

ca-app-pub-3940256099942544/2435281174

获取广告尺寸

如需请求锚定自适应横幅广告,请调用 AdSize.getLargeAnchoredAdaptiveBannerAdSize 方法,并传入可用的广告容器宽度(以密度无关像素 [dp] 为单位)。此方法会返回一个 promise,该 promise 会解析为 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 界面中指定的任何刷新频率进行刷新。如果您尚未启用刷新功能,则需发出新的请求。如需详细了解广告单元刷新(例如如何设置刷新频率),请参阅为横幅广告使用自动刷新功能。

展示横幅广告

如需展示已加载的 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。

后续步骤

植入横幅广告后,请探索以下主题: