谷歌广告Admob在cocos2dx上通过回调实现底部Banner

Posted 田丰

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了谷歌广告Admob在cocos2dx上通过回调实现底部Banner相关的知识,希望对你有一定的参考价值。

首先说明我的开发平台,以免由于平台问题造成不必要的误解:

cocos2dx-3.4

ndk-r9d

eclipse

 

Admob是谷歌官方广告,已经集成在google_play_service_lib包里面,这里给出百度云下载地址,大家也可以使用官方提供的包。

下载包之后导入到eclipse,将刚导入的项目添加到自己的项目(本文中的项目是AdmobDemo)中做依赖,如下图

 

然后添加以下代码到AdmobDemo的Manifest.xml的<application>下:

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

 

 添加以下权限到Manifest.xml的<manifest>标签下:

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

然后打开下项目的java代码的主Activity(这里是是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

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.util.Timer;
import java.util.TimerTask;

import org.cocos2dx.lib.Cocos2dxActivity;

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

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class AppActivity extends Cocos2dxActivity {
    
    private AdView adView;
    private static final String AD_UNIT_ID = "ca-app-pub-2641376718074288/4798565659";//此处需要申请账号,然后生成应用id
    private static AppActivity _appActiviy;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//横屏:根据传感器横向切换

        RelativeLayout layout = new RelativeLayout(this);  
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
        addContentView(layout,lp);
        RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
        adParams.setMargins(5, 5, 5, 5);
        adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId(AD_UNIT_ID );
        adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();

        adView.loadAd(adRequest);
        adView.setBackgroundColor(Color.BLACK);
        adView.setBackgroundColor(0);
        layout.addView(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 onStart() {
      super.onStart();
  }

@Override
protected void onStop() {
    super.onStop();
}

@Override
protected void onPause() {
    super.onPause();
    if (adView != null) {
        adView.pause();
        }

}

@Override
protected void onResume() {
    super.onResume();
    if (adView != null) {
        adView.resume();
        }

}

@Override
protected void onDestroy() {
    super.onDestroy();
    adView.destroy();
}

@Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
    super.onActivityResult(reqCode, resCode, data);
}
}

到这里广告窗口就已经准备好了,就是等cocos2dx 游戏主程启动时调用就OK了。

在cocos2dx里面调用Java需要使用Jni回调。

下面给出AdmobHelper.cpp类的实现:

#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 = "org/cocos2dx/cpp/AppActivity";

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, AppActivityClassName, "showAd", "()V"))
    {

        t.env->CallStaticVoidMethod(t.classID, 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

通过上面的AdmobHelper::showAd()就可以在C++代码中调用广告了,记得添加AdmobHelper.h到头文件中哦。

 

是不是很简单呢,自己实践一遍吧!

 

此处给出在AdmobDemo在github上的地址:https://github.com/DiaoYung/AdmobDemo;各位可以按此方法添加到自己的项目中即可。博文写的时候正在上传代码,天朝GitHub比较慢。

 

以上是关于谷歌广告Admob在cocos2dx上通过回调实现底部Banner的主要内容,如果未能解决你的问题,请参考以下文章

为啥谷歌 Admob 广告不显示

Admob广告未显示

正在等待Admob插页式广告加载

admob间隙回调事件只能工作一次,而不是第二次。

AdMob 横幅广告未显示 Swift 3

如何从admob添加NATIVE广告?