激励广告是指用户可以选择通过互动来换取应用内奖励的一种广告。本指南介绍了如何将 Ad Manager 激励广告集成到 Flutter 应用中。
务必用测试广告进行测试
在构建和测试应用时,请确保使用的是测试广告,而不是实际投放的广告。否则,可能会导致您的账号被中止。
对于激励广告,加载测试广告最简便的方法就是使用我们的专用测试广告单元 ID:
/21775744923/example/rewarded
这些测试广告单元经过专门配置,可确保每个请求返回的都是测试广告;在编码、测试和调试期间,您可以在自己的应用中随时调用。只需确保在发布应用之前,将这些测试广告单元 ID 替换为您自己的广告单元 ID 即可。
加载广告
以下示例加载了一个激励广告:
请将 _adUnitId 替换为您自己的广告单元 ID。
激励广告事件
通过使用 FullScreenContentCallback,您可以监听各种广告生命周期事件,例如广告何时展示或何时关闭。请在展示广告之前设置 RewardedAd.fullScreenContentCallback,以便接收这些事件的相关通知。以下示例实现了每个方法,并在控制台中记录了一条消息:
ad.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (ad) {
// Called when the ad showed the full screen content.
debugPrint('Ad showed full screen content.');
},
onAdFailedToShowFullScreenContent: (ad, err) {
// Called when the ad failed to show full screen content.
debugPrint('Ad failed to show full screen content with error: $err');
// Dispose the ad here to free resources.
ad.dispose();
},
onAdDismissedFullScreenContent: (ad) {
// Called when the ad dismissed full screen content.
debugPrint('Ad was dismissed.');
// Dispose the ad here to free resources.
ad.dispose();
},
onAdImpression: (ad) {
// Called when an impression occurs on the ad.
debugPrint('Ad recorded an impression.');
},
onAdClicked: (ad) {
// Called when a click is recorded for an ad.
debugPrint('Ad was clicked.');
},
);
展示广告
RewardedAd 作为叠加层展示在所有应用内容之上,由于它是静态放置的,因此无法将其添加到 Flutter widget 树中。您可以通过调用 show() 来选择展示广告的时机。RewardedAd.show() 接受 OnUserEarnedRewardCallback,当用户获得奖励时,系统就会触发该回调。请务必实现此回调,在用户观看广告后给予奖励。
_rewardedAd?.show(
onUserEarnedReward:
(AdWithoutView ad, RewardItem rewardItem) {
debugPrint(
'Reward amount: ${rewardItem.amount}',
);
},
);
一旦调用 show(),以这种方式展示的 Ad 就无法以程序化方式移除,需要用户手动关闭。RewardedAd 仅可展示一次。后续对 show 的调用将触发 onAdFailedToShowFullScreenContent。
当不再需要访问广告时,必须将其销毁。最佳实践是在 FullScreenContentCallback.onAdDismissedFullScreenContent 和 FullScreenContentCallback.onAdFailedToShowFullScreenContent 回调中调用 dispose()。
[可选] 验证服务器端验证 (SSV) 回调
如果应用需要在服务器端验证回调中包含额外的数据,则应使用激励广告的自定义数据功能。在激励广告对象中设置的任何字符串值都将传递给 SSV 回调的 custom_data 查询参数。如果未设置自定义数据值,custom_data 查询参数值不会出现在 SSV 回调中。
以下代码示例演示了如何在加载激励广告后设置 SSV 选项:
请将 SAMPLE_CUSTOM_DATA_STRING 替换为您的自定义数据。