Cocos2d-x 2.x android 集成admob广告(三)banner+interstitial

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

Chapter1:
1、创建一个 cocos2d-x项目 admob_combine
2、Eclipse :import->admob_combine->proj.android
3、Eclipse :Import ->libcocos2dx
选择 目录:……/cocos2d-x2.x/cocos2dx/platform/andorid/java,导入

Chapter2: 准备admob 测试帐号;
MY_INTERSTITIAL_ID = “ca-app-pub-3940256099942544/4411468910”;
MY_BANNER_ID = “ca-app-pub-3940256099942544/6300978111”;

Chapter3:把google-play-service.lib 加入项目android库。

add “google-play-services_lib ” to admob_combine 项目属性下的android 库。

Chapter4: 修改清单文件
1、androidManifest.xml内添加 admob广告支持

!-- 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>

Chapter5 修改java文件
5.1、路径在src/com.walkiway.admob_combine下
5.2、admob_combine.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 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 com.walkiway.admob_combine;

import org.cocos2dx.lib.Cocos2dxActivity;
import com.walkiway.admob_combine.AdmobPlugin;
import android.os.Bundle;
public class admob_combine extends Cocos2dxActivity {

   @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

           AdmobPlugin.setActivity(this);

        }

        @Override
        protected void onDestroy() {
             AdmobPlugin.destroy();

            super.onDestroy();
        }


        @Override
        protected void onResume() {
         AdmobPlugin.resume();

            super.onResume();
        }

        @Override
        protected void onPause() {
              AdmobPlugin.pause();

            super.onPause();
        }
    //add this line,if u using cocos2d-x2.x
        static {
            System.loadLibrary("cocos2dcpp");
        }   
}

Very Important: cocos2d-x 2.x下必须加这句,3.x下则不需要加
static {
System.loadLibrary("cocos2dcpp");
}

5.3、com.walkiway.admob_combine下新建class ->AdmobPlugin
编辑AdmobPlugin 代码如下:

package com.walkiway.admob_combine;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.Gravity;

import android.graphics.Color;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;


import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.AdSize;

import org.cocos2dx.lib.Cocos2dxActivity;

public class AdmobPlugin {
    private static Cocos2dxActivity activity;
    private static final String TAG = "cocos2d";
    private static InterstitialAd interstitial;
    private static AdView adView;

    private final static String MY_INTERSTITIAL_ID = "ca-app-pub-3940256099942544/4411468910";
    private final static String MY_BANNER_ID = "ca-app-pub-3940256099942544/6300978111";

    public static void setActivity(Cocos2dxActivity act){
        activity = act;
    }

    public static void pause(){

          Log.i(TAG,"pause");

        if (adView != null) {
              Log.i(TAG,"adview.pause");
                 adView.pause();
               }

    }
    public static void destroy(){
          Log.i(TAG,"destroy");
        if (adView != null) {
              Log.i(TAG,"adview.destroy");
                 adView.destroy();

               }


    }
    public static void resume(){
          Log.i(TAG,"resume");
        if (adView != null) {
              Log.i(TAG,"adview.resume");
                 adView.resume();
               }

    }
    public static void showBanner(){
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if(adView == null){
                    try{

                            adView = new AdView(activity);
                            adView.setAdSize(AdSize.SMART_BANNER);
                            adView.setAdUnitId(MY_BANNER_ID);


                            RelativeLayout relativeLayout=new RelativeLayout(activity);

                            //TO access mFrameLayout in Cocos2d-V3.3 make it public!!
                            activity.mFrameLayout.addView( relativeLayout );

                        //Banner at the bottom 
                            RelativeLayout.LayoutParams adViewParams = new RelativeLayout.LayoutParams(
                            AdView.LayoutParams.WRAP_CONTENT,AdView.LayoutParams.WRAP_CONTENT);
                            adViewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                            relativeLayout.addView(adView,adViewParams);


                    }catch (Exception e) {
                        Log.e("AdmobPlugin",e.toString());
                    }
                }

                //Nexus7 device
                AdRequest request = new AdRequest.Builder().addTestDevice("E5FDDF2B808A6724F12238F571356547").build();
            // AdRequest request = new AdRequest.Builder().build();
                adView.loadAd(request);
                //Hack so that the banner is displayed at startup of the app??!!!!
                adView.setBackgroundColor(Color.BLACK); 
                adView.setBackgroundColor(0);  
                //---------------------------------------------------------------
                adView.setVisibility(View.VISIBLE);
            }
        });
    }

    public static void hideBanner(){
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if(adView != null){
                    adView.setVisibility(View.GONE);
                }
            }
        });
    }

    public static void showInterstitial(){
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                interstitial = new InterstitialAd(activity);
                interstitial.setAdUnitId(MY_INTERSTITIAL_ID);
                //AdRequest adRequest = new AdRequest.Builder().build();
                //Nexus7 device
                AdRequest adRequest = new AdRequest.Builder().addTestDevice("E5FDDF2B808A6724F12238F571356547").build();
                interstitial.loadAd(adRequest);

                interstitial.setAdListener(new AdListener() {
                    @Override
                    public void onAdLoaded() {
                        activity.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                interstitial.show();
                            }
                        });
                    }
                });
            }
        });
    }
}

Very Important: 修改文件后,这句可能报错。
//TO access mFrameLayout in Cocos2d-V3.3 make it public!!
activity.mFrameLayout.addView( relativeLayout );

所以需要接下来这步。

5.4 修改在libcocos2dx/src/org.cocos2dx.lib/Cocos2dxActivity.java
protected static FrameLayout mFrameLayout;修改

public static FrameLayout mFrameLayout;

Chapter6 修改CPP文件
在class下添加AdmobWrapper.h 和 AdmobWrapper.cpp

//AdmobWrapper.h


#ifndef ADMOB_WRAPPER_H_
#define ADMOB_WRAPPER_H_

class AdmobWrapper{

public:
    static AdmobWrapper * getInstance();

    static void setup();
    // show banner ad
    static void showBanner();
    // hide banner ad
    static void hideBanner();
    // show interstitial
    static void showInterstitial();

};

#endif /* defined(ADMOB_WRAPPER_H_) */
//AdmobWrapper.cpp



#include "AdmobWrapper.h"
#include <jni.h>
#include "platform/android/jni/JniHelper.h"


#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)


#define  JAVA_CLASS_NAME "com/walkiway/admob_combine/AdmobPlugin"

using namespace cocos2d;

static AdmobWrapper * s_Instance = NULL;

AdmobWrapper * AdmobWrapper::getInstance(){
    if(s_Instance == NULL){
        s_Instance = new AdmobWrapper();
    }

    return s_Instance;
}
void AdmobWrapper::setup(){
//void AdmobWrapper::setup(const char* bannerId,const char* lbAudioId){

    //Empty for Android 

    //CCLOG("AdmobWrapper::setup");
}


void AdmobWrapper::showBanner(){
    JniMethodInfo minfo;
    bool isHave = JniHelper::getStaticMethodInfo(minfo,JAVA_CLASS_NAME,"showBanner","()V");
    if(!isHave){
            //CCLOG("jni:openURL showBanner");
    }else{
        minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
    }
}

void AdmobWrapper::hideBanner(){
    JniMethodInfo minfo;
    bool isHave = JniHelper::getStaticMethodInfo(minfo,"hideBanner","()V");
    if(!isHave){
            //CCLOG("jni:openURL hideBanner");
    }else{
        minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
    }
}

void AdmobWrapper::showInterstitial(){
    JniMethodInfo minfo;
    bool isHave = JniHelper::getStaticMethodInfo(minfo,"showInterstitial","()V");
    if(!isHave){
            // CCLOG("jni:openURL showInter");
    }else{
        minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
    }
}

#endif

Very Important: 为了cpp中直接用 类名::函数名() 引用,.h文件中定义为:static void showBanner();

//在需要调用admob的界面cpp加头文件include "AdmobWrapper.h"
//调用interstitial类admob
AdmobWrapper::showInterstitial();

Chapter6: 编辑Android.mk 加入编译AdmobWrapper.cpp

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/AdmobWrapper.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)

终端:
build_native.sh

Eclipse: Run -> Run as Android Application -> Wait ads to show

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