獎勵廣告
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
使用者可選擇與獎勵廣告互動,換取應用程式內獎勵。本指南說明如何使用 Google Mobile Ads C++ SDK,將獎勵廣告整合至 Android 和 iOS 應用程式。
請參閱客戶成功案例:
個案研究 1、
個案研究 2。
必要條件
一律使用測試廣告進行測試
建構及測試應用程式時,請務必使用測試廣告,而非實際的正式廣告。否則帳戶可能會遭到停權。
如要載入測試廣告,最簡單的方法是使用獎勵廣告專用的測試廣告單元 ID,這會因裝置平台而異:
- Android:
ca-app-pub-3940256099942544/5224354917
- iOS:
ca-app-pub-3940256099942544/1712485313
這些 ID 經過特別設定,可針對每項要求傳回測試廣告。您編寫程式碼、測試及偵錯時,可以在自己的應用程式中自由使用。但請務必留意,在發布應用程式前,將這類 ID 換成您自己的廣告單元 ID。
如要進一步瞭解 Mobile Ads 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
,請參閱「使用 Futures 監控方法呼叫的完成狀態」。
載入廣告
載入廣告時,請使用 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
物件只能使用一次,也就是說,獎勵廣告一經顯示,就無法再次顯示。最佳做法是在 OnAdDismissedFullScreenContent()
方法中載入另一個獎勵廣告,FullScreenContentListener
這樣前一個廣告遭到關閉後,系統就會立即開始載入下一個廣告。
顯示廣告並處理獎勵事件
向使用者顯示獎勵廣告前,請務必提供明確的選項,讓他們選擇觀看獎勵廣告素材來換取獎勵。獎勵廣告一定要使用者選擇觀看才會顯示。
顯示廣告時必須提供 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);
常見問題
- 初始化呼叫有逾時限制嗎?
- Google Mobile Ads C++ SDK 初始化 10 秒後,即使有中介服務聯播網尚未完成初始化,SDK 仍會完成
Initialize()
傳回的 firebase::Future
。
- 收到初始化回呼時,如果部分中介服務聯播網尚未就緒,該怎麼辦?
建議您在 SDK 初始化完成後再載入廣告。即使中介服務聯播網尚未就緒,Google Mobile Ads C++ SDK 仍會請求廣告。中介服務聯播網若在逾時後完成初始化,仍能於該工作階段處理後續的廣告請求。
您可以在應用程式工作階段中呼叫 GetInitializationStatus()
,持續輪詢所有轉接程式的初始化狀態。
- 如何找出特定中介服務聯播網尚未就緒的原因?
AdapterStatus.description()
會說明轉接程式無法處理廣告請求的原因。如要查看中介服務介面卡狀態的記錄範例,請參閱 GitHub 上的快速入門導覽課程範例應用程式原始碼。
其他資源
GitHub 中的範例
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-31 (世界標準時間)。
[null,null,["上次更新時間: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."]]