激励广告会在用户与视频广告、试玩广告和调查问卷互动后,向其发放应用内商品。如需了解详情,请参阅激励广告单元概览。
本指南介绍了如何将激励广告植入到 React Native 应用中。
前提条件
在继续操作之前,请确保满足以下条件:
- 设置 Google Mobile Ads SDK for React Native。
- 启用测试广告并使用以下测试广告单元:
Android
ca-app-pub-3940256099942544/5224354917
iOS
ca-app-pub-3940256099942544/1712485313
加载广告
如需加载激励广告,请对 RewardedAd 类调用 load 方法。
以下示例会在成功时加载激励广告,在失败时记录错误:
export async function loadRewardedAd(
adUnitId: string,
): Promise<RewardedAd | null> {
try {
const ad = await RewardedAd.load({adUnitId});
return ad;
} catch (error) {
const loadError = error as LoadAdError;
console.error('Failed to load rewarded ad:', loadError.message);
return null;
}
}
监听广告事件
在展示广告之前,请在已加载的 RewardedAd 实例上设置 adEventCallback 监听器。此监听器会接收广告生命周期事件(例如广告在屏幕上展示或用户点按广告)的回调。如需了解可用的回调,请参阅 AdEventCallback。
以下示例设置了用于监听广告事件的回调:
export function registerAdEvents(ad: RewardedAd) {
ad.adEventCallback = {
// Called when the ad is presented on screen.
onAdShowedFullScreenContent: () => {
console.log('Rewarded ad showed full screen content.');
},
// Called when the ad is closed by the user.
onAdDismissedFullScreenContent: () => {
console.log('Rewarded ad dismissed full screen content.');
ad.destroy();
},
// Called when presentation fails.
onAdFailedToShowFullScreenContent: (error) => {
console.error('Failed to show rewarded ad:', error);
ad.destroy();
},
// Called when an impression is recorded.
onAdImpression: () => {
console.log('Rewarded ad recorded an impression.');
},
// Called when the user taps the ad.
onAdClicked: () => {
console.log('Rewarded ad was clicked.');
},
// Called when the ad is estimated to have earned money.
onAdPaid: (adValue) => {
console.log(
`Rewarded ad paid: ${adValue.amountMicros} ${adValue.currencyCode}`,
);
},
};
}
此示例还会在用户关闭广告或广告未能展示时调用 destroy 方法。此过程会释放广告使用的资源。
展示广告
如需展示激励广告,请调用 show 方法,并使用回调来处理用户获得的奖励:
export function showRewardedAd(
ad: RewardedAd,
onRewardEarned: (reward: Reward) => void,
) {
ad.show(onRewardEarned);
}
可选:验证服务器端验证回调
如果您的应用需要在服务器端验证 (SSV) 回调中使用自定义验证参数(例如用户 ID 或自定义奖励元数据),请在展示广告之前,在已加载的广告实例上设置 serverSideVerificationOptions 属性。
您设置的值会传递给 SSV 回调查询参数:
userId:传递给user_id查询参数,用于标识用户。customData:传递给custom_data查询参数,以转发自定义元数据。
以下示例在展示广告之前,对激励广告对象设置 ServerSideVerificationOptions(customData 和 userId):
查看完整示例
本部分通过一个完整示例介绍了如何将激励广告植入到 React Native 原生应用中。
以下示例将广告集成到 React Native 组件中,在状态中管理广告实例,并提供用于加载和展示广告的控件:
后续步骤
植入激励广告后,请探索以下主题: