cocos2d-x 3.X 如何在android里添加广告

1,使用的是谷歌的AdMob的广告

先去注册个账号吧http://www.google.com/ads/admob/ 

怎么注册就不说了,注册需要翻墙,如何翻墙,自己解决,注册太长了,就那么回事,不说了。注册好后,登陆界面如下




按顺序点击,填写好相关内容后,你会得到这个界面


为什么是中文,google自动帮我翻译了,有时候翻译有时候不翻译,这里就不说了,看到广告单元ID没,把他记下来,


2,现在,新建一个的cocos2d-X 3.0的工程,你环境是不是按照上一篇的环境搭建篇搭建的呢,不是的话还不快去

茯苓新admobTest-P com.test.admobTest-L CPP-D D:\工作

先用日食导入工程,你看的很清楚,不是对,是Eclispe的

1)先导入libcocos2dx库

有关Eclispe中,文件 - >导入 - >现有的Andr​​oid代码放入工作区

然后点击浏览...找到如下图路径


然后导入,库导入完了再导入admobTest工程

还是按照刚才的方法,不过赵路径的时候是下面这个



当你导入以后,工程会自动运行 “的Python build_native.py”,如下图



你就直接连接手机运行就OK了,


3,下面,开始添加广告,

1)关闭Eclispe的,

2)打开翻墙软件,

3)打开SDK 的manager.exe选择工具- >选项...,如下配置


然后,关闭SDK 的manager.exe重新打开,更新以下项目



更新完毕后,将下图中的文件夹


复制到你的工程目录下




打开Eclipse中,按照导入库方式导入谷歌播放services_lib

导入后,右键点击admobTest工程,选择属性属性,然后如图设置


将谷歌 - 播放services_lib加到工程中


修改 的AndroidManifest.xml文件,如图

文本在此

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.       <meta-data android:name="com.google.android.gms.version"  
  2.                    android:value="@integer/google_play_services_version"/>  
  3. <activity android:name="com.google.android.gms.ads.AdActivity"  
  4.               android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>  


打开工程中的AppActivity.java文件,修改如下


[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**************************************************************************** 
  2. Copyright (c) 2008-2010 Ricardo Quesada 
  3. Copyright (c) 2010-2012 cocos2d-x.org 
  4. Copyright (c) 2011      Zynga Inc. 
  5. Copyright (c) 2013-2014 Chukong Technologies Inc. 
  6.   
  7. http://www.cocos2d-x.org 
  8.  
  9. Permission is hereby granted, free of charge, to any person obtaining a copy 
  10. of this software and associated documentation files (the "Software"), to deal 
  11. in the Software without restriction, including without limitation the rights 
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
  13. copies of the Software, and to permit persons to whom the Software is 
  14. furnished to do so, subject to the following conditions: 
  15.  
  16. The above copyright notice and this permission notice shall be included in 
  17. all copies or substantial portions of the Software. 
  18.  
  19. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
  20. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
  21. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
  22. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
  23. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
  24. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
  25. THE SOFTWARE. 
  26.  ****************************************************************************/  
  27. package org.cocos2dx.cpp;  
  28.   
  29. import java.lang.reflect.InvocationTargetException;  
  30. import java.lang.reflect.Method;  
  31.   
  32. import org.cocos2dx.lib.Cocos2dxActivity;  
  33.   
  34. import android.annotation.TargetApi;  
  35. import android.graphics.Color;  
  36. import android.graphics.Point;  
  37. import android.os.Build;  
  38. import android.os.Bundle;  
  39. import android.view.Display;  
  40. import android.view.View;  
  41. import android.view.WindowManager;  
  42. import android.widget.LinearLayout;  
  43. import android.widget.RelativeLayout;  
  44.   
  45. import com.google.android.gms.ads.AdSize;  
  46. import com.google.android.gms.ads.AdRequest;  
  47. import com.google.android.gms.ads.AdView;  
  48.   
  49. public class AppActivity extends Cocos2dxActivity {  
  50.     private static AppActivity _appActiviy;  
  51.     private AdView adView;  
  52.     private static final String AD_UNIT_ID = "ca-app-pub-4321574338161624/7981547992";//填写你的广告单元ID  
  53.   
  54.     // Helper get display screen to avoid deprecated function use  
  55.     private Point getDisplaySize(Display d) {  
  56.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {  
  57.             return getDisplaySizeGE11(d);  
  58.         }  
  59.         return getDisplaySizeLT11(d);  
  60.     }  
  61.   
  62.     @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)  
  63.     private Point getDisplaySizeGE11(Display d) {  
  64.         Point p = new Point(00);  
  65.         d.getSize(p);  
  66.         return p;  
  67.     }  
  68.   
  69.     private Point getDisplaySizeLT11(Display d) {  
  70.         try {  
  71.             Method getWidth = Display.class.getMethod("getWidth",  
  72.                     new Class[] {});  
  73.             Method getHeight = Display.class.getMethod("getHeight",  
  74.                     new Class[] {});  
  75.             return new Point(  
  76.                     ((Integer) getWidth.invoke(d, (Object[]) null)).intValue(),  
  77.                     ((Integer) getHeight.invoke(d, (Object[]) null)).intValue());  
  78.         } catch (NoSuchMethodException e2) // None of these exceptions should  
  79.                                             // ever occur.  
  80.         {  
  81.             return new Point(-1, -1);  
  82.         } catch (IllegalArgumentException e2) {  
  83.             return new Point(-2, -2);  
  84.         } catch (IllegalAccessException e2) {  
  85.             return new Point(-3, -3);  
  86.         } catch (InvocationTargetException e2) {  
  87.             return new Point(-4, -4);  
  88.         }  
  89.     }  
  90.   
  91.     @Override  
  92.     protected void onCreate(Bundle savedInstanceState) {  
  93.         super.onCreate(savedInstanceState);  
  94.   
  95.         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
  96.         //获取显示宽度  
  97.         int width = getDisplaySize(getWindowManager().getDefaultDisplay()).x;  
  98.         //顶部显示1,如果想在顶部显示广告请将顶部显示1和顶部显示2注释去掉,然后注释掉底部显示1,底部显示2,底部显示3  
  99. //      LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams(  
  100. //              width, LinearLayout.LayoutParams.WRAP_CONTENT);  
  101.           
  102.         //底部显示1  
  103.         RelativeLayout relativeLayout = new RelativeLayout(this);//  
  104.         this.frameLayout.addView(relativeLayout);//3.0 中,先打开Cocos2dxActivity.java文件,在52行,就是private static Context sContext = null;之后添加public static FrameLayout framelayout;然后在public void init() 函数中,将FrameLayout framelayout = new FrameLayout(this);改成framelayout = new FrameLayout(this);就可以了使用这句代码了,3.1.1之后什么都不要动,直接写成this.mFrameLayout.add(relativeLayout)就可以了  
  105.   
  106.         //底部显示2  
  107.         RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(width,  
  108.                 AdView.LayoutParams.WRAP_CONTENT);//  
  109.         adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);//  
  110.           
  111.                 //广告  
  112.         adView = new AdView(this);  
  113.         adView.setAdSize(AdSize.BANNER);  
  114.         adView.setAdUnitId(AD_UNIT_ID);  
  115.   
  116.         AdRequest adRequest = new AdRequest.Builder()  
  117.                 .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)  
  118.                 .addTestDevice("HASH_DEVICE_ID").build();  
  119.         //底部显示3  
  120.         relativeLayout.addView(adView,adParams);//  
  121.         //广告请求  
  122.                 adView.loadAd(adRequest);  
  123.         adView.setBackgroundColor(Color.BLACK);  
  124.         adView.setBackgroundColor(0);  
  125.         //顶部显示2  
  126.         //addContentView(adView, adParams);  
  127.         //赋值  
  128.         _appActiviy = this;  
  129.   
  130.     }  
  131.   
  132.     public static void hideAd() {  
  133.         _appActiviy.runOnUiThread(new Runnable() {  
  134.   
  135.             @Override  
  136.             public void run() {  
  137.                 if (_appActiviy.adView.isEnabled())  
  138.                     _appActiviy.adView.setEnabled(false);  
  139.                 if (_appActiviy.adView.getVisibility() != 4)  
  140.                     _appActiviy.adView.setVisibility(View.INVISIBLE);  
  141.             }  
  142.         });  
  143.   
  144.     }  
  145.   
  146.     public static void showAd() {  
  147.         _appActiviy.runOnUiThread(new Runnable() {  
  148.   
  149.             @Override  
  150.             public void run() {  
  151.                 if (!_appActiviy.adView.isEnabled())  
  152.                     _appActiviy.adView.setEnabled(true);  
  153.                 if (_appActiviy.adView.getVisibility() == 4)  
  154.                     _appActiviy.adView.setVisibility(View.VISIBLE);  
  155.             }  
  156.         });  
  157.   
  158.     }  
  159.   
  160.     @Override  
  161.     protected void onResume() {  
  162.         super.onResume();  
  163.         if (adView != null) {  
  164.             adView.resume();  
  165.         }  
  166.     }  
  167.   
  168.     @Override  
  169.     protected void onPause() {  
  170.         if (adView != null) {  
  171.             adView.pause();  
  172.         }  
  173.         super.onPause();  
  174.     }  
  175.   
  176.     @Override  
  177.     protected void onDestroy() {  
  178.         adView.destroy();  
  179.         super.onDestroy();  
  180.     }  
  181. }  


