AdMob Integration in Cocos2d-x

  • Tutorial
Dear hawkers, in this article I want to share my experience in integrating the AdMob banner network into an Android game written using the Cocos2d-x engine.


Introduction

The interest in mobile development in recent years has been high and many independent developers and companies seek to develop a part of this market. This creates high competition and even a good application can get lost in the market. It may take a long time before your application reaches high positions in the ranking. And time is money. It is important to get a good position in the ranking, as this leads to further downloads. This makes positioning the application as free a good strategy. However, application development is a costly task, especially if you are a company or use part of the work through outsourcing. But even if the entire development was completed by one participant, it was hardly in the developer's plans to simply leave his mark on the application store. I want to get at least some kind of material return. Thus, we come to two application monetization strategies. The Freemium model is a free application plus additional functionality for a fee, through purchases inside the application. Or monetization due to the advertising built into the application. In this article we will consider the introduction of advertising in the application.


Theory and preparation of tools

So let's say that you already have an application or game for android written using Cocos2d-x 2.0.4. Not? Well then, let's take the examples that come with the Cocos2d-x SDK as a basis. SDK not yet installed? Then we go to the github section , where the source code of the framework is stored (at the time of writing, the official website of the cocos2d-x.org project was unavailable). The AdMob SDK can be found at admob.com .

The code in the project using the framework is written in C ++. However, the AdMob SDK is a Java library. How to use this library in our project? In fact, everything is much simpler than it might seem at first glance. And all this thanks to the capabilities of the Android SDK. The fact is that the View object in which the graphics implemented in C ++ is displayed is also a Java object, and here we are free to build the configuration of the various View we need.

The first thing that comes to mind is the stack from the View, let's say a banner on top and a game window below. This can be done using the LinearLayout object in which to place the AdView object and Cocos2dxGLSurfaceView. All this will work, the only problem will arise at the moment when you want the ability to remove the banner, for example, after paying for the purchase inside the application. The problem is that the OpenGL view in Cocos2d-x does not support resizing the viewport.
Another solution is to use RelativeLayout and display the banner on top of the OpenGL view of the game. In this case, the display area of ​​the game will occupy all available space on the screen and will not change, and the area with the banner will be superimposed on top. Cast aside fears, this will not cause image distortion or flicker.

If you are familiar with Android development, then you know that usually the parameters of the display area are described in a special XML file. In programs on Cocos2d-x 1.0 it was. However, in the latest version of Cocos2d-x, you will not find this file. For a reason unknown to me, the description of the display areas has been transferred to Java code. This does not cause any difficulties, you just need to know where these files are located (cocos2dx-2.0.4 / cocos2dx / platform / android / java / src / org / cocos2dx / lib). The code is slightly larger, but we are able to dynamically create the necessary display configuration. Unfortunately, without modifying the library files, it will not be possible to connect the viewport we need - the members of the class we need are declared private. In my project, I made a radical decision - to completely copy this code into my project, instead of referring to framework files. Since now all the code was now in the repository of my project, this freed my hands and I spent all the necessary code modifications directly in the Cocos2dxActivity class.

Integration

So let's get started. First, copy the folder of the test project, for example, HelloCpp to HelloAdMob in the same folder. Next, copy the AdMob SDK HelloAdMob / proj.android / AdMob files. Now create the HelloAdMob / proj.android / cocos_java folder and copy the files from cocos2dx-2.0.4 / cocos2dx / platform / android / java / src into it, including subdirectories.
Next, open the project in Eclipse, or in another environment of your choice (notepad? ;-). Project properties should look like the screenshots below.

You will need to add the cocos_java folder to the project, as well as the AdMob library. and mark the AdMob library for export.








You also need to change the version of the Android SDK, since AdMob requires a version not lower than 3.2. Don’t worry, version 2.2 support will remain. We modify the project.properties file by setting the appropriate version
# Project target.
target=android-13

Next, open the AndroidManifest.xml file as text, fix the line of the target SDK

the minimum version is left old. We’ll add the necessary permissions below so that AdMob can download the banner from the network.

You also need to declare AdMob in the manifest file. I did this after declaring the game's activity class.

Now we modify the Cocos2dxActivity.java file - add the AdMob import sinks:
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

add a field for the ad unit to the class
private AdView adView;

now, after the lines
// ...add to FrameLayout
framelayout.addView(edittext);

insert the following code:
// создаем область отображения баннера
adView = new AdView(this, AdSize.BANNER, "ваш_id");
// задаем параметры отображения, здесь я использовал вертикальное смещение, так как в примере cocos2d-x использован режим отображения без полей
ViewGroup.LayoutParams ad_layout_params = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, 50);
adView.setLayoutParams(ad_layout_params);
// Создаем запрос баннера
AdRequest adRequest = new AdRequest();
// Устанавливаем свойства
adRequest.addTestDevice("id_тестового_устройства");
// Запускаем загрузку баннера в фоне
adView.loadAd(adRequest);

You’ll get the publisher ID after registering on admob.com and adding information about your program. The device ID will be displayed in the logcat console, it must be copied and pasted into the code, because due to accidental clicks on your own banner you can be banned (sorry for the pun) in the admob system, and if you used a Google account to log in, it may be this account is also blocked, with all the ensuing consequences.
Next, add the created viewport to the class hierarchy. You must do this after adding the OpenGL area, otherwise your banner will be blocked by it. After the line
gLSurfaceView.setCocos2dxEditText(edittext);

add our code:
// Добавляем AdView в иерархию областей отображения. Область не будет иметь размера, пока реклама не загружена
framelayout.addView(adView);


Everything, you can start assembling. Do not forget to build the native library using the Android NDK, after which you can build the project in Eclipse (or in your favorite environment) and enjoy the result.


Also popular now: