Cocos2d-x

This guide demonstrates how to include AdMob with Firebase into a newly created Cocos2d-x project. If you don't have a project already, you can follow along by getting the prerequisites and creating a new cocos project from the command line:

cocos new MyGame -l cpp
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID ||
     CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  ...
#endif

Prerequisites

You must have following installed on your machine:

  • The latest version of Cocos2d-x
  • Python 2.7 or higher
  • NDK r10d or higher (only required for Android development)
  • CocoaPods 1.0.0 or higher (only required for iOS development)

Get the AdMob with Firebase C++ SDK

Download the Firebase C++ SDK. Extract the files into the top level directory of your Cocos2d-x project, the same directory that contains your proj.android-studio and proj.ios_mac directories. Name the folder firebase_cpp_sdk.

Set up iOS

The following steps explain how to import the Firebase SDK into a newly created Cocos2d-x iOS project.

  1. Follow the steps to Add Firebase to your app. Once completed, your Xcode project inside the proj.ios_mac/ directory should reference a GoogleService-Info.plist file.

  2. Create a Podfile in your proj.ios_mac/ directory with the following content:

    source 'https://github.com/CocoaPods/Specs.git'
    
    platform :ios, '7.0'
    
    # Replace "MyGame" with the name of your game.
    target 'MyGame-mobile' do
      pod 'Firebase'
      pod 'Firebase/AdMob'
    end
    
  3. Run pod update to install the CocoaPods and open up the MyGame.xcworkspace as instructed by CocoaPods. At this point, you have the Firebase and AdMob iOS SDKs included in your project.

  4. CocoaPods gives warnings about missing $(inherited) on a few properties. Go to the build settings for the MyGame-mobile target in Xcode, and add $(inherited) to the bottom of the list for each of the following build settings:

    • Other Linker Flags
    • Preprocessor Macros
    • Library Search Paths
  5. While you're in the build settings, add $(PROJECT_DIR)/../firebase_cpp_sdk/frameworks/ios/universal to your Framework Search Paths and $(PROJECT_DIR)/../firebase_cpp_sdk/include to your Header Search Paths.

  6. Next, you need to include a reference to the libraries you want to use. Right click your project and select Add Files to "MyGame". From the firebase_cpp_sdk/frameworks/ios/universal directory, select firebase.framework and firebase_admob.framework. Before adding the frameworks, uncheck the Copy Items if Needed option. The build settings you added in the previous step let Xcode know where to find the frameworks.

  7. Add GameController.framework to Build Phases > Link Binary with Libraries.

  8. Follow AdMob's App Transport Security guide to ensure all ads behave correctly on iOS 9 and up.

Checkpoint: You should be able to build and run the iOS app from Xcode.

You now have your iOS project set up with AdMob and Firebase integrated. You're ready to set up the Android project.

Set up Android

The following steps explain how to import the Firebase SDK into a newly created Cocos2d-x Android project.

  1. Open up your proj.android-studio/app/jni/Android.mk and add the lines shown in bold below. Make sure to set FIREBASE_CPP_SDK_DIR to the local path to the Firebase C++ SDK you just downloaded.

    LOCAL_PATH := $(call my-dir)
     
    # The path to the Firebase C++ SDK, in the project's root directory.
    FIREBASE_CPP_SDK_DIR := ../../../firebase_cpp_sdk
     
    APP_ABI := armeabi-v7a x86
    STL := $(firstword $(subst _, ,$(APP_STL)))
    FIREBASE_LIBRARY_PATH := $(FIREBASE_CPP_SDK_DIR)/libs/android/$(TARGET_ARCH_ABI)/$(STL)
     
    include $(CLEAR_VARS)
    LOCAL_MODULE := firebase_app
    LOCAL_SRC_FILES := $(FIREBASE_LIBRARY_PATH)/libapp.a
    LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/$(FIREBASE_CPP_SDK_DIR)/include
    include $(PREBUILT_STATIC_LIBRARY)
     
    include $(CLEAR_VARS)
    LOCAL_MODULE := firebase_feature
    LOCAL_SRC_FILES := $(FIREBASE_LIBRARY_PATH)/libadmob.a
    LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/$(FIREBASE_CPP_SDK_DIR)/include
    include $(PREBUILT_STATIC_LIBRARY)
     
    include $(CLEAR_VARS)
     
    $(call import-add-path,$(LOCAL_PATH)/../../../cocos2d)
    $(call import-add-path,$(LOCAL_PATH)/../../../cocos2d/external)
    $(call import-add-path,$(LOCAL_PATH)/../../../cocos2d/cocos)
    $(call import-add-path,$(LOCAL_PATH)/../../../cocos2d/cocos/audio/include)
     
    LOCAL_MODULE := MyGame_shared
    LOCAL_MODULE_FILENAME := libMyGame
     
    LOCAL_SRC_FILES := hellocpp/main.cpp \
                   ../../../Classes/AppDelegate.cpp \
                   ../../../Classes/HelloWorldScene.cpp
     
    LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../../Classes
     
    # _COCOS_HEADER_ANDROID_BEGIN
    # _COCOS_HEADER_ANDROID_END
     
    LOCAL_STATIC_LIBRARIES := cocos2dx_static
    LOCAL_STATIC_LIBRARIES += firebase_app
    LOCAL_STATIC_LIBRARIES += firebase_feature
     
    # _COCOS_LIB_ANDROID_BEGIN
    # _COCOS_LIB_ANDROID_END
     
    include $(BUILD_SHARED_LIBRARY)
     
    $(call import-module,.)
     
    # _COCOS_LIB_IMPORT_ANDROID_BEGIN
    # _COCOS_LIB_IMPORT_ANDROID_END
    

  2. Check that you can still compile your Cocos app:

    cocos compile -p android --ap android-24 --android-studio --app-abi armeabi-v7a
    
  3. Follow the steps to Add Firebase to your app that is located in the proj.android-studio/ directory.

  4. Include the ads package in your app/build.gradle:

    compile 'com.google.firebase:firebase-ads:11.6.2'
    
  5. Check that you can still compile your Cocos app:

    cocos compile -p android --ap android-42 --android-studio --app-abi armeabi-v7a
    

Your Android project now references the AdMob components in the Firebase C++ SDK.

C++ integration

Now that your iOS and Android projects are referenced in the Firebase C++ SDK, the next step is to start using the SDK and load some ads.

Initialize Firebase and AdMob

It is recommended to initialize Firebase and AdMob as early as possible in your application lifecycle. The most natural place to add this initialization code for a Cocos2d-x project is in the AppDelegate.cpp file:

AppDelegate.cpp


#include "firebase/app.h"
#include "firebase/admob.h"

USING_NS_CC;

bool AppDelegate::applicationDidFinishLaunching() {

  ...

  #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  // Initialize Firebase for Android.
  firebase::App* app = firebase::App::Create(
  firebase::AppOptions(), JniHelper::getEnv(), JniHelper::getActivity());
  // Initialize AdMob.
  firebase::admob::Initialize(*app, "INSERT_YOUR_ADMOB_ANDROID_APP_ID");
  #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  // Initialize Firebase for iOS.
  firebase::App* app = firebase::App::Create(firebase::AppOptions());
  // Initialize AdMob.
  firebase::admob::Initialize(*app, "INSERT_YOUR_ADMOB_IOS_APP_ID");
  #endif
  // Initialize AdMob.
  firebase::admob::Initialize(*app);
  // Create a scene. it's an autorelease object.
  auto scene = HelloWorldScene::createScene();
  // run
  director->runWithScene(scene);
  return true;
}

On Android, creating the Firebase app requires a JNI environment and Activity. The sample code above uses the JniHelper class from Cocos2d-x to supply these parameters.

Get an ad parent

AdMob requires a firebase::admob::AdParent object to initialize each ad format. This object corresponds to an Activity on Android and a UIView on iOS. The following helper class creates a single getAdParent() method that returns the appropriate object depending on the platform.

FirebaseHelper.h

#ifndef __FIREBASE_HELPER_H__
#define __FIREBASE_HELPER_H__

#include "firebase/admob/types.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
extern "C" {
#include <objc/objc.h>
}  // extern "C"
#endif

// Returns a variable that describes the ad parent for the app. On Android
// this will be a JObject pointing to the Activity. On iOS, it's an ID pointing
// to the root view of the view controller.
firebase::admob::AdParent getAdParent();

#endif // __FIREBASE_HELPER_H__

FirebaseHelper.cpp

#include "FirebaseHelper.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/jni/JniHelper.h"
#endif

USING_NS_CC;

firebase::admob::AdParent getAdParent() {
  #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  // Returns the iOS RootViewController's main view (i.e. the EAGLView).
  return (id)Director::getInstance()->getOpenGLView()->getEAGLView();
  #elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  // Returns the Android Activity.
  return JniHelper::getActivity();
  #else
  // A void* for any other environments.
  return 0;
  #endif
}

Add this FirebaseHelper class to your project's Classes/ folder. Make sure to add this file to your Xcode project for iOS and update the local source files in your Android.mk for Android:

LOCAL_SRC_FILES := hellocpp/main.cpp \
                   ../../../Classes/AppDelegate.cpp \
                   ../../../Classes/HelloWorldScene.cpp \
                   ../../../Classes/FirebaseHelper.cpp

Load a banner ad

A complete example of how to load a banner ad is shown below, using the getAdParent() method defined above.

#include "FirebaseHelper.h"

#include "firebase/admob.h"
#include "firebase/admob/types.h"
#include "firebase/app.h"
#include "firebase/future.h"
#include "firebase/admob/banner_view.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <android/log.h>
#include <jni.h>
#include "platform/android/jni/JniHelper.h"
#endif

USING_NS_CC;

bool HelloWorld::init()
{
  // General scene setup ...

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

  // Create and initialize banner view.
  firebase::admob::BannerView* banner_view;
  banner_view = new firebase::admob::BannerView();
  firebase::admob::AdSize ad_size;
  ad_size.ad_size_type = firebase::admob::kAdSizeStandard;
  ad_size.width = 320;
  ad_size.height = 50;
  banner_view->Initialize(getAdParent(), kBannerAdUnit, ad_size);

  // Schedule updates so that the Cocos2d-x update() method gets called.
  this->scheduleUpdate();
  return true;
}

void HelloWorld::update(float delta) {
  // Check that the banner has been initialized.
  if (banner_view->InitializeLastResult().status() ==
      firebase::kFutureStatusComplete) {
    // Check that the banner hasn't started loading.
    if (banner_view->LoadAdLastResult().status() ==
        firebase::kFutureStatusInvalid) {
      // Make the banner visible and load an ad.
      CCLOG("Loading a banner.");
      banner_view->Show();
      firebase::admob::AdRequest my_ad_request = {};
      banner_view->LoadAd(my_ad_request);
    }
  }
}

What's next

Now that you have the Firebase with AdMob SDK integrated into your Cocos2d-x project, you can Interact with the Google Mobile Ads SDK and implement your preferred format:

Send feedback about...

Need help? Visit our support page.