设置原生广告的高级功能

原生广告提供以下高级功能,可让您自定义广告集成:

  • 视频播放控件:自定义视频播放行为并监听视频生命周期事件。
  • “广告选项”图标展示位置:自定义“广告选项”图标的展示位置。
  • 自定义点击手势:将滑动手势配置为点击操作。

本指南介绍了如何将原生广告的高级功能与 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 方法。

配置“广告选项”展示位置

如需自定义“广告选项”图标的展示位置,请使用 AdChoicesPlacement 对象在 NativeAdRequest 对象上指定 adChoicesPlacement 属性。

以下示例在广告请求中将“广告选项”图标位置配置为左上角:

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 属性,以验证该广告是否启用了自定义点击手势。

后续步骤

配置原生高级广告功能后,您可以了解以下内容: