为什么要接谷歌广告?简述几个点:游戏版号暂停、轻游戏回暖、游戏出海、google play、广告收益。
网上关于cocos creator接入AdMob的教程,多是不能用,或已经过时,或不详细,容易给初学者带来勿扰。
所以特写此文,给大家分享一下完整的Android游戏应用如何接入AdMob,以及过程中踩到的坑。
参考文档
Google AdMob官方文档:/admob/android/quick-start;Cocos Creator官方文档:/creator/manual/zh/;
完成目标
Android手游成功接入AdMob,并上架google play store获取广告收益;实现在指定场景(如游戏首页或者通关页面)展示横幅广告;实现在指定场景(如使用道具)展示激励视频广告;实现检测激励视频广告是否播放完成,根据是否获得广告收益判断是否给予玩家道具等奖励;
如果有官方文档就可以让所有开发者搞定一切功能,还要教程干什么。话不多说,进入正题!
cocos creator将游戏打包成android项目
这个cocos creator官方有详细教程文档,不重复。
链接:/creator/manual/zh/publish/publish-native.html
项目级build.gradle改动:
添加maven {url “”}allprojects {repositories {google()jcenter()flatDir {dirs 'libs'}maven {url ""}}}
应用级build.gradle改动:
添加implementation ‘com.google.android.gms:play-services-ads:17.1.1’dependencies {implementation fileTree(dir: 'libs', include: ['*.jar','*.aar'])implementation fileTree(dir: "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/android/java/libs", include: ['*.jar'])implementation project(':libcocos2dx')implementation 'com.google.android.gms:play-services-ads:17.1.1'}
AndroidManifest.xml改动:
将你的ADMOB_APP_ID添加到AndroidManifest.xml文件中<manifest><application><meta-dataandroid:name="com.google.android.gms.ads.APPLICATION_ID"android:value="ca-app-pub-3940256099942544~3347511713"/></application></manifest>
初始化 MobileAds
AppActivity.java请参考我的改动package org.cocos2dx.javascript;import org.cocos2dx.lib.Cocos2dxActivity;import org.cocos2dx.lib.Cocos2dxGLSurfaceView;import android.os.Bundle;import android.content.Intent;import android.content.res.Configuration;public class AppActivity extends Cocos2dxActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// Workaround in /questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508if (!isTaskRoot()) {return;}// DO OTHER INITIALIZATION BELOWSDKWrapper.getInstance().init(this);//初始化广告管理AdManage.getInstance().init(this);}@Overridepublic Cocos2dxGLSurfaceView onCreateView() {Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);// TestCpp should create stencil bufferglSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView, this);return glSurfaceView;}@Overrideprotected void onResume() {super.onResume();SDKWrapper.getInstance().onResume();AdManage.getInstance().onResume();}@Overrideprotected void onPause() {super.onPause();SDKWrapper.getInstance().onPause();AdManage.getInstance().onPause();}@Overrideprotected void onDestroy() {super.onDestroy();SDKWrapper.getInstance().onDestroy();AdManage.getInstance().onDestroy();}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data);}@Overrideprotected void onNewIntent(Intent intent) {super.onNewIntent(intent);SDKWrapper.getInstance().onNewIntent(intent);}@Overrideprotected void onRestart() {super.onRestart();SDKWrapper.getInstance().onRestart();}@Overrideprotected void onStop() {super.onStop();SDKWrapper.getInstance().onStop();}@Overridepublic void onBackPressed() {SDKWrapper.getInstance().onBackPressed();super.onBackPressed();}@Overridepublic void onConfigurationChanged(Configuration newConfig) {SDKWrapper.getInstance().onConfigurationChanged(newConfig);super.onConfigurationChanged(newConfig);}@Overrideprotected void onRestoreInstanceState(Bundle savedInstanceState) {SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState);super.onRestoreInstanceState(savedInstanceState);}@Overrideprotected void onSaveInstanceState(Bundle outState) {SDKWrapper.getInstance().onSaveInstanceState(outState);super.onSaveInstanceState(outState);}@Overrideprotected void onStart() {SDKWrapper.getInstance().onStart();super.onStart();}}
接下来是教程重点,本人封装的谷歌广告管理类AdManage.java:
package org.cocos2dx.javascript;import android.content.Context;import android.view.Gravity;import android.view.View;import android.widget.FrameLayout;import android.widget.LinearLayout;import android.widget.Toast;import com.google.android.gms.ads.AdRequest;import com.google.android.gms.ads.AdSize;import com.google.android.gms.ads.AdView;import com.google.android.gms.ads.MobileAds;import com.google.android.gms.ads.reward.RewardItem;import com.google.android.gms.ads.reward.RewardedVideoAd;import com.google.android.gms.ads.reward.RewardedVideoAdListener;public class AdManage implements RewardedVideoAdListener {private static final String AD_BANNER_UNIT_ID = "ca-app-pub-3940256099942544/6300978111";//横幅广告IDprivate static final String AD_VIDEO_ID = "ca-app-pub-3940256099942544/5224354917";//激励视频广告IDprivate static final String APP_ID = "ca-app-pub-3940256099942544~3347511713";//应用IDprivate Context mainActive = null;private static AdManage mInstace = null;private AdView mAdView;private LinearLayout bannerLayout;private RewardedVideoAd rewardedVideoAd;private static boolean isVideoRewarded = false;private static boolean isVideoClose = false;public static AdManage getInstance() {if (null == mInstace) {mInstace = new AdManage();}return mInstace;}public void init(Context context) {this.mainActive = context;//初始化广告 SDK.MobileAds.initialize(context, APP_ID);//预加载激励视频广告rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(context);rewardedVideoAd.setRewardedVideoAdListener(this);loadRewardedVideoAd();//预加载banner广告loadBannerAd();}/*加载google banner广告*/public void loadBannerAd() {bannerLayout = new LinearLayout(this.mainActive);bannerLayout.setOrientation(LinearLayout.VERTICAL);// Create a banner ad. The ad size and ad unit ID must be set before calling loadAd.mAdView = new AdView(this.mainActive);mAdView.setAdSize(AdSize.SMART_BANNER);mAdView.setAdUnitId(AD_BANNER_UNIT_ID);// Create an ad request.AdRequest.Builder adRequestBuilder = new AdRequest.Builder();// Optionally populate the ad request builder.adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);// Add the AdView to the view hierarchy.bannerLayout.addView(mAdView);// Start loading the ad.mAdView.loadAd(adRequestBuilder.build());AppActivity activity = (AppActivity)this.mainActive;FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);params.gravity=Gravity.BOTTOM;activity.addContentView(bannerLayout,params);bannerLayout.setVisibility(View.INVISIBLE);}/*显示google banner广告*/public static void showBannerAd(){AppActivity mActivity = (AppActivity)AdManage.getInstance().mainActive;//一定要确保在UI线程操作mActivity.runOnUiThread(new Runnable() {@Overridepublic void run() {AdManage.getInstance().bannerLayout.setVisibility(View.VISIBLE);}});}/*隐藏google banner广告*/public static void hideBannerAd(){AppActivity mActivity = (AppActivity)AdManage.getInstance().mainActive;//一定要确保在UI线程操作mActivity.runOnUiThread(new Runnable() {@Overridepublic void run() {AdManage.getInstance().bannerLayout.setVisibility(View.INVISIBLE);}});}/*预加载google视频广告*/public void loadRewardedVideoAd() {if (!rewardedVideoAd.isLoaded()) {rewardedVideoAd.loadAd(AD_VIDEO_ID, new AdRequest.Builder().build());}}/*显示视频广告*/public static void showRewardedVideo() {AdManage.getInstance().isVideoRewarded = false;AdManage.getInstance().isVideoClose = false;AppActivity mActivity = (AppActivity)AdManage.getInstance().mainActive;//一定要确保在UI线程操作mActivity.runOnUiThread(new Runnable() {@Overridepublic void run() {if (AdManage.getInstance().rewardedVideoAd.isLoaded()) {AdManage.getInstance().rewardedVideoAd.show();}}});}@Overridepublic void onRewardedVideoAdLeftApplication() {Toast.makeText(this.mainActive, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();}@Overridepublic void onRewardedVideoAdClosed() {AdManage.getInstance().isVideoClose = true;//预加载下一个视频广告loadRewardedVideoAd();}@Overridepublic void onRewardedVideoAdFailedToLoad(int errorCode) {}@Overridepublic void onRewardedVideoAdLoaded() {}@Overridepublic void onRewardedVideoAdOpened() {}@Overridepublic void onRewarded(RewardItem reward) {AdManage.getInstance().isVideoRewarded = true;}@Overridepublic void onRewardedVideoStarted() {}@Overridepublic void onRewardedVideoCompleted() {}//用于cocos监听视频广告播放完成public static boolean videoRewardedListener(){return AdManage.getInstance().isVideoRewarded;}//用于cocos监听视频广告播放关闭public static boolean videoCloseListener(){return AdManage.getInstance().isVideoClose;}public void onResume() {mAdView.resume();rewardedVideoAd.resume(this.mainActive);}public void onPause() {mAdView.pause();rewardedVideoAd.pause(this.mainActive);}public void onDestroy() {mAdView.destroy();rewardedVideoAd.destroy(this.mainActive);}}
js和java交互
因为前面写的视频广告播放与关闭等方法,是在java中写的,然而我们用Cocos Creator开发游戏的时候,写的都是js,那么问题来了,如果我们在开发的时候,点击某个button,需要它调用广告管理类AdManage.java中的视频播放方法showRewardedVideo,怎么办?一行代码搞定:jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showRewardedVideo", "()V");
注意事项:
简单提两点
文中为了给大家测试方便,用的广告ID和应用ID全是google提供的测试ID,上线前记得改为自己的ID配置,切记!!!如果想要使用Android Studio运行Cocos Creator打包编译好的项目文件,尽量不要移动原来目录,否则容易出现各种运行报错。
如果觉得《Cocos Creator接入谷歌广告AdMob详细教程(原创)》对你有帮助,请点赞、收藏,并留下你的观点哦!