记住要改成你的广告标识

JAVA的完成了,下面就是C + +的了

新建一个AdmobHelper.h文件,内容如下

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #pragma once  
  2.   
  3. class AdmobHelper{  
  4. public:  
  5.     static void hideAd();  
  6.     static void showAd();  
  7.     static bool isAdShowing;  
  8. };  


新建一个 AdmobHelper.cpp文件,内容如下

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include "AdmobHelper.h"  
  2. #include "cocos2d.h"  
  3.   
  4. USING_NS_CC;  
  5.   
  6. bool AdmobHelper::isAdShowing = true;  
  7.   
  8. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)  
  9. #include "platform/android/jni/JniHelper.h"  
  10. #include <jni.h>  
  11.   
  12. const char* AppActivityCalssName = "org/cocos2dx/cpp/AppActivity";  
  13.   
  14. void AdmobHelper::hideAd(){  
  15.     cocos2d::JniMethodInfo t;  
  16.     if(cocos2d::JniHelper::getStaticMethodInfo(t,AppActivityCalssName,"hideAd","()V")){  
  17.         t.env->CallStaticVoidMethod(t.classID,t.methodID);  
  18.         t.env->DeleteLocalRef(t.classID);  
  19.         isAdShowing = false;  
  20.     }  
  21. }  
  22.   
  23. void AdmobHelper::showAd(){  
  24.     cocos2d::JniMethodInfo t;  
  25.     if(cocos2d::JniHelper::getStaticMethodInfo(t,AppActivityCalssName,"showAd","()V")){  
  26.         t.env->CallStaticVoidMethod(t.classID,t.methodID);  
  27.         t.env->DeleteLocalRef(t.classID);  
  28.         isAdShowing = true;  
  29.     }  
  30. }  
  31.   
  32. #else  
  33.   
  34. void AdmobHelper::hideAd(){  
  35.     log("hideAd() called");  
  36.     isAdShowing = false;  
  37.     return;  
  38. }  
  39.   
  40. void AdmobHelper::showAd(){  
  41.     log("showAd() called");  
  42.     isAdShowing = true;  
  43.     return;  
  44. }  
  45.   
  46. #endif  


