借助插页式激励广告,您可以在屏幕或游戏关卡之间展示广告,并向用户提供应用内商品。与激励广告不同,用户无需选择观看即可看到广告。 如需了解详情,请参阅插页式激励广告单元概览。
本指南介绍了如何将插页式激励广告植入到 React Native 原生应用中。
前提条件
在继续操作之前,请确保满足以下条件:
- 设置 Google Mobile Ads SDK for 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):
查看完整示例
本部分通过一个完整示例介绍了如何将插页式激励广告植入到 React Native 应用中。
以下示例将广告集成到 React Native 组件中,在状态中管理广告实例,并提供用于加载和展示广告的控件:
后续步骤
植入插页式激励广告后,请探索以下主题: