Cocos2d-x 2.x android下集成admob广告(一)顶部banner

前端之家收集整理的这篇文章主要介绍了Cocos2d-x 2.x android下集成admob广告(一)顶部banner前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Chapter1:
1、创建一个 cocos2d-x项目 admob_test
2、用Eclipse import-> admob_test\proj.android
3、Import ->libcocos2dx
选择 目录:……/cocos2d-x2.x/cocos2dx/platform/andorid/java,导入;
4、编译CPP files
4.1选择proj.andorid目录 ,启动终端;
4.2设置ANDROID_SDK_ROOT 和 NDK_ROOT
export ANDROID_SDK_ROOT=”/Users/SamMa/Desktop/AndroidStudio/sdk”
export NDK_ROOT=”/Users/SamMa/Desktop/AndroidStudio/android-ndk-r10d”
4.3 编译 build_native.sh

5、用Eclipse真机测试
选择admob_test 项目右键-> Build Configruation->Target 选择每次提示选择调试设备
选择admob_test 项目右键-> Run as Android App

Chapter2:admob Account
1、申请 admob account
2、创建APP,准备banner 广告,插屏广告;

Chapter3: Implementing AdMob in Android cocos2d-x 2.x based game
1、下载并安装 “Google Play Services” SDK
Eclipse 选择Android SDK Manager 下载 Google Play Services
2、Eclipse Import :google_play_services_lib
路径:/Users/SamMa/Desktop/AndroidStudio/sdk/extras/google/google_play_services/libproject/
3、在项目代码中引用google_play_services_lib


4、尽量使 all projects (admobTest,google-play-services_lib and libcocos2dx) have the same build target (但 Android 4.42 、5.0.1、 5.0.1 在此例真机运行OK).
5、修改清单文件
参考:https://developers.google.com/admob/android/eclipse
5.1 AndroidManifest.xml:

<!-- Include required permissions for Google Mobile Ads to run-->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application>
        <!--This Meta-data tag is required to use Google Play Services.-->
        <Meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

        <!--Include the AdActivity configChanges and theme. -->
        <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
    </application>

需要完成以下三项更改:

为 INTERNET 和 ACCESS_NETWORK_STATE 添加两个 <uses-permission> 标记。INTERNET 的标记是必需的,用于访问互联网以发送广告请求。 ACCESS_NETWORK_STATE 是可选的,用于在发出广告请求前检查是否有可用的互联网连接。

添加一个引用 Google Play 服务版本的 <Meta-data> 标记。这会让 Android 知道您的应用希望使用哪个版本的服务。

添加具有 configChanges 和 theme 属性的 <activity> 元素。当横幅广告被点击或展示插页式广告时,SDK 会使用此活动,而且与其他活动一样,必须在展示之前在清单中声明此活动。

5.2 为应用指定广告单元 ID -修改BannerExample/res/values/strings.xml

<string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>

上面提供的广告单元 ID 仅用于测试,由Google 提供。

6、 Editing Java file
Edit admobtest->src->com->walkiway->admob_test->admob_test.java

/**************************************************************************** ms modified ******* 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. ****************************************************************************/
/* Copyright (c) 2014 Mudafar GPLv3 */
package com.walkiway.admob_test;

import org.cocos2dx.lib.Cocos2dxGLSurfaceView;



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 admob_test extends Cocos2dxActivity{

    private static admob_test  _appActiviy;
    private AdView adView;
    private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/6300978111";

    // 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();
    }

        public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
        // admob_test should create stencil buffer
        glSurfaceView.setEGLConfigChooser(5,6,5,0,16,8);

        return glSurfaceView;
    }

    static {
        System.loadLibrary("cocos2dcpp");
    }   

}

Very Important:private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/6300978111";
应用程序正式发布时,此处应根据admob 账号 APP 里的广告ID 进行修改

7、 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 = "com/walkiway/admob_test/admob_test";

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,"showAd",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

Very Important: const char* AppActivityClassName = "com/walkiway/admob_test/admob_test";
proj.andorid/src目录下路径,最后的.java后缀不要写。

8、Control Ads visibility:
JNI
Now will show “admobTest” ad :

#include "AdmobHelper.h"
AdmobHelper::showAd();

9、编辑 .MK file:
Edit admobTest -> jni > Android.mk

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 += chipmunk_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static

include $(BUILD_SHARED_LIBRARY)

$(call import-module,cocos2dx)
$(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl)
$(call import-module,CocosDenshion/android)
$(call import-module,extensions)
$(call import-module,external/Box2D)
$(call import-module,external/chipmunk)

最后: Note: 终端: build-native.sh Eclipse: Run -> Run as Android Application -> Wait ads to show

猜你在找的Cocos2d-x相关文章