How to integrate "Admob" with Cocos2d-x V3.0rc0&beta2 Android Project

Note from Ryeeeeee:Because Cocos2d-x V3.0 use android.app.NativeActivity instead of android.app.Activity, there is an issue that Admob don’t work in your pure native activity application. This post will walk you through process of fixing the issue.
P.S. Sorry for my english, it is not my native language, unfortunately.

Create App in Admob

First, you need to create a free Admob account to get started. And you have to provide the following information to finish create an Admob account.

After that, you can add your first app,such as.

Using Google Play Services SDK

Because Google Play will stop accepting new or updated apps that use the old standalone Google Mobile Ads SDK v6.4.1 or lower on August 1, 2014, we select Android(Google Play Services). This is the recommended way of enabling ads on your Android app.

Set Up Google Play Services SDK

To develop an app using the Google Play services APIs, you must download the Google Play services SDK from the SDK Manager.

  • Launch the SDK Manager:
    in Eclipse(with ADT), select Window -> Android SDK Manager
  • Install the Google Play services SDK:
    Scroll to the bottom of the package list, expand Extras, select Google Play services, and install it. it is saved in your Android SDK environment at $ANDROID_SDK/extras/google/google_play_services/.
  • Make a copy of the Google Play services library project:
    Copy the library project at $ANDROID_SDK/extras/google/google_play_services/libproject/google-play-services_lib/ to the location where you maintain your Android app projects.

Incorporating the SDK

Add and reference the Google Play services library project. Right click on your project in Eclipse and select Properties.

Select Android and then click Add… Find the google-play-services_lib project and select OK to add the Google Play services library.

The project now references the Google Play services library.

Open the AndroidManifest.xml and add the following tag as a child of the <application> element.

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

Add the following tag as a child of the <manifest> element.

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

Because Cocos2d-x V3.0 use android.app.NativeActivity instead of android.app.Activity, there is an issue that Admob don’t work in your pure native activity application. The following is the solution.

Now, open the Cocos2dxActivity.java and modify it in such a way:

package org.cocos2dx.cpp;

import android.app.NativeActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

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

public class Cocos2dxActivity extends NativeActivity {
	private AdView adView;
	private PopupWindow popUp;
	private static Cocos2dxActivity _activity;
	private LinearLayout layout;
	private LinearLayout mainLayout;
	boolean adsinited = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Make your custom init here
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		_activity = this;
		// Create our ad view here
		adView = new AdView(this);
                // you can get the ID from Admob
		adView.setAdUnitId("a1531054c66348c");
		adView.setAdSize(AdSize.BANNER);

	}

	public static void showAdPopup(){
		_activity._showAdPopup();
	}
	
	public void _showAdPopup() {
		if (adsinited) {
			return;
		}
		if (adView != null) {
			_activity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					adsinited = true;
					// Out popup window
					popUp = new PopupWindow(_activity);

					// This is the minimum size for AdMob, we need to set this
					// in case our target device run at 320x480 resolution
					// (Otherwise no ad will be shown, see the padding kill
					// below)

					popUp.setWidth(320);
					popUp.setHeight(50);
					popUp.setWindowLayoutMode(LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					popUp.setClippingEnabled(false);

					layout = new LinearLayout(_activity);
					mainLayout = new LinearLayout(_activity);

					// The layout system for the PopupWindow will kill some
					// pixels due to margins/paddings etc… (No way to remove
					// it), so padd it to adjust
					layout.setPadding(-5, -5, -5, -5);

					MarginLayoutParams params = new MarginLayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);

					params.setMargins(0, 0, 0, 0);
					layout.setOrientation(LinearLayout.VERTICAL);
					layout.addView(adView, params);
					popUp.setContentView(layout);
					_activity.setContentView(mainLayout, params);
                                        // you can get the TestDevice ID from the output of logcat .
					AdRequest adRequest = new AdRequest.Builder()
							.addTestDevice(
									"CE7DCE5945F79BBF863872D5026787EFbuild")
							.build();
					// Enable this if your are testing AdMob, otherwise you'll
					// risk to be banned!
					_activity.adView.loadAd(adRequest);
					// Show our popup window
					popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 0, 0);
					popUp.update();
					
				}
			});
		}
	}

	private class AdmobListener extends AdListener {
		@Override
		public void onAdClosed() {
			super.onAdClosed();
		}

		@Override
		public void onAdFailedToLoad(int errorCode) {
			super.onAdFailedToLoad(errorCode);
		}

		@Override
		public void onAdLeftApplication() {
			super.onAdLeftApplication();
		}

		@Override
		public void onAdLoaded() {
			super.onAdLoaded();

		}

		@Override
		public void onAdOpened() {
			super.onAdOpened();
		}
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}
}

IMPORTANT : This is the clue. It is time to call our ads show. Before we proceed keep in mind this: Never call this function in an onCreate callback. You have to call this code after your whole native window is created. Personally I call it when my game (native, C) window is ready to be shown.

