Join us for Firebase Summit on November 10, 2021. Tune in to learn how Firebase can help you accelerate app development, release with confidence, and scale with ease. Register

開始

您可以使用 AdMob 在 C++ 應用中展示廣告。本指南向您展示如何與 Firebase 集成並與 Google 移動廣告 SDK 進行交互。

如果這是您第一次通過這個指南會,建議您下載並請跟隨使用AdMob的測試程序

與 Firebase 集成

  1. 完成本步驟設置適用於iOS設置為Android節AdMob和火力地堡添加到您的C ++應用程序。

  2. 在應用的 C++ 代碼中包含以下標頭:

    #include "firebase/admob.h"
    #include "firebase/admob/types.h"
    #include "firebase/app.h"
    #include "firebase/future.h"
    
  3. 將以下內容添加到您的應用程序中的 C++ 代碼中,以使用您的 AdMob 應用程序 ID 初始化 AdMob 庫(應在創建橫幅視圖或插頁式廣告之前執行此代碼):

    #if defined(__ANDROID__)
    // Create the Firebase app.
    firebase::App* app =
        firebase::App::Create(firebase::AppOptions(),
                              your_jni_env,
                              your_android_activity);
    
    // Your Android AdMob app ID.
    const char* kAdMobAppID = "ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN";
    #else
    // Create the Firebase app.
    firebase::App* app =
        firebase::App::Create(firebase::AppOptions());
    
    // Your iOS AdMob app ID.
    const char* kAdMobAppID = "ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN";
    #endif  // __ANDROID__
    
    // Initialize the AdMob library with your AdMob app ID.
    firebase::admob::Initialize(*app, kAdMobAppID);
    

與 Google 移動廣告 SDK 互動

設置廣告單元 ID

在編寫 iOS 和 Android 都支持的 C++ 代碼時,您可能需要使用預處理器指令來定義只能在特定操作系統上編譯的代碼。要在 iOS 和 Android 上顯示橫幅廣告和插頁式廣告,建議您為每個操作系統和每個唯一的廣告展示位置創建一個新的廣告單元 ID。以下廣告單元 ID 是為 iOS 和 Android 創建的,並配置為始終投放測試廣告:

#if defined(__ANDROID__)
// Android ad unit IDs
const char* kBannerAdUnit = "ca-app-pub-3940256099942544/6300978111";
const char* kInterstitialAdUnit = "ca-app-pub-3940256099942544/1033173712";
#else
// iOS ad unit IDs
const char* kBannerAdUnit = "ca-app-pub-3940256099942544/2934735716";
const char* kInterstitialAdUnit = "ca-app-pub-3940256099942544/4411468910";
#endif

設置橫幅視圖

將以下標頭添加到您應用的 C++ 代碼中:

#include "firebase/admob/banner_view.h"

聲明並實例一個BannerView對象:

firebase::admob::BannerView* banner_view;
banner_view = new firebase::admob::BannerView();

創建AdSize和初始化橫幅畫面:

firebase::admob::AdSize ad_size;
ad_size.ad_size_type = firebase::admob::kAdSizeStandard;
ad_size.width = 320;
ad_size.height = 50;
// my_ad_parent is a reference to an iOS UIView or an Android Activity.
// This is the parent UIView or Activity of the banner view.
banner_view->Initialize(static_cast<firebase::admob::AdParent>(my_ad_parent), kBannerAdUnit, ad_size);

設置插頁式廣告

將以下標頭添加到您應用的 C++ 代碼中:

#include "firebase/admob/interstitial_ad.h"

聲明和實例一InterstitialAd對象:

firebase::admob::InterstitialAd* interstitial_ad;
interstitial_ad = new firebase::admob::InterstitialAd();

初始化插頁式廣告:

// my_ad_parent is a reference to an iOS UIView or an Android Activity.
// This is the parent UIView or Activity of the interstitial ad.
interstitial_ad->Initialize(static_cast<firebase::admob::AdParent>(my_ad_parent), kInterstitialAdUnit);

創建 AdMob 廣告請求

AdMob 庫允許您為廣告請求提供自定義定位信息。這是通過設置一個成員所做AdRequest結構。然後該結構被傳遞給BannerView::LoadAd()InterstitialAd::LoadAd()方法。

有關定位和自定義廣告請求的一般信息,請訪問我們的iOSAndroid的定位指南。

這裡的AdRequest使用的一個結構BannerViewInterstitialAd使廣告請求:

struct AdRequest {
  const char **test_device_ids;
  unsigned int test_device_id_count;
  const char **keywords;
  unsigned int keyword_count;
  const KeyValuePair *extras;
  unsigned int extras_count;
  int birthday_day;
  int birthday_month;
  int birthday_year;
  Gender gender;
  ChildDirectedTreatmentState tagged_for_child_directed_treatment;
};

聲明並初始化AdRequest的結構:

// Initialize all the AdRequest struct member values to zero.
firebase::admob::AdRequest my_ad_request = {};

下面的代碼設置的成員值AdRequest結構添加到廣告請求的定位信息:

// If the app is aware of the user's gender, it can be added to the
// targeting information. Otherwise, "unknown" should be used.
my_ad_request.gender = firebase::admob::kGenderUnknown;

// The user's birthday, if known. Note that months are indexed from one.
my_ad_request.birthday_day = 10;
my_ad_request.birthday_month = 11;
my_ad_request.birthday_year = 1976;

// Additional keywords to be used in targeting.
static const char* kKeywords[] = {"AdMob", "C++", "Fun"};
my_ad_request.keyword_count = sizeof(kKeywords) / sizeof(kKeywords[0]);
my_ad_request.keywords = kKeywords;

// "Extra" key value pairs can be added to the request as well.
static const firebase::admob::KeyValuePair kRequestExtras[] = {
    {"the_name_of_an_extra", "the_value_for_that_extra"}};
my_ad_request.extras_count = sizeof(kRequestExtras) / sizeof(kRequestExtras[0]);
my_ad_request.extras = kRequestExtras;

// Register the device IDs associated with any devices that will be used to
// test your app. Below are sample test device IDs used for making the ad request.
static const char* kTestDeviceIDs[] =
    {"2077ef9a63d2b398840261c8221a0c9b",
     "098fe087d987c9a878965454a65654d7"};
my_ad_request.test_device_id_count =
    sizeof(kTestDeviceIDs) / sizeof(kTestDeviceIDs[0]);
my_ad_request.test_device_ids = kTestDeviceIDs;

傳遞AdRequest結構的BannerView::LoadAd()Interstitial::LoadAd()方法:

banner_view->LoadAd(my_ad_request);
interstitial_ad->LoadAd(my_ad_request);

Note: A single `AdRequest` struct can be reused for multiple calls.

使用 Futures 監控方法調用的完成狀態

期貨為你提供一種方法來確定你以前的完成狀態BannerViewInterstitialAd方法調用。當呼叫到由InterstitialAd::LoadAd()方法,例如,新的未來創建並返回。應用程序可以輪詢 Future 的狀態以確定廣告何時加載。一旦 Future 完成,插頁式廣告就可以在您的應用程序中的下一個自然停止點展示。

在大多數方法BannerViewInterstitialAd類都有相應的“最後結果”方法的應用程序可以使用它來獲取最新的未來給定動作。所述InterstitialAd::LoadAd()方法,例如,有一個稱為一個對應的方法InterstitialAd::LoadAdLastResult()它返回一個可以用來檢查到最後一次通話狀態的未來InterstitialAd::LoadAd()方法。

同樣,應用程序可以使用BannerView::InitializeLastResult()方法來獲取表示狀態的未來(和錯誤代碼,如果有的話)的最後調用的BannerView::Initialize()方法。如果其狀態是完整的,它的錯誤代碼是firebase::admob::kAdMobErrorNone ,然後就可以通過調用將橫幅視圖中可見BannerView::Show()方法:

