Bài này mình sẽ hướng dẫn cách tích hợp AdMob Banner vào Cocos Creator. Sau khi build bằng Cocos Creator, mở dự án proj.android-studio bằng Android Studio rồi thực hiện các thay dổi sau:
1. proj.android-studio/build.gradle
buildscript {
repositories {
google()
jcenter()
// Google AdMob
mavenCentral()
}
...
allprojects {
repositories {
google()
// Google AdMob
mavenCentral()
...
2. proj.android-studio/gradle.properties
PROP_MIN_SDK_VERSION=19
...
android.useAndroidX=true
org.gradle.daemon=true
org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx4g -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
3. proj.android-studio/app/AndroidManifest.xml
<application
...
<!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713"/>
4. proj.android-studio/app/build.gradle
dependencies {
...
// adMob
implementation 'com.google.android.gms:play-services-ads:21.3.0'
5. proj.android-studio\app\src\org\cocos2dx\javascript\AppActivity.java
...
// Admob
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.AdSize;
import android.widget.RelativeLayout;
public class AppActivity extends Cocos2dxActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Admob
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
AdView adView = new AdView(this);
RelativeLayout relativeLayout = new RelativeLayout(this);
mFrameLayout.addView(relativeLayout);
RelativeLayout.LayoutParams adViewParams = new RelativeLayout.LayoutParams(
AdView.LayoutParams.WRAP_CONTENT,
AdView.LayoutParams.WRAP_CONTENT);
adViewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
relativeLayout.addView(adView, adViewParams);
adView.setAdSize(AdSize.BANNER);
// Test adunit
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);