設定進階原生廣告功能

原生廣告提供下列進階功能,可讓您自訂廣告整合:

  • 影片播放控制項:自訂影片播放行為,並監聽影片生命週期事件。
  • AdChoices 圖示位置:自訂 AdChoices 圖示的位置。
  • 自訂點擊手勢:將滑動手勢設為點擊動作。

本指南說明如何搭配 Google Mobile Ads SDK for React Native 使用原生廣告的進階功能。

必要條件

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

管理影片播放和事件

請求含有影片素材資源的原生廣告時,請自訂影片播放啟動選項、監聽影片生命週期事件,以及控制影片播放。

設定影片請求選項

如要自訂初始影片行為,請使用 VideoOptions 物件,在 NativeAdRequest 物件上設定 videoOptions 屬性。

以下範例將影片設為開始播放時靜音:

export async function loadNativeVideoAd(
  adUnitId: string,
): Promise<NativeAd | null> {
  try {
    const ad = await NativeAd.load({
      adUnitId,
      videoOptions: {
        // Autoplay video with sound muted.
        startMuted: true,
      },
    });

    // Inspect video metadata if the ad contains video content.
    if (ad.mediaContent.hasVideoContent) {
      console.log('Video duration in seconds:', ad.mediaContent.duration);
      console.log('Video aspect ratio:', ad.mediaContent.aspectRatio);
    }

    return ad;
  } catch (error) {
    const loadError = error as LoadAdError;
    console.error('Failed to load native video ad:', loadError.message);
    return null;
  }
}

廣告載入後,這個範例也會檢查廣告是否含有影片素材資源、記錄影片中繼資料,並傳回載入的廣告。如果失敗,範例會記錄錯誤訊息。

如要進一步瞭解影片中繼資料屬性,例如顯示比例、目前時間和時間長度,請參閱 MediaContent。

監聽影片事件

如要監聽影片生命週期事件 (例如影片開始或結束時),請將 VideoControllerEventProps 介面的事件回呼傳遞至 NativeAdMediaView 元件。

以下範例會傳遞回呼,記錄影片生命週期事件,並算繪自訂按鈕來控制影片播放:

export function NativeAdWithVideoControls({ad}: {ad: NativeAd}) {
  const mediaViewRef = useRef<NativeAdMediaViewMethods>(null);

  return (
    <NativeAdView ad={ad}>
      {/* Video lifecycle callbacks */}
      <NativeAdMediaView
        ref={mediaViewRef}
        // Called when video playback starts.
        onVideoStart={() => {
          console.log('Video playback started.');
        }}
        // Called when video playback resumes or plays.
        onVideoPlay={() => {
          console.log('Video is playing.');
        }}
        // Called when video playback pauses.
        onVideoPause={() => {
          console.log('Video playback paused.');
        }}
        // Called when video playback completes.
        onVideoEnd={() => {
          console.log('Video playback finished.');
        }}
        // Called when the video mute state changes.
        onVideoMute={(isMuted: boolean) => {
          console.log(`Video mute state changed: ${isMuted}`);
        }}
      />

      {/* Custom playback controls (Ad Manager customControlsRequested only) */}
      <View>
        {/* Plays or resumes the video. */}
        <Button
          title="Play"
          onPress={() => mediaViewRef.current?.playVideo()}
        />
        {/* Pauses video playback. */}
        <Button
          title="Pause"
          onPress={() => mediaViewRef.current?.pauseVideo()}
        />
        {/* Stops video playback and resets the playback position to the beginning. */}
        <Button
          title="Stop"
          onPress={() => mediaViewRef.current?.stopVideo()}
        />
        {/* Mutes or unmutes audio. */}
        <Button
          title="Mute"
          onPress={() => mediaViewRef.current?.setVideoMuted(true)}
        />
        <Button
          title="Unmute"
          onPress={() => mediaViewRef.current?.setVideoMuted(false)}
        />
      </View>
    </NativeAdView>
  );
}

啟用自訂控制項後,請將 NativeAdMediaViewMethods 類型的 ref 屬性附加至 NativeAdMediaView 元件,以控制影片播放。NativeAdMediaViewMethods 類型會為 VideoControllerMethods 介面建立別名,該介面會公開 ref 物件上的 playVideo、pauseVideo、stopVideo 和 setVideoMuted 方法。

設定 AdChoices 刊登位置

如要自訂 AdChoices 圖示的位置,請使用 AdChoicesPlacement 物件,在 NativeAdRequest 物件上指定 adChoicesPlacement 屬性。

以下範例說明如何在廣告請求中,將 AdChoices 圖示位置設在左上角:

export async function loadNativeAdWithAdChoicesPlacement(
  adUnitId: string,
): Promise<NativeAd | null> {
  try {
    const ad = await NativeAd.load({
      adUnitId,
      // Render the AdChoices icon in the top-left corner.
      adChoicesPlacement: AdChoicesPlacement.TOP_LEFT,
    });
    return ad;
  } catch (error) {
    const loadError = error as LoadAdError;
    console.error('Failed to load native ad:', loadError.message);
    return null;
  }
}

這個範例也會在成功時傳回載入的廣告,並在失敗時記錄錯誤訊息。

設定自訂點擊手勢

使用 NativeAdRequest 物件的 customClickGestureDirection 和 customClickGestureAllowTaps 屬性,將滑動手勢設為原生廣告的點擊動作。

以下範例將手勢方向設為向右滑動,並允許在載入廣告時輕觸:

export async function loadNativeAdWithCustomClick(
  adUnitId: string,
): Promise<NativeAd | null> {
  try {
    const ad = await NativeAd.load({
      adUnitId,
      // Require a right swipe gesture for clicks while allowing standard taps.
      customClickGestureDirection: SwipeGestureDirection.RIGHT,
      customClickGestureAllowTaps: true,
    });

    if (ad.isCustomClickGestureEnabled) {
      console.log('Custom click gestures are enabled for this ad.');
    }

    return ad;
  } catch (error) {
    const loadError = error as LoadAdError;
    console.error('Failed to load native ad:', loadError.message);
    return null;
  }
}

這個範例也會檢查是否已啟用自訂點擊手勢,如果成功,則傳回載入的廣告,如果失敗,則記錄錯誤。

載入廣告後,請檢查 ad.isCustomClickGestureEnabled 屬性,確認該廣告是否已啟用自訂點擊手勢。

後續步驟

設定進階版原生廣告功能後,您可以瞭解下列事項: