加载单个插页式激励广告

借助插页式激励广告,您可以在屏幕或游戏关卡之间展示广告,并向用户提供应用内商品。与激励广告不同,用户无需选择观看即可看到广告。 如需了解详情,请参阅插页式激励广告单元概览。

本指南介绍了如何将插页式激励广告植入到 React Native 原生应用中。

前提条件

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

Android

ca-app-pub-3940256099942544/5354046379

iOS

ca-app-pub-3940256099942544/6978759866

加载广告

如需加载插页式激励广告,请对 RewardedInterstitialAd 类调用 load 方法。

以下示例会在成功时加载插页式激励广告,在失败时记录错误:

export async function loadRewardedInterstitialAd(
  adUnitId: string,
): Promise<RewardedInterstitialAd | null> {
  try {
    const ad = await RewardedInterstitialAd.load({adUnitId});
    return ad;
  } catch (error) {
    const loadError = error as LoadAdError;
    console.error('Failed to load rewarded interstitial:', loadError.message);
    return null;
  }
}

监听广告事件

在展示广告之前,请在已加载的 RewardedInterstitialAd 实例上设置 adEventCallback 监听器。此监听器会接收广告生命周期事件(例如广告在屏幕上展示或用户点按广告)的回调。如需了解可用的回调,请参阅 AdEventCallback。

以下示例设置了用于监听广告事件的回调:

export function registerAdEvents(ad: RewardedInterstitialAd) {
  ad.adEventCallback = {
    // Called when the ad is presented on screen.
    onAdShowedFullScreenContent: () => {
      console.log('Rewarded interstitial ad showed full screen content.');
    },
    // Called when the ad is closed by the user.
    onAdDismissedFullScreenContent: () => {
      console.log('Rewarded interstitial ad dismissed full screen content.');
      ad.destroy();
    },
    // Called when presentation fails.
    onAdFailedToShowFullScreenContent: (error) => {
      console.error('Failed to show rewarded interstitial ad:', error);
      ad.destroy();
    },
    // Called when an impression is recorded.
    onAdImpression: () => {
      console.log('Rewarded interstitial ad recorded an impression.');
    },
    // Called when the user taps the ad.
    onAdClicked: () => {
      console.log('Rewarded interstitial ad was clicked.');
    },
    // Called when the ad is estimated to have earned money.
    onAdPaid: (adValue) => {
      console.log(
        `Rewarded interstitial ad paid: ${adValue.amountMicros} ${adValue.currencyCode}`,
      );
    },
  };
}

此示例还会在用户关闭广告或广告未能展示时调用 destroy 方法。此过程会释放广告使用的资源。

展示广告

若要展示插页式激励广告,请对已加载的 RewardedInterstitialAd 实例调用 show,并传递一个回调来接收 Reward:

export function showRewardedInterstitialAd(
  ad: RewardedInterstitialAd,
  onRewardEarned: (reward: Reward) => void,
) {
  ad.show(onRewardEarned);
}

可选:验证服务器端验证回调

如果您的应用需要在服务器端验证 (SSV) 回调中使用自定义验证参数(例如用户 ID 或自定义奖励元数据),请在展示广告之前,在已加载的广告实例上设置 serverSideVerificationOptions 属性。

您设置的值会传递给 SSV 回调查询参数:

  • userId:传递给 user_id 查询参数,用于标识用户。
  • customData:传递给 custom_data 查询参数,以转发自定义元数据。

以下示例在展示广告之前,对插页式激励广告对象设置 ServerSideVerificationOptions(customData 和 userId):

export function setServerSideVerificationRewardedInterstitial(
  ad: RewardedInterstitialAd,
) {
  ad.serverSideVerificationOptions = {
    userId: 'user_123',
    customData: 'sample_custom_data',
  };
}

查看完整示例

本部分通过一个完整示例介绍了如何将插页式激励广告植入到 React Native 应用中。

以下示例将广告集成到 React Native 组件中,在状态中管理广告实例,并提供用于加载和展示广告的控件:

export function RewardedInterstitialSingleLoadScreen() {
  const [ad, setAd] = useState<RewardedInterstitialAd | null>(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [status, setStatus] = useState<string>('Idle');
  const [reward, setReward] = useState<string | null>(null);

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

  const handleLoad = async () => {
    setReward(null);
    setStatus('Loading Rewarded Interstitial ad...');
    const loadedAd = await loadRewardedInterstitialAd(
      REWARDED_INTERSTITIAL_AD_UNIT_ID,
    );
    if (loadedAd) {
      registerAdEvents(loadedAd);
      const onDismiss =
        loadedAd.adEventCallback?.onAdDismissedFullScreenContent;
      loadedAd.adEventCallback = {
        ...loadedAd.adEventCallback,
        onAdDismissedFullScreenContent: () => {
          onDismiss?.();
          setStatus('Ad dismissed.');
        },
      };
      setAd((prevAd) => {
        prevAd?.destroy();
        return loadedAd;
      });
      setIsLoaded(true);
      setStatus('Rewarded Interstitial ad loaded!');
    } else {
      setStatus('Failed to load Rewarded Interstitial ad.');
    }
  };

  const handleShow = () => {
    if (ad) {
      showRewardedInterstitialAd(ad, (userReward) => {
        setReward(`${userReward.amount} ${userReward.type}`);
      });
      setIsLoaded(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Rewarded Interstitial Ad</Text>
      <Text style={styles.status}>Status: {status}</Text>
      {reward && <Text style={styles.rewardText}>Earned: {reward}</Text>}
      <View style={styles.buttonGroup}>
        <Button title="Load Ad" onPress={handleLoad} />
        <View style={styles.spacerSmall} />
        <Button title="Show Ad" onPress={handleShow} disabled={!isLoaded} />
      </View>
    </View>
  );
}

后续步骤

植入插页式激励广告后,请探索以下主题: