Developers Manual > Cocos2d-x > How To > User Contributed Tutorials > User Tutorial-Integrate AdMob

Integrate Admob ( google play services ) with Cocos2d-x v3.0 Final

Contributed By: victory144

Chapter 0: References

For Cococs2d-x 2.2, follow these simple modifications. Thanks den1812

Change ad position to bottom Thanks adrian_dsl

This tutorial is based, but not limited on these links

Ryeeeeee
ymkimwizard
Unscrambler
stackoverflow, getSize()


Download all files on this tutorial

GitHub

Example Test Ad



Chapter 1: AdMob account

1.1. Creating a free account

Go to http://www.google.com/ads/admob/
Sign up with AdMob (Fill all the required fields).


1.2. Creating a new app ID

a) Sign in to the new AdMob using this URL: https://apps.admob.com/
Monetize -> “+Monetize new app”

b) Select an app to monetize:
Add new app manually -> Platform Android -> add app

Monetize

c) Select ad format and name ad unit:
Banner -> Ad unit name : test app ads -> Save .
Important: Save the “Ad unit ID” for later use.

Monetize-2



Chapter 2: Preparing Eclipse and run Hello World

2.1. Creating a new cocos2d-x project

Using “Cocos console” (Run and make sure “setup.py” on the root folder of cocos2d-x success):
Open CMD (Windows) or Terminal (Mac).
cocos new admobTest –p com.test.admobTest –l cpp –d PROJECT_LOCATION

console


2.2. Import “admobTest\proj.android” :

Eclipse:

Open Eclipse -> Create a new Workplace
File -> New -> Project -> Android -> Android Project from Exiting Code -> Next
Root Directory -> Browse “PROJECT_LOCATION\admobTest\proj.android” -> Finish
Project -> Properties -> Android -> Project build target :
At least Android v3.2 (API Level 13) up to latest 4.4.x. This tutorial based on 4.2.2
Apply -> Ok.

Workplace

Workplace

Workplace

Workplace


2.3. Import “libcocos2dx” :

Eclipse:

File -> Import -> Android -> Exiting Android code into Workplace -> Next
Root Directory -> Browse “PROJECT_LOCATION\admobTest\cocos2d\cocos” -> Finish

Workplace


2.4. Compile CPP files:

Open CMD (Windows) or Terminal (Mac).
Go to “PROJECT_LOCATION\admobTest\proj.android”
Run “Python build_native.py”
Make sure no errors have been occurred.


2.5. Test project on device:

Eclipse:

Connect an Android device (adb enabled).
Run -> Run -> Android Application -> Choose a running Android Device -> OK
Auto Monitor logcat -> yes, Monitor logcat and display … -> Ok (will use this later for device hash)
Make sure “Hello World” showing and working correctly.

Workplace



Chapter 3: Implementing AdMob in Android cocos2d-x 3.0 Final based game

3.1. Downloading “google play services”

Eclipse:

Windows -> Android SDK Manager -> Extras -> “Google Play services” -> Install packages

Workplace


3.2. Copying library to project directory:

Copy “ANDROID_SDK_HOME\extras\google\google_play_services\libproject\google-play-services_lib” folder to “PROJECT_LOCATION\admobTest\proj.android”


3.3. Importing and enlacing google play service:

Eclipse:

File -> Import -> Android -> Exiting Android code into Workplace -> Next
Root Directory -> Browse “PROJECT_LOCATION\ admobTest\proj.android\google-play-services_lib” -> Finish

From Package Explorer -> Select “admobTest“ project -> Right Click -> Properties ->
Android -> Library -> Add -> google-play-services_lib -> Ok -> Apply -> Ok

Make sure all projects (admobTest, google-play-services_lib and libcocos2dx) have the same build target (Adnroid 4.2.2 in this tutorial).

Build Target


3.4. Editing XML file:

Eclipse:

Edit admobTest -> AndroidManifest.xml -> add this after </activity> tag :