if (banner_view->InitializeLastResult().status() ==
    firebase::kFutureStatusComplete &&
    banner_view->InitializeLastResult().error() ==
    firebase::admob::kAdMobErrorNone) {
  banner_view->Show();
}

一旦未來對到最後一次通話狀態BannerView::Show()方法完成,那麼你就可以在廣告加載到橫幅畫面:

if (banner_view->ShowLastResult().status() ==
    firebase::kFutureStatusComplete &&
    banner_view->ShowLastResult().error() ==
    firebase::admob::kAdMobErrorNone) {
  banner_view->LoadAd(my_ad_request);
}

對於插頁式廣告,使用InterstitialAd::InitializeLastResult()方法來獲取表示狀態的未來(和錯誤代碼,如果有的話)的最後一次通話InterstitialAd::Initialize()方法。如果其狀態是完整的,它的錯誤代碼是firebase::admob::kAdMobErrorNone ,那麼你就可以加載插頁式廣告:

if (interstitial_ad->InitializeLastResult().status() ==
    firebase::kFutureStatusComplete &&
    interstitial_ad->InitializeLastResult().error() ==
    firebase::admob::kAdMobErrorNone) {
  interstitial_ad->LoadAd(my_ad_request);
}

一旦未來對到最後一次通話狀態InterstitialAd::LoadAd()方法完成,那麼你就可以在你的應用的下一個自然停止點展示插頁廣告:

if (interstitial_ad->LoadAdLastResult().status() ==
    firebase::kFutureStatusComplete &&
    interstitial_ad->LoadAdLastResult().error() ==
    firebase::admob::kAdMobErrorNone) {
  interstitial_ad->Show();
}

您還可以註冊要在 Future 完成時調用的回調。此代碼片段使用函數指針進行回調:

// Initialize the interstitial ad.
interstitial_ad->Initialize(static_cast<firebase::admob::AdParent>(my_ad_parent), kInterstitialAdUnit);

// Registers the OnCompletion callback. user_data is a pointer that is passed verbatim
// to the callback as a void*. In this example, we pass the interstitial ad object to be
// used in the OnCompletionCallback function.
interstitial_ad->InitializeLastResult().OnCompletion(OnCompletionCallback, interstitial_ad /*user_data*/);

// The OnCompletion callback function.
static void OnCompletionCallback(const firebase::Future<void>& future, void* user_data) {
  // Called when the Future is completed for the last call to the InterstitialAd::Initialize()
  // method. If the error code is firebase::admob::kAdMobErrorNone, then you're ready to
  // load the interstitial ad.
  firebase::admob::InterstitialAd *interstitial_ad = static_cast<firebase::admob::InterstitialAd*>(user_data);
  if (future.error() == firebase::admob::kAdMobErrorNone) {
    interstitial_ad->LoadAd(my_ad_request);
  }
}

使用偵聽器接收廣告生命週期事件的通知

AdMob廣告提供了一個抽象BannerView::Listener類,你可以擴展和傳遞給BannerView::SetListener()方法,以通知更改為橫幅畫面的呈現狀態和邊界框。類似的抽象InterstitialAd::Listener還提供了能夠為了延伸以變更通知到插頁式廣告的呈現狀態插頁廣告類。

下面是一個擴展的類的示例實現BannerView::Listener類(一個類似的實現可用於插頁廣告):

class ExampleBannerViewListener
    : public firebase::admob::BannerView::Listener {
public:
  ExampleBannerViewListener() {}

  void OnPresentationStateChanged(
      firebase::admob::BannerView* banner_view,
      firebase::admob::BannerView::PresentationState state) override {
    // This method gets called when the banner view's presentation
    // state changes.
  }

  void OnBoundingBoxChanged(
      firebase::admob::BannerView* banner_view,
      firebase::admob::BoundingBox box) override {
    // This method gets called when the banner view's bounding box
    // changes.
  }
};

下一步是什麼

了解如何通過應用獲利與AdMob和確保更換本指南中使用自己的廣告單元ID的測試廣告單元ID。