Chapter 0: References
[For Cococs2d-x 2.2, follow these simple modifications.] (http://www.cocos2d-x.org/forums/6/topics/50259?r=55055#message-55055) 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
Chapter 1: AdMob account
1.1. Creating a free account
Go to Mobile App Monetization - Google 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
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.
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
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.
2.3. Import âlibcocos2dxâ :
Eclipse:
File â Import â Android â Exiting Android code into Workplace â Next
Root Directory â Browse âPROJECT_LOCATION\admobTest\cocos2d\cocosâ â Finish
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.
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
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).
3.4. Editing XML file:
###Eclipse:
Edit admobTest â AndroidManifest.xml â add this after tag :
<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 tag :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
3.5. Editing Java file:
###Eclipse:
Edit admobtest->src->org.cocos2dx.cpp â AppActivity.java
/****************************************************************************
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â :
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â
/*
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â
/*
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â
#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.
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.
capt (6).png (78.2 KB)
capt (7).png (87.4 KB)
capt (8).png (57.7 KB)
capt (9).png (113.0 KB)
capt (1).png (57.6 KB)
capt (2).png (74.9 KB)
capt (3).png (19.2 KB)
capt (11).png (98.0 KB)
capt (10).png (64.9 KB)
capt (5).png (26.6 KB)
SC20140408-165326.png (87.8 KB)