Create AdmobHelper.h and add the following code in it.

#ifndef  __Admob_Helper_H_
#define  __Admob_Helper_H_

class AdmobHelper
{
public:
    static void showAds();
    //if necessary, you can add other methods to control AdView(e.g. dismiss the AdView).
};
#endif  //__INTERFACE_FACEBOOK_H_

Create AdmobHelper.cpp and add the following code in it.

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "AdmobHelper.h"
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <android/log.h>

const char* NativeActivityClassName = "org/cocos2dx/cpp/Cocos2dxActivity";

void AdmobHelper::showAds(){
	cocos2d::JniMethodInfo t;
	if (cocos2d::JniHelper::getStaticMethodInfo(t
                                                , NativeActivityClassName
                                                , "showAdPopup"
                                                , "()V"))
	{
		t.env->CallStaticVoidMethod(t.classID, t.methodID);
		t.env->DeleteLocalRef(t.classID);
	}
}

#endif

Finally,you just need to include AdmobHelper.h and call AdmobHelper::showAds() in C++ side.Then you can see the Ad.

Source Code

You can download the source code of the demo from:https://github.com/Ryeeeeee/AdmobDemoV3
And replace the corresponding files in your project.

References

http://www.dynadream.com/ddweb/index.php/Special_Blog?id=20


bold_fields_required.png (60.7 KB)


bold_fields_required.png (23.8 KB)


add_first_app.png (46.0 KB)


play-add-library.png (99.6 KB)


play-confirm.png (102.5 KB)


play-edit-properties.png (75.7 KB)


play-add-library.png (99.6 KB)


play-confirm.png (102.5 KB)


play-edit-properties.png (75.7 KB)


ad.png (70.2 KB)

4 Likes

thanks you for your post, i am about to integrate it to my game, but not time to research :wink: , your post’s really helpful for me :smiley:

Thank Ryeeeeee very much for your help. It’s really helpful. I spent much time to google, but I’ve not done. Could u show me how can I call AdmobHelper::showAds() in LUA side
Thank you again, nice man, cool man

I put AdmobHelper::showAds() in AppDelegate.cpp

bool AppDelegate::applicationDidFinishLaunching()
{
    ....
    
    engine->executeString("require 'hello.lua'");
    AdmobHelper::showAds(); 
    return true;
}

When I run on the real device, it gives me an error “Unfortunately,… has stopped”
Help me plz, thanks

I completely put AdmobHelper::showAds() in AppDelegate.cpp file. But I need to put in LUA file to call it some times
Could u plx help me
Thanks

@NC1988 You are welcome.

@vnju Hello, did you try putting AdmobHelper::showAds() in HelloWorldScene.cpp ?

Dear Ryeeeeee
what’s HelloWorldScene.cpp file? I put AdmobHelper::showAds() in AppDelegate.cpp file and it’s OK now. But the Ads is shown all the time that game’s running. I just need call it when the game over, for example. So I thinks I must to put it on the LUA file (As I’m using COCOs2dx 3.0 with LUA), but I don’t know how can I do.
Could u help me?
thank you

@vnju I get it, Maybe you have to bind C++ Class/Member function to Lua manually. You can refer to https://github.com/cocos2d/cocos-docs/blob/master/manual/framework/native/scripting/lua/lua-class-function-manually/zh.md , but you need to translate it first.

Thanks Ryeeeee, I’ll try or just let ads auto refresh :slight_smile:

Hi all
I’ve done the first Cocos2dx Game named Flap star Bird (similar with flappy bird:) here http://www.cocos2d-x.org/forums/21/topics/46948
Thanks Ryeeeee for helping me to put ads :slight_smile:
the only thing I missed is to put rate link on Game, i’’ research and put later

thanks…would this work with 2.2.2 also :slight_smile:

Hi all
Why ads is not shown up on android 4.4 device like Note 3?
Is it from targetAPI? I used API=17
Thanks

Hi all
Why ads is not shown up on android 4.4 device like Note 3?
Is it from targetAPI? I used API=17
Thanks

Great code, it even works for version 2.2.2 but I get a black screen when the add shows :;qst

I know that this is for the 3.0 version, but maybe somebody has a tip what could be wrong?

Thanks

@Matuda wrote:

Great code, it even works for version 2.2.2 but I get a black screen when the add shows :;qst

I know that this is for the 3.0 version, but maybe somebody has a tip what could be wrong?

Thanks

I also wish to ask,the admob is show,but become black screen.

I don’t know why ads is not shown up on some devices using android 4.4 as note 3, samsung s4
who help me
thanks alot

i donr get it… do i modify the cocos2dxactivity.java in the cocos2d-xsrc??or create a new one and put in the src/org folder???..

just saw your adhelper class… answered my quesiton…

Did you all know there is an AdMob plugin for cocos2dx v3?