激励广告
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
激励广告允许用户选择与之互动来换取应用内奖励。本指南介绍了如何使用 Google 移动广告 C++ SDK 将激励广告植入到 Android 和 iOS 应用中。
欢迎查看一些客户成功案例:案例研究 1、案例研究 2。
前提条件
务必用测试广告进行测试
在构建和测试应用时,请确保使用的是测试广告,而不是实际投放的广告。否则,可能会导致您的账号被中止。
对于激励广告,加载测试广告最简便的方法就是使用我们的专用测试广告单元 ID,该 ID 因设备平台而异:
- Android:
ca-app-pub-3940256099942544/5224354917
- iOS:
ca-app-pub-3940256099942544/1712485313
这些测试广告单元 ID 已经过专门配置,可确保每个请求返回的都是测试广告。您可以在自己应用的编码、测试和调试过程中随意使用这些测试广告单元 ID。只需确保您会在发布应用前用自己的广告单元 ID 替换该测试广告单元 ID 即可。
如需详细了解移动广告 SDK 的测试广告如何运作,请参阅测试广告。
实现
植入激励广告的主要步骤如下所示:
- 加载广告。
- 注册回调。
- 展示广告并处理奖励事件。
激励广告在 RewardedAd
对象中展示,因此将激励广告集成到应用中的第一步是创建并初始化 RewardedAd
的实例。
将以下头文件添加到应用的 C++ 代码中:
#include "firebase/gma/rewarded_ad.h"
声明并实例化一个 RewardedAd
对象:
firebase::gma::RewardedAd* rewarded_ad;
rewarded_ad = new firebase::gma::RewardedAd();
使用强制转换为 AdParent
类型的父视图初始化 RewardedAd
实例。父视图是 JNI jobject
对 Android Activity
的引用或指向 iOS UIView
的指针。
// my_ad_parent is a jobject reference to an Android Activity or
// a pointer to an iOS UIView.
firebase::gma::AdParent ad_parent =
static_cast<firebase::gma::AdParent>(my_ad_parent);
firebase::Future<void> result = rewarded_ad->Initialize(ad_parent);
除了将 future 保留为变量之外,您还可以通过对 RewardedAd
对象调用 InitializeLastResult()
来定期检查初始化操作的状态。这有助于跟踪全局游戏循环中的初始化过程。
// Monitor the status of the future in your game loop:
firebase::Future<void> result = rewarded_ad->InitializeLastResult();
if (result.status() == firebase::kFutureStatusComplete) {
// Initialization completed.
if(future.error() == firebase::gma::kAdErrorCodeNone) {
// Initialization successful.
} else {
// An error has occurred.
}
} else {
// Initialization on-going.
}
如需详细了解如何使用 firebase::Future
,请参阅使用 Future 来监控方法调用的完成状态。
加载广告
广告的加载是通过针对 RewardedAd
对象使用 LoadAd()
方法完成的。加载方法要求您已初始化 RewardedAd
对象,并且拥有广告单元 ID 和 AdRequest
对象。系统会返回一个 firebase::Future
,您可以使用它来监控加载操作的状态和结果。
以下代码展示了如何在 RewardedAd
成功初始化后加载广告:
firebase::gma::AdRequest ad_request;
firebase::Future<firebase::gma::AdResult> load_ad_result;
load_ad_result = rewarded_ad->LoadAd(rewarded_ad_unit_id, ad_request);
注册回调
您必须扩展 FullScreenContentListener
类,才能接收有关激励广告展示和生命周期事件的通知。您可以通过 RewardedAd::SetFullScreenContentListener()
方法注册自定义 FullScreenContentListener
子类,该子类会在广告成功展示或展示失败以及广告关闭时收到回调。
以下代码展示了如何扩展该类并将其分配给广告:
class ExampleFullScreenContentListener
: public firebase::gma::FullScreenContentListener {
public:
ExampleFullScreenContentListener() {}
void OnAdClicked() override {
// This method is invoked when the user clicks the ad.
}
void OnAdDismissedFullScreenContent() override {
// This method is invoked when the ad dismisses full screen content.
}
void OnAdFailedToShowFullScreenContent(const AdError& error) override {
// This method is invoked when the ad failed to show full screen content.
// Details about the error are contained within the AdError parameter.
}
void OnAdImpression() override {
// This method is invoked when an impression is recorded for an ad.
}
void OnAdShowedFullScreenContent() override {
// This method is invoked when the ad showed its full screen content.
}
};
ExampleFullScreenContentListener* example_full_screen_content_listener =
new ExampleFullScreenContentListener();
rewarded_ad->SetFullScreenContentListener(example_full_screen_content_listener);
RewardedAd
是一次性对象。这意味着,激励广告展示一次后就不能再展示了。最佳做法是在 FullScreenContentListener
的 OnAdDismissedFullScreenContent()
方法中加载另一个激励广告,以便在上一个激励广告关闭后,立即开始加载下一个激励广告。
展示广告并处理奖励事件
在向用户展示激励广告之前,必须为用户提供明确的选项,让用户可以自行选择是否通过观看激励广告内容来换取奖励。激励广告必须始终是一项可由用户自行选择的体验。
展示广告时,您必须提供 UserEarnedReward
对象,用于处理用户奖励。
以下代码展示了如何显示 RewardedAd
:
// A simple listener track UserEarnedReward events.
class ExampleUserEarnedRewardListener :
public firebase::gma::UserEarnedRewardListener {
public:
ExampleUserEarnedRewardListener() { }
void OnUserEarnedReward(const firebase::gma::AdReward& reward) override {
// Reward the user!
}
};
ExampleUserEarnedRewardListener* user_earned_reward_listener =
new ExampleUserEarnedRewardListener();
firebase::Future<void> result = rewarded_ad->Show(user_earned_reward_listener);
常见问题解答
- 初始化调用是否会超时?
- 10 秒后,即使中介广告联盟仍未完成初始化,Google 移动广告 C++ SDK 也会完成
Initialize()
返回的 firebase::Future
。
- 在获得初始化回调时,如果某些中介广告联盟尚未就绪,该怎么办?
最佳做法是在 SDK 初始化完成后加载广告。即使中介广告联盟尚未就绪,Google 移动广告 C++ SDK 仍会向该广告联盟请求广告。因此,如果中介广告联盟在超时后完成初始化,它仍然可以在该会话中为将来的广告请求提供服务。
您可以通过调用 GetInitializationStatus()
继续在整个应用会话中轮询所有适配器的初始化状态。
- 如何找出特定中介广告联盟未准备就绪的原因?
AdapterStatus.description()
描述了适配器未准备好为广告请求提供服务的原因。如需查看记录中介适配器状态的示例,请参阅 GitHub 上示例快速入门应用的源代码。
其他资源
GitHub 中的示例
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-31。
[null,null,["最后更新时间 (UTC):2025-08-31。"],[[["\u003cp\u003eThe Google Mobile Ads C++ SDK is deprecated and will be end-of-maintenance on June 17, 2025, with iOS and Android SDKs recommended as alternatives.\u003c/p\u003e\n"],["\u003cp\u003eRewarded ads allow users to interact with ads in exchange for in-app rewards, and this guide explains their integration using the Google Mobile Ads C++ SDK for Android and iOS.\u003c/p\u003e\n"],["\u003cp\u003eImplementation involves configuring a \u003ccode\u003eRewardedAd\u003c/code\u003e object, loading an ad, registering for callbacks using a \u003ccode\u003eFullScreenContentListener\u003c/code\u003e, and displaying the ad while handling rewards with a \u003ccode\u003eUserEarnedReward\u003c/code\u003e object.\u003c/p\u003e\n"],["\u003cp\u003eTest ads should always be used during development to avoid account suspension, with dedicated test ad unit IDs provided for Android and iOS.\u003c/p\u003e\n"],["\u003cp\u003eThe Google Mobile Ads C++ SDK initialization has a 10-second timeout, but ads can still be loaded afterward, and mediation network initialization status can be polled using \u003ccode\u003eGetInitializationStatus()\u003c/code\u003e.\u003c/p\u003e\n"]]],["The Google Mobile Ads C++ SDK is deprecated as of June 17, 2024, with support ending June 17, 2025; AdMob's iOS and Android SDKs are recommended replacements. To use rewarded ads, initialize a `RewardedAd` object, load an ad using `LoadAd()` and an `AdRequest`, and register callbacks through a `FullScreenContentListener`. When ready, show the ad via `Show()` while providing a `UserEarnedRewardListener` to handle user rewards. Remember to use test ad unit IDs during development.\n"],null,["# Rewarded ads\n\n| **DEPRECATED:** The Google Mobile Ads C++ SDK is *deprecated* as of June 17, 2024 and should not be adopted in projects that don't already use it. It will enter *End-of-Maintenance (EoM)* on June 17, 2025. Note that versions of the SDK released before the EoM date will continue to function, but no further bug fixes or changes will be released after the EoM date.\n|\n| Instead of the Google Mobile Ads C++ SDK, consider using the\n| [iOS](/admob/ios/quick-start) and\n| [Android](/admob/android/quick-start) SDKs from AdMob.\n| For support, reach out to the\n| [Google Mobile Ads SDK Technical Forum](https://groups.google.com/g/google-admob-ads-sdk).\n\n\u003cbr /\u003e\n\nRewarded ads let users have the option of interacting with them in exchange\nfor in-app rewards. This guide shows you how to integrate rewarded ads into\nAndroid and iOS apps using the Google Mobile Ads C++ SDK.\n\nRead some customer success stories:\n[case study 1](//admob.google.com/home/resources/kongregate-uses-admob-to-boost-revenue-average-30-dollar-cpm/),\n[case study 2](//admob.google.com/home/resources/four-thirty-three-uses-admob-to-boost-mobile-game-revenue-15-percent/).\n\nPrerequisites\n-------------\n\n- Complete [Get started](/admob/cpp/quick-start).\n- *(Android only)* Familiarity working with JNI `jobject` references (see [Android JNI tips](//developer.android.com/training/articles/perf-jni)).\n\nAlways test with test ads\n-------------------------\n\nWhen building and testing your apps, make sure you use test ads rather than\nlive, production ads. Failure to do so can lead to suspension of your account.\n\nThe easiest way to load test ads is to use our dedicated test ad unit ID for\nrewarded ads, which varies per device platform:\n\n- Android: `ca-app-pub-3940256099942544/5224354917`\n- iOS: `ca-app-pub-3940256099942544/1712485313`\n\nThey've been specially configured to return test ads for every request, and\nyou're free to use it in your own apps while coding, testing, and debugging.\nJust make sure you replace it with your own ad unit ID before publishing your\napp.\n\nFor more information about how the Mobile Ads SDK's test ads work, see\n[Test Ads](/admob/cpp/test-ads).\n\nImplementation\n--------------\n\nThe main steps to integrate rewarded ads are:\n\n1. Load an ad.\n2. Register for callbacks.\n3. Display the ad and handle the reward event.\n\n### Configure a `RewardedAd`\n\nRewarded ads are displayed in `RewardedAd` objects, so the first step toward\nintegrating rewarded ads into your app is to create and initialize an instance\nof `RewardedAd`.\n\n1. Add the following header to your app's C++ code:\n\n ```c++\n #include \"firebase/gma/rewarded_ad.h\"\n ```\n\n \u003cbr /\u003e\n\n2. Declare and instantiate a `RewardedAd` object:\n\n ```c++\n firebase::gma::RewardedAd* rewarded_ad;\n rewarded_ad = new firebase::gma::RewardedAd();\n ```\n\n \u003cbr /\u003e\n\n3. Initialize the `RewardedAd` instance using your parent view cast to an\n `AdParent` type. The parent view is a JNI `jobject` reference to an Android\n `Activity` or a pointer to an iOS `UIView`.\n\n // my_ad_parent is a jobject reference to an Android Activity or\n // a pointer to an iOS UIView.\n firebase::gma::AdParent ad_parent =\n static_cast\u003cfirebase::gma::AdParent\u003e(my_ad_parent);\n firebase::Future\u003cvoid\u003e result = rewarded_ad-\u003eInitialize(ad_parent);\n\n4. As an alternative to retaining the future as a variable, you can periodically\n check the status of the initialization operation by invoking\n `InitializeLastResult()` on the `RewardedAd` object. This may be helpful\n for keeping track of the initialization process in your global game loop.\n\n // Monitor the status of the future in your game loop:\n firebase::Future\u003cvoid\u003e result = rewarded_ad-\u003eInitializeLastResult();\n if (result.status() == firebase::kFutureStatusComplete) {\n // Initialization completed.\n if(future.error() == firebase::gma::kAdErrorCodeNone) {\n // Initialization successful.\n } else {\n // An error has occurred.\n }\n } else {\n // Initialization on-going.\n }\n\nFor more information about working with `firebase::Future`, see\n[Use Futures to monitor the completion status of method\ncalls](/admob/cpp/quick-start#futures).\n\n### Load an ad\n\nLoading an ad is accomplished using the `LoadAd()` method on a `RewardedAd`\nobject. The load method requires that you've initialized the `RewardedAd`\nobject, and that you have your ad unit ID and an `AdRequest` object. A\n`firebase::Future` is returned which you can use to monitor the state and result\nof the load operation.\n\nThe following code shows how to load an ad once the `RewardedAd` has been\nsuccessfully initialized: \n\n firebase::gma::AdRequest ad_request;\n firebase::Future\u003cfirebase::gma::AdResult\u003e load_ad_result;\n load_ad_result = rewarded_ad-\u003eLoadAd(rewarded_ad_unit_id, ad_request);\n\n### Register for callbacks\n\nYou must extend the `FullScreenContentListener` class in order to receive\nnotifications of rewarded ad presentation and lifecycle events. Your custom\n`FullScreenContentListener` subclass can be registered through the\n`RewardedAd::SetFullScreenContentListener()` method, and it will receive\ncallbacks when the ad presents successfully or unsuccessfully as well as when\nit's dismissed.\n\nThe following code shows how to extend the class and assign it to the ad: \n\n```c++\n class ExampleFullScreenContentListener\n : public firebase::gma::FullScreenContentListener {\n\n public:\n ExampleFullScreenContentListener() {}\n\n void OnAdClicked() override {\n // This method is invoked when the user clicks the ad.\n }\n\n void OnAdDismissedFullScreenContent() override {\n // This method is invoked when the ad dismisses full screen content.\n }\n\n void OnAdFailedToShowFullScreenContent(const AdError& error) override {\n // This method is invoked when the ad failed to show full screen content.\n // Details about the error are contained within the AdError parameter.\n }\n\n void OnAdImpression() override {\n // This method is invoked when an impression is recorded for an ad.\n }\n\n void OnAdShowedFullScreenContent() override {\n // This method is invoked when the ad showed its full screen content.\n }\n };\n\n ExampleFullScreenContentListener* example_full_screen_content_listener =\n new ExampleFullScreenContentListener();\n rewarded_ad-\u003eSetFullScreenContentListener(example_full_screen_content_listener);\n```\n\n`RewardedAd` is a one-time-use object. This means that once a rewarded ad is\nshown, it cannot be shown again. A best practice is to load another rewarded ad\nin the `OnAdDismissedFullScreenContent()` method of your\n`FullScreenContentListener` so that the next rewarded ad starts loading as soon\nas the previous one is dismissed.\n\n### Show the ad and handle the reward event\n\nBefore displaying a rewarded ad to users, you must present the user with an\nexplicit choice to view rewarded ad content in exchange for a reward. Rewarded\nads must always be an opt-in experience.\n\nWhen presenting your ad, you must provide a `UserEarnedReward` object to handle\nthe reward for the user.\n\nThe following code shows how to display a `RewardedAd`: \n\n // A simple listener track UserEarnedReward events.\n class ExampleUserEarnedRewardListener :\n public firebase::gma::UserEarnedRewardListener {\n public:\n ExampleUserEarnedRewardListener() { }\n\n void OnUserEarnedReward(const firebase::gma::AdReward& reward) override {\n // Reward the user!\n }\n };\n\n ExampleUserEarnedRewardListener* user_earned_reward_listener =\n new ExampleUserEarnedRewardListener();\n firebase::Future\u003cvoid\u003e result = rewarded_ad-\u003eShow(user_earned_reward_listener);\n\nFAQ\n---\n\nIs there a timeout for the initialization call?\n: After 10 seconds, the Google Mobile Ads C++ SDK completes the\n `firebase::Future` returned by `Initialize()` even if a mediation network still\n hasn't completed initialization.\n\nWhat if some mediation networks aren't ready when I get the initialization callback?\n\n: It's a best practice to load ads after the SDK initialization has completed.\n Even if a mediation network is not ready, the Google Mobile Ads C++ SDK will\n still ask that network for an ad. So if a mediation network finishes\n initializing after the timeout, it can still service future ad requests in that\n session.\n\n: You can continue to poll the initialization status of all adapters throughout\n your app session by calling `GetInitializationStatus()`.\n\nHow do I find out why a particular mediation network isn't ready?\n\n: `AdapterStatus.description()` describes why an adapter is not ready to service\n ad requests. See the source code of our\n [example quickstart app](//github.com/firebase/quickstart-cpp/tree/main/gma/testapp)\n in GitHub for an example of logging mediation adapter status.\n\nAdditional resources\n--------------------\n\n### Example in GitHub\n\n- View the source code of our example [quickstart app](//github.com/firebase/quickstart-cpp/tree/main/gma/testapp) in GitHub."]]