考虑到以下两点:
1. Cocos2d-x从3.7版开始优化对Android Studio的支持,相信这一趋势还会继续。可惜目前相关帮助文档还不完善,很多东西需要自己摸索。
2. 多盟广告平台的官方帮助文档没有针对Cocos2d-x。
所以在此对自己所学所得做一些总结,也希望能帮助到那些处在摸索之中的朋友们。
本文所用cocos2d-x为3.8版,android studio为1.3.2版,多盟SDK为4.5.4版。
准备工作
1)进入多盟官网,注册账户。注册时需要上传身份证正反面照片和银行账户,并等待审核。审核大概需要一两天时间。
开干正事
1) 在搞懂如何添加之前,建议不要直接在自己的工程里面添加,最好新建一个HelloWorld项目用于试验。关于如何新建一个Android studio版的HelloWorld,请参考上一篇博文。
2) 打开下载下来的多盟SDK->lib,将其中的domob_android_sdk.jar考到新建的HelloWorld项目下proj.android-studio->app->libs->armeabi文件夹中。并在android studio中找到domob_android_sdk.jar(在jiniLibs->armeabi下面),右击,选择Add As Library。这样就把多盟的SDK添加到我们的项目中了。如果是eclipse,这一步稍有区别,需要通过Java Build Path添加。
3) 在android studio里面打开AndroidManifest.xml。相信你能找到这个文件!往里面添加两样东西:在<application>之前为多盟SDK添加权限,并在<application>里面添加多盟Activity声明。添加完后完整代码如下所示:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.istudy.CocosDomob" android:installLocation="auto" android:versionCode="2" android:versionName="2.0"> <!--多盟官网考来的部分1开始--> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19"/> <!-- 网络访问权限 --> <uses-permission android:name="android.permission.INTERNET" /> <!-- 获取网络信息状态,如当前的网络连接是否有效 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 读取手机状态 --> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- 允许程序写入外部存储,如SD卡上写文件 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 获取错略位置--> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 获取WiFi状态 --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 以下权限为可选权限,主要是品牌广告会用到,如果您没有添加,需要这些效果的品牌广告将不会投放到您的应用上 --> <!-- 震动权限 --> <uses-permission android:name="android.permission.VIBRATE" /> <!--多盟官网考来的部分1结束--> <uses-feature android:glEsVersion="0x00020000" /> <application tools:replace="android:label" android:label="@string/app_name" android:allowBackup="true" android:icon="@mipmap/ic_launcher"> <!-- Tell Cocos2dxActivity the name of our .so --> <Meta-data android:name="android.app.lib_name" android:value="cocos2dcpp" /> <!-- 多盟官网考来的部分2开始 --> <activity android:name="cn.domob.android.ads.DmActivity" android:theme="@android:style/Theme.Translucent"></activity> <!--多盟官网考来的部分2结束--> <activity android:name="org.cocos2dx.cpp.AppActivity" android:screenOrientation="Portrait" android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET"/> </manifest>注意<application>里面的第一行tools:replace="android:label"本来是没有的,但是如果不添加该代码,编译时会提示出错(发生定义冲突),并给出添加该代码的建议。该代码还需配合第三行的xmlns:tools="http://schemas.android.com/tools"使用。
在Activity声明部分,我们把所有广告类型都声明了一遍,其实不必如此,按需添加即可。
4) 在android studio里面找到AppActivity(在java->org.cocos2dx.cpp下面),往里面添加显示广告的java代码,但是由于我们要在cocos2d-x的HelloWorld场景里面(也就是C++代码里面)添加广告,所以此处需要做一些接口函数,而不是像多盟官方文件UserGuide.pdf里面直接令其显示。添加完后,完整代码如下所示:
AppActivity
package org.cocos2dx.cpp; import org.cocos2dx.lib.Cocos2dxActivity; import cn.domob.android.ads.AdEventListener; //import cn.domob.android.ads.AdManager; import cn.domob.android.ads.AdManager.ErrorCode; import cn.domob.android.ads.AdView; import cn.domob.android.ads.InterstitialAd; import cn.domob.android.ads.InterstitialAdListener; //import android.app.ActionBar; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; //import android.view.ViewGroup; import android.widget.RelativeLayout; public class AppActivity extends Cocos2dxActivity { //声明应用和应用ID private static AppActivity _AppActivity; public static final String PUBLISHER_ID = "你的应用ID"; //声明插屏广告和插屏广告ID private InterstitialAd mInterstitialAd; public static final String InterstitialPPID = "你的插屏广告ID"; //声明广告条层和广告位ID private static RelativeLayout bannerLayout; private AdView mAdview; public static final String InlinePPID="你的广告条ID"; //声明handler用于发送消息 private static Handler handler; @Override protected void onCreate(Bundle savedIntanceState){ super.onCreate(savedIntanceState); //创建插屏广告 if (mInterstitialAd != null) { return; } mInterstitialAd = new InterstitialAd(this,PUBLISHER_ID,InterstitialPPID); mInterstitialAd.setInterstitialAdListener(new InterstitialAdListener() { @Override public void onInterstitialAdReady() { Log.i("DomobSDKDemo","onAdReady"); } @Override public void onLandingPageOpen() { Log.i("DomobSDKDemo","onLandingPageOpen"); } @Override public void onLandingPageClose() { Log.i("DomobSDKDemo","onLandingPageClose"); } @Override public void onInterstitialAdPresent() { Log.i("DomobSDKDemo","onLandingAdPresent"); } @Override public void onInterstitialAdDismiss() { mInterstitialAd.loadInterstitialAd(); Log.i("DomobSDKDemo","onInterstitialAdDismiss"); } @Override public void onInterstitialAdFailed(ErrorCode errorCode) { Log.i("DomobSDKDemo","onInterstitialAdFailed"); } @Override public void onInterstitialAdLeaveApplication() { Log.i("DomobSDKDemo","onInterstitialAdLeaveApplication"); } @Override public void onInterstitialAdClicked(InterstitialAd arg0) { Log.i("DomobSDKDemo","onInterstitialAdClicked"); } }); mInterstitialAd.loadInterstitialAd(); //创建广告条容器 bannerLayout = new RelativeLayout(this); RelativeLayout.LayoutParams parentLayoutParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); this.addContentView(bannerLayout,parentLayoutParams); //加载广告 handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0:// showBannerAd() if (bannerLayout.getChildCount() == 0) { //创建广告条 //setContentView(R.layout.banner); //mAdContainer = (RelativeLayout) findViewById(R.id.adcontainer); //注意这两行注释掉的代码来自多盟文档,不可用 mAdview = new AdView(AppActivity.this,InlinePPID); mAdview.setKeyword("game"); mAdview.setUserGender("male"); mAdview.setUserBirthdayStr("2000-08-08"); mAdview.setUserPostcode("123456"); mAdview.setAdEventListener(new AdEventListener() { @Override public void onEventAdReturned(AdView adView) { Log.i("DomobSDKDemo","onDomobAdReturned"); } @Override public void onAdFailed(AdView adView,ErrorCode errorCode) { Log.i("DomobSDKDemo","onDomobAdFailed"); } @Override public void onAdOverlayPresented(AdView adView) { Log.i("DomobSDKDemo","overlayPresented"); } @Override public void onAdOverlayDismissed(AdView adView) { Log.i("DomobSDKDemo","Overrided be dismissed"); } @Override public void onLeaveApplication(AdView adView) { Log.i("DomobSDKDemo","onDomobLeaveApplication"); } @Override public void onAdClicked(AdView adView) { Log.i("DomobSDKDemo","onDomobAdClicked"); } @Override public Context onAdRequiresCurrentContext() { //return null; return AppActivity.this; } }); //添加广告并设置它的位置 RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); //layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.TRUE); layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL,RelativeLayout.TRUE); bannerLayout.addView(AppActivity.this.mAdview,layoutParams); }else{ if (mAdview != null) { mAdview.setVisibility(View.VISIBLE); mAdview.requestRefreshAd(); } } break; case 1: //hideBannerAd() if (mAdview != null) { mAdview.setVisibility(View.GONE); } break; case 2: //initInterstitialAd() break; case 3: //showInterstitialAd() if (mInterstitialAd != null) { if (mInterstitialAd.isInterstitialAdReady()) { mInterstitialAd.showInterstitialAd(AppActivity.this); } else { Log.i("DomobSDKCocos2d-xDemo","Interstitial Ad is not ready"); mInterstitialAd.loadInterstitialAd(); } } else { Log.i("DomobSDKCocos2d-xDemo","Interstitial Ad is not init"); } default: break; } } }; } //打开和关闭广告 public static void showBannerAd() { handler.sendEmptyMessage(0); } public static void hideBannerAd() { handler.sendEmptyMessage(1); } public static void initInterstitialAd() { handler.sendEmptyMessage(2); } public static void showInterstitialAd() { handler.sendEmptyMessage(3); } }
注意这里和多盟官方文档UserGuide.pdf的两点区别。1,我们的场景都是通过cocos2d-x创建的,因此本身没有布局文件xml,所以我们不通过布局文件以及setContentView(R.layout.banner)和mAdContainer=(RelativeLayout)findViewById(R.id.adcontainer)两条命令来创建广告条,而是选择通过代码来创建一个RelativeLayout布局对象作为广告条的容器。2,我们通过Handler来发送消息,从而起到控制广告开关的作用。
5) 在cocos2d-x的classes下面添加一个C++类,命名为DomobAd,里面通过jni把java的广告开关函数转换成了C++函数,以便在cocos2d-x场景里调用。完整代码如下所示:
DomobAd.h
#ifndef CLASSES_DOMOBAD_H #define CLASSES_DOMOBAD_H class DomobAd { public: static void showBannerAd(); static void hideBannerAd(); static void showInterstitialAd(); }; #endif //CLASSES_DOMOBAD_H
#include "DomobAd.h" #include "cocos2d.h" USING_NS_CC; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "platform/android/jni/JniHelper.h" #include <jni.h> const char* AppActivityCalssName = "org/cocos2dx/cpp/AppActivity"; //显示广告条 void DomobAd::showBannerAd() { cocos2d::JniMethodInfo showBanner; if (cocos2d::JniHelper::getStaticMethodInfo(showBanner,AppActivityCalssName,"showBannerAd","()V")) { showBanner.env->CallStaticVoidMethod(showBanner.classID,showBanner.methodID); } else{ log("jni:showBannerStatic false"); } } //隐藏广告条 void DomobAd::hideBannerAd() { cocos2d::JniMethodInfo hideBanner; if (cocos2d::JniHelper::getStaticMethodInfo(hideBanner,"hideBannerAd","()V")) { hideBanner.env->CallStaticVoidMethod(hideBanner.classID,hideBanner.methodID); } else{ log("jni:hideBannerStatic false"); } } //显示插屏广告 void DomobAd::showInterstitialAd() { cocos2d::JniMethodInfo showInterstitial; if(cocos2d::JniHelper::getStaticMethodInfo(showInterstitial,"showInterstitialAd","()V")){ showInterstitial.env->CallStaticVoidMethod(showInterstitial.classID,showInterstitial.methodID); showInterstitial.env->DeleteLocalRef(showInterstitial.classID); } else{ log("jni:showBannerStatic false"); } } #else //广告条 void DomobAd::showBannerAd() { log("showBannerAd() called"); return; } void DomobAd::hideBannerAd() { log("hideBannerAd() called"); return; } //插屏广告 void DomobAd::showInterstitialAd(){ log("showInterstitialAd() called"); return; } #endif
6) 接下来就可以愉快的在Cocos2d-x场景里添加广告了。这里我们就在HelloWorld场景的上端添加一个广告条,并在场景的中间设置一个按钮,一按就弹出一个插屏广告。完整代码如下:
HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" class HelloWorld : public cocos2d::Layer { public: static cocos2d::Scene* createScene(); virtual bool init(); // a selector callback void menuCloseCallback(cocos2d::Ref* pSender); void adCallback(cocos2d::Ref* pRef); // implement the "static create()" method manually CREATE_FUNC(HelloWorld); }; #endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h" #include "DomobAd.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)); //添加一个按钮用来弹出插屏广告 auto adItem = MenuItemImage::create( "CloseNormal.png",CC_CALLBACK_1(HelloWorld::adCallback,this)); adItem->setPosition(Vec2(origin.x + visibleSize.width/2,origin.y + visibleSize.height/2)); // create menu,it's an autorelease object auto menu = Menu::create(closeItem,adItem,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 //添加广告条 DomobAd::showBannerAd(); auto label = Label::createWithTTF("Hello World","fonts/Marker Felt.ttf",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); return true; } void HelloWorld::menuCloseCallback(Ref* pSender) { Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif } void HelloWorld::adCallback(cocos2d::Ref* pRef){ DomobAd::showInterstitialAd(); }
效果如下图所示
从效果图里可以看出我已经在AndroidManifest.xml里把横屏改成了竖屏。
人生感悟:1.多跟人交流;2,多尝试;3,打好基础。
水平有限,如有不妥,欢迎指正!
参考文献:
[1]多盟官方UserGuide.pdf
[2]http://blog.csdn.net/aa294194253/article/details/38514125
[3]http://blog.csdn.net/u011909633/article/details/47038859
原文链接:https://www.f2er.com/cocos2dx/341153.html