1
2
3
4
5
        <meta-data android:name="com.google.android.gms.version"
                   android:value="@integer/google_play_services_version"/>
        <activity android:name="com.google.android.gms.ads.AdActivity"
                  android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

And add this after </application> tag :

1
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

3.5. Editing Java file:

Eclipse:

Edit admobtest->src->org.cocos2dx.cpp -> AppActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011      Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.

http://www.cocos2d-x.org
****************************************************************************/
/*
Copyright (c) 2014 Mudafar
GPLv3
*/

package org.cocos2dx.cpp;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.cocos2dx.lib.Cocos2dxActivity;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

public class AppActivity extends Cocos2dxActivity {

private static AppActivity _appActiviy;
private AdView adView;
private static final String AD_UNIT_ID = "ca-app-pub-0000000000000000/0000000000";

// Helper get display screen to avoid deprecated function use
private Point getDisplaySize(Display d)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        {
            return getDisplaySizeGE11(d);
        }
        return getDisplaySizeLT11(d);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private Point getDisplaySizeGE11(Display d)
    {
        Point p = new Point(0, 0);
        d.getSize(p);
        return p;
    }
    private Point getDisplaySizeLT11(Display d)
    {
        try
        {
            Method getWidth = Display.class.getMethod("getWidth", new Class[] {});
            Method getHeight = Display.class.getMethod("getHeight", new Class[] {});
            return new Point(((Integer) getWidth.invoke(d, (Object[]) null)).intValue(), ((Integer) getHeight.invoke(d, (Object[]) null)).intValue());
        }
        catch (NoSuchMethodException e2) // None of these exceptions should ever occur.
        {
            return new Point(-1, -1);
        }
        catch (IllegalArgumentException e2)
        {
            return new Point(-2, -2);
        }
        catch (IllegalAccessException e2)
        {
            return new Point(-3, -3);
        }
        catch (InvocationTargetException e2)
        {
            return new Point(-4, -4);
        }
    }




    @Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

int width = getDisplaySize(getWindowManager().getDefaultDisplay()).x;


LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams(
width,
LinearLayout.LayoutParams.WRAP_CONTENT);


adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);


AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("HASH_DEVICE_ID")
.build();

adView.loadAd(adRequest);
            adView.setBackgroundColor(Color.BLACK);
            adView.setBackgroundColor(0);
            addContentView(adView,adParams);

            _appActiviy = this;

}


     public static void hideAd()
    {
     _appActiviy.runOnUiThread(new Runnable()
     {

     @Override
     public void run()
     {
if (_appActiviy.adView.isEnabled())
_appActiviy.adView.setEnabled(false);
if (_appActiviy.adView.getVisibility() != 4 )
_appActiviy.adView.setVisibility(View.INVISIBLE);
     }
     });

    }


     public static void showAd()
    {
     _appActiviy.runOnUiThread(new Runnable()
     {

     @Override
     public void run()
     {  
if (!_appActiviy.adView.isEnabled())
_appActiviy.adView.setEnabled(true);
if (_appActiviy.adView.getVisibility() == 4 )
_appActiviy.adView.setVisibility(View.VISIBLE); 
     }
     });

    }

@Override
protected void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}

@Override
protected void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}

    @Override
    protected void onDestroy() {
     adView.destroy();
        super.onDestroy();
    }

}

Very Important:

Change ca-app-pub-0000000000000000/0000000000 with your "Ad unit ID" from Chapter 1.

Change HASH_DEVICE_ID with your actual hashed device id, to work on Test Ad,
and do not risk your AdMob account.

Run admobTest on device and search in logcat for this line to get the "hashed device id" :

1
Use AdRequest.Builder.addTestDevice( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) to get test ads on this device.

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX is the "hashed device id".

showAd() and hideAd() will be used from “C++ class using JNI to show or hide the advertisement on runtime.


3.6. Editing CPP file:

Create a new file “AdmobHelper.h” in “admobTest\Classes”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
Copyright (c) 2014 Mudafar
GPLv3
*/


#ifndef  __ADMOB_HELPER_H_
#define  __ADMOB_HELPER_H_

class AdmobHelper
{
public:
    static void hideAd();
    static void showAd();
    static bool isAdShowing;

};


#endif // __ADMOB_HELPER_H_

Create a new file “AdmobHelper.cpp” in “admobTest\Classes”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
Copyright (c) 2014 Mudafar
GPLv3
*/


#include "AdmobHelper.h"
#include "cocos2d.h"


bool AdmobHelper::isAdShowing = true;

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

#include "platform/android/jni/JniHelper.h"
#include <jni.h>
//#include <android/log.h>


const char* AppActivityClassName = "org/cocos2dx/cpp/AppActivity";

void AdmobHelper::hideAd()
{
    cocos2d::JniMethodInfo t;
    if (cocos2d::JniHelper::getStaticMethodInfo(t, AppActivityClassName, "hideAd", "()V"))
    {

        t.env->CallStaticVoidMethod(t.classID, t.methodID);
        t.env->DeleteLocalRef(t.classID);
        isAdShowing = false;
    }
}



void AdmobHelper::showAd()
{

    cocos2d::JniMethodInfo t;
    if (cocos2d::JniHelper::getStaticMethodInfo(t, AppActivityClassName, "showAd", "()V"))
    {

        t.env->CallStaticVoidMethod(t.classID, t.methodID);
        t.env->DeleteLocalRef(t.classID);
        isAdShowing = true;
    }

}


#else


void AdmobHelper::hideAd()
{
    CCLOG("hideAd() called");
    isAdShowing = false;
    return; //nothing
}


void AdmobHelper::showAd()
{
    CCLOG("showAd() called");
    isAdShowing = true;
    return; //nothing;

}

#endif


3.7. Control Ads visibility:

JNI

Now will make “admobTest” toggle ad when touch the screen:
Edit “HelloWorldScene.cpp”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include "HelloWorldScene.h"
#include "AdmobHelper.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Point origin = Director::getInstance()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    auto closeItem = MenuItemImage::create(
                                           "CloseNormal.png",
                                           "CloseSelected.png",
                                           CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

    closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                                origin.y + closeItem->getContentSize().height/2));

    // create menu, it's an autorelease object
    auto menu = Menu::create(closeItem, NULL);
    menu->setPosition(Point::ZERO);
    this->addChild(menu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label

    auto label = LabelTTF::create("Hello World", "Arial", 24);

    // position the label on the center of the screen
    label->setPosition(Point(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - label->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(label, 1);

    // add "HelloWorld" splash screen"
    auto sprite = Sprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    // add the sprite as a child to this layer
    this->addChild(sprite, 0);

    //////////////////////////////////////////////////////////////////////////
    //Toggle ad when touch the screen

    auto listener = EventListenerTouchOneByOne::create();

    listener->setSwallowTouches(true);

    listener->onTouchBegan = [](Touch* touch, Event* event)
    {
        if (AdmobHelper::isAdShowing)
            AdmobHelper::hideAd();
        else
            AdmobHelper::showAd();

        return true;

    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

    //////////////////////////////////////////////////////////////////////////


    return true;
}


void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
    MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
    return;
#endif

    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}


3.8. Editing MK file:

Edit admobTest -> jni -> hellocpp -> Adnroid.mk
To add the new AdmobHelper Class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := cocos2dcpp_shared

LOCAL_MODULE_FILENAME := libcocos2dcpp

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

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes

LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static
LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static


include $(BUILD_SHARED_LIBRARY)

$(call import-module,2d)
$(call import-module,audio/android)
$(call import-module,Box2D)


Note:

Remember to re-run “Python build-native.py“ after any C++ modification.
Run -> Run -> Wait ads to show -> Touch the screen to toggle visibility of ad.


Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.