cocos2d-x 3.0 final 如何在android里添加广告(AppActivity.java注释部分是原作者原创,未验证)

ms:先参考下原文章:
http://discuss.cocos2d-x.org/t/cocos3-0-tutorial-integrate-admob-google-play-services-with-cocos2d-x-v3-0-final/12798

接下来转载:
http://blog.csdn.net/leelyn/article/details/32712315
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 plaincopy在CODE上查看代码片派生到我的代码片

      <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"/>  

[html] view plaincopy在CODE上查看代码片派生到我的代码片

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

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

[java] view plaincopy在CODE上查看代码片派生到我的代码片

/**************************************************************************** 
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 

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is 
furnished to do so, subject to the following conditions: 

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software. 

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
THE SOFTWARE. 
 ****************************************************************************/  
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 android.widget.RelativeLayout;  

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-4321574338161624/7981547992";//填写你的广告单元ID  

    // 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;  
        //顶部显示1,如果想在顶部显示广告请将顶部显示1和顶部显示2注释去掉,然后注释掉底部显示1,底部显示2,底部显示3  
//      LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams(  
//              width, LinearLayout.LayoutParams.WRAP_CONTENT);  

        //底部显示1  
        RelativeLayout relativeLayout = new RelativeLayout(this);//  
        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)就可以了  

        //底部显示2  
        RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(width,  
                AdView.LayoutParams.WRAP_CONTENT);//  
        adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);//  

                //广告  
        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();  
        //底部显示3  
        relativeLayout.addView(adView,adParams);//  
        //广告请求  
                adView.loadAd(adRequest);  
        adView.setBackgroundColor(Color.BLACK);  
        adView.setBackgroundColor(0);  
        //顶部显示2  
        //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();  
    }  
}  

记住要改成你的广告标识

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

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

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片

#pragma once  

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

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

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片

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

USING_NS_CC;  

bool AdmobHelper::isAdShowing = true;  

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

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

void AdmobHelper::hideAd(){  
    cocos2d::JniMethodInfo t;  
    if(cocos2d::JniHelper::getStaticMethodInfo(t,AppActivityCalssName,"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,AppActivityCalssName,"showAd","()V")){  
        t.env->CallStaticVoidMethod(t.classID,t.methodID);  
        t.env->DeleteLocalRef(t.classID);  
        isAdShowing = true;  
    }  
}  

#else  

void AdmobHelper::hideAd(){  
    log("hideAd() called");  
    isAdShowing = false;  
    return;  
}  

void AdmobHelper::showAd(){  
    log("showAd() called");  
    isAdShowing = true;  
    return;  
}  

#endif  

然后,在HelloWorldScene.cpp中调用它

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片

#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();  
    Vec2 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(Vec2(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(Vec2::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(Vec2(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(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));  

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

    //Ad  
    auto listener = EventListenerTouchOneByOne::create();  
    listener->setSwallowTouches(true);//如果不加入此句消息依旧会向下传递    
    listener->onTouchBegan = [](Touch* touch,Event* event){  
        if(AdmobHelper::isAdShowing)  
            AdmobHelper::hideAd();  
        else  
            AdmobHelper::showAd();  
        return true;  
    };  
    this->_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  
}  

别忘了 Adnroid.mk文件

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片

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  
# LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static  
# LOCAL_WHOLE_STATIC_LIBRARIES += spine_static  
# LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static  
# LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static  
# LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static  


include $(BUILD_SHARED_LIBRARY)  

$(call import-module,.)  
$(call import-module,audio/android)  

# $(call import-module,Box2D)  
# $(call import-module,editor-support/cocosbuilder)  
# $(call import-module,editor-support/spine)  
# $(call import-module,editor-support/cocostudio)  
# $(call import-module,network)  
# $(call import-module,extensions)  

最后,运行吧

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值