然后,在 HelloWorldScene.cpp中调用它

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include "HelloWorldScene.h"  
  2. #include "AdmobHelper.h"  
  3.   
  4. USING_NS_CC;  
  5.   
  6. Scene* HelloWorld::createScene()  
  7. {  
  8.     // 'scene' is an autorelease object  
  9.     auto scene = Scene::create();  
  10.       
  11.     // 'layer' is an autorelease object  
  12.     auto layer = HelloWorld::create();  
  13.   
  14.     // add layer as a child to scene  
  15.     scene->addChild(layer);  
  16.   
  17.     // return the scene  
  18.     return scene;  
  19. }  
  20.   
  21. // on "init" you need to initialize your instance  
  22. bool HelloWorld::init()  
  23. {  
  24.     //  
  25.     // 1. super init first  
  26.     if ( !Layer::init() )  
  27.     {  
  28.         return false;  
  29.     }  
  30.       
  31.     Size visibleSize = Director::getInstance()->getVisibleSize();  
  32.     Vec2 origin = Director::getInstance()->getVisibleOrigin();  
  33.   
  34.     /  
  35.     // 2. add a menu item with "X" image, which is clicked to quit the program  
  36.     //    you may modify it.  
  37.   
  38.     // add a "close" icon to exit the progress. it's an autorelease object  
  39.     auto closeItem = MenuItemImage::create(  
  40.                                            "CloseNormal.png",  
  41.                                            "CloseSelected.png",  
  42.                                            CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));  
  43.       
  44.     closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,  
  45.                                 origin.y + closeItem->getContentSize().height/2));  
  46.   
  47.     // create menu, it's an autorelease object  
  48.     auto menu = Menu::create(closeItem, NULL);  
  49.     menu->setPosition(Vec2::ZERO);  
  50.     this->addChild(menu, 1);  
  51.   
  52.     /  
  53.     // 3. add your codes below...  
  54.   
  55.     // add a label shows "Hello World"  
  56.     // create and initialize a label  
  57.       
  58.     auto label = LabelTTF::create("Hello World""Arial", 24);  
  59.       
  60.     // position the label on the center of the screen  
  61.     label->setPosition(Vec2(origin.x + visibleSize.width/2,  
  62.                             origin.y + visibleSize.height - label->getContentSize().height));  
  63.   
  64.     // add the label as a child to this layer  
  65.     this->addChild(label, 1);  
  66.   
  67.     // add "HelloWorld" splash screen"  
  68.     auto sprite = Sprite::create("HelloWorld.png");  
  69.   
  70.     // position the sprite on the center of the screen  
  71.     sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));  
  72.   
  73.     // add the sprite as a child to this layer  
  74.     this->addChild(sprite, 0);  
  75.   
  76.     //Ad  
  77.     auto listener = EventListenerTouchOneByOne::create();  
  78.     listener->setSwallowTouches(true);//如果不加入此句消息依旧会向下传递    
  79.     listener->onTouchBegan = [](Touch* touch,Event* event){  
  80.         if(AdmobHelper::isAdShowing)  
  81.             AdmobHelper::hideAd();  
  82.         else  
  83.             AdmobHelper::showAd();  
  84.         return true;  
  85.     };  
  86.     this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);  
  87.       
  88.     return true;  
  89. }  
  90.   
  91.   
  92. void HelloWorld::menuCloseCallback(Ref* pSender)  
  93. {  
  94. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)  
  95.     MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");  
  96.     return;  
  97. #endif  
  98.   
  99.     Director::getInstance()->end();  
  100.   
  101. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)  
  102.     exit(0);  
  103. #endif  
  104. }  


别忘了   Adnroid.mk文件

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. LOCAL_PATH := $(call my-dir)  
  2.   
  3. include $(CLEAR_VARS)  
  4.   
  5. LOCAL_MODULE := cocos2dcpp_shared  
  6.   
  7. LOCAL_MODULE_FILENAME := libcocos2dcpp  
  8.   
  9. LOCAL_SRC_FILES := hellocpp/main.cpp \  
  10.                    ../../Classes/AppDelegate.cpp \  
  11.                    ../../Classes/HelloWorldScene.cpp \  
  12.                    ../../Classes/AdmobHelper.cpp  
  13.   
  14. LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes  
  15.   
  16. LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static  
  17. LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static  
  18.   
  19. # LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static  
  20. # LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static  
  21. # LOCAL_WHOLE_STATIC_LIBRARIES += spine_static  
  22. # LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static  
  23. # LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static  
  24. # LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static  
  25.   
  26.   
  27. include $(BUILD_SHARED_LIBRARY)  
  28.   
  29. $(call import-module,.)  
  30. $(call import-module,audio/android)  
  31.   
  32. # $(call import-module,Box2D)  
  33. # $(call import-module,editor-support/cocosbuilder)  
  34. # $(call import-module,editor-support/spine)  
  35. # $(call import-module,editor-support/cocostudio)  
  36. # $(call import-module,network)  
  37. # $(call import-module,extensions)  


最后,运行吧


转自:http://blog.csdn.net/leelyn/article/details/32712315

转载于:https://my.oschina.net/fgreshrht/blog/379003

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值