Ryeeeeee
ymkimwizard
Unscrambler
Go to http://www.google.com/ads/admob/
Sign up with AdMob (Fill all the required fields).
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
p
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.
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
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.
File -> Import -> Android -> Exiting Android code into Workplace -> Next
Root Directory -> Browse “PROJECT_LOCATION\admobTest\cocos2d\cocos” -> Finish
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.
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.
Windows -> Android SDK Manager -> Extras -> “Google Play services” -> Install packages
Copy “ANDROID_SDK_HOME\extras\google\google_play_services\libproject\google-play-services_lib” folder to “PROJECT_LOCATION\admobTest\proj.android”
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).
Edit admobTest -> AndroidManifest.xml -> add this after tag :
|
And add this after tag :
|
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(); } } |
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.
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 |
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 } |
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) |
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.