1.cocos版本需要在2.4.13
2.配置gardle plugin 7.4.2 gradle version 7.5.1
3.gradle setting jdk 17
4.ndk 23.1.7779620
5.manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-2912341234436825~6257054724"/>
<meta-data
android:name="com.google.android.gms.ads.AD_MANAGER_APP"
android:value="true"/>
6.appactivity
oncreate(){
AdManage.getInstance().init(this);
}
onCreateView(){
new AppBannerManager(this);
}
7.module gradle app
android{
defaultconfig{
....
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
dependencies{
implementation 'io.github.beesads:sdk:1.1.3'
implementation 'io.github.beesads:adapter-admob:1.0.5'
implementation 'com.google.android.gms:play-services-ads:23.2.0'
implementation 'com.google.android.gms:play-services-ads-identifier:18.0.1'
implementation 'com.google.android.gms:play-services-appset:16.0.2'
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.lifecycle:lifecycle-runtime:2.2.0"
implementation 'androidx.lifecycle:lifecycle-process:2.2.0'
// appmetrica
implementation "io.appmetrica.analytics:analytics:7.0.0"
// yandex
implementation 'com.yandex.ads.adapter:admob-mobileads:7.2.0.0'
implementation 'com.yandex.android:mobileads:7.2.0'
implementation 'com.yandex.ads.mediation:mobileads-google:23.0.0.2'
}
8.proguard-rules.pro 的app最后面加入
-keep public class com.google.** { *; }
-keep class com.adjust.sdk.** { *; }
-keep class com.google.android.gms.ads.** { *; }
-keep interface com.google.android.gms.ads.** { *; }
-keep class com.google.android.gms.common.ConnectionResult {
int SUCCESS;
}
-keep class com.google.android.gms.ads.identifier.AdvertisingIdClient {
com.google.android.gms.ads.identifier.AdvertisingIdClient$Info getAdvertisingIdInfo(android.content.Context);
}
-keep class com.google.android.gms.ads.identifier.AdvertisingIdClient$Info {
java.lang.String getId();
boolean isLimitAdTrackingEnabled();
}
-keep public class com.android.installreferrer.** { *; }
-keep class com.facebook.login.** {*;}
1,cocos creator调用的脚本块
const { ccclass, property } = cc._decorator;
@ccclass
export default class PlatformApi {
private static _instance: PlatformApi | null = null;
public static get Instance() {
if (!PlatformApi._instance) {
// window["PlatformApi"] = new PlatformApi();
PlatformApi._instance = new PlatformApi()
window["PlatformApi"] = PlatformApi._instance;
}
// return PlatformApi._instance || (PlatformApi._instance = new PlatformApi());
return PlatformApi._instance;
}
// 是否预加载激励广告
public isLoadRewardAd: boolean = false;
// 申请激励广告时间
public showRewardVideoADTime: number = 0;
public vibrateNum: number = 0;
// 震动时间
public VibrateTime: number = 0;
// 是否ios平台
public isPlatformIos() {
let bIos = false;
if (cc.sys.os == cc.sys.OS_IOS) {
bIos = true;
}
return bIos;
}
/**
*
* @param dir bottom-lefte 左下 top 顶部居中 bottom 底部居中 top-lefte
*/
public showBanner(dir?: string) {
dir = dir || "bottom"
cc.log("广告 showBanner");
//eg
//jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showBannerAd", "(Ljava/lang/String;)V", "bottom-left");
jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showBannerAd", "(Ljava/lang/String;)V", dir);
}
/**隐藏banner */
public hideBanner() {
cc.log("广告 hideBanner");
jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "hideBannerAd", "()V");
}
timeCount=35;
//这个计时得在其他常驻节点上调用
public UpdateInterstitialAd(dt: number)
{
PlatformApi.Instance.timeCount += dt;
//cc.log("timeCount "+PlatformApi.Instance.timeCount);
}
public showOpenAd() {
jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showOpenAd", "()V");
}
//展示插屏广告
public showInterstitialAd() {
cc.log("广告 插屏广告");
//35秒内触发一次,不需要的话可以注释掉
if (this.timeCount<35) {
cc.log("广告 "+this.timeCount+" 短时间内重复触发");
return;
}
this.timeCount = 0
// cc.game.off("_close_interstital_AD_")
// cc.game.once("_close_interstital_AD_", ()=>{
// callback && callback.call(target)
// })
jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showInterstitialAd", "()V");
}
//展示激励广告
public showRewardVideoAD(callback,target?) {
// =================================
let newTime = new Date().getTime();
if ((newTime - PlatformApi.Instance.showRewardVideoADTime) < 5000) {
cc.game.emit("_no_5_seconds_");
// console.log("5秒内不能重复请求");
return;
}
PlatformApi.Instance.showRewardVideoADTime = newTime;
// =================================
console.log("广告 激励广告");
cc.game.off("_get_video_reward_")
cc.game.once("_get_video_reward_", ()=>{
callback && callback.call(target)
})
jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showRewardVideoAd", "()V");
}
// 回调=================================================================================
// 安卓广告播放成功回调
// 安卓广告播放成功回调
public getVideoReward() {
console.log("ADManage getVideoReward");
cc.game.emit("_get_video_reward_");
}
// 广告回调失败是因为缺少库存,显示本地广告
public showRewardVideoADFailByAndroid() {
console.log("ADManage showRewardVideoADFailByAndroid");
cc.game.emit("_show_reward_video_AD_fail_");
}
// 插屏广告关闭
public getInterstitalHidden() {
console.log("ADManage getInterstitalHidden");
// cc.game.emit("_close_interstital_AD_");
// PlatformApi.Instance.timeCount=0;
}
//视频广告关闭
public getVideoHidden() {
console.log("ADManage getVideoHidden");
PlatformApi.Instance.timeCount=0;
}
}
在android studio中的android 里app文件夹的org.cocos2dx.javascript添加脚本
1.GlobalApplication.java
package org.cocos2dx.javascript;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;
import com.google.android.gms.ads.MobileAds;
import org.cocos2dx.javascript.admob.AppBannerManager;
import org.cocos2dx.javascript.admob.AppInterstitialAdManager;
import org.cocos2dx.javascript.admob.AppOpenAdManager;
import org.cocos2dx.javascript.admob.AppRewardAdManager;
import java.util.Date;
import io.appmetrica.analytics.AppMetrica;
import io.appmetrica.analytics.AppMetricaConfig;
public class GlobalApplication extends Application
implements Application.ActivityLifecycleCallbacks, LifecycleObserver {
private AppOpenAdManager appOpenAdManager;
private Activity currentActivity;
// @Override
// protected void attachBaseContext(Context base) {
// super.attachBaseContext(base);
// MultiDex.install(this);
// }
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
// Then activate AppMetrica SDK
AppMetricaConfig appMetricaConfig = AppMetricaConfig.newConfigBuilder("0fb95331-bbef-49a8-b6da-53cf9c9d647e").build();
AppMetrica.activate(this, appMetricaConfig);
// admob
// new Thread(
// () -> {
// })
// .start();
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this, initializationStatus -> {
// 开屏
AppOpenAdManager.startTime = (new Date()).getTime();
appOpenAdManager = new AppOpenAdManager(this);
});
}
/** ActivityLifecycleCallback methods. */
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//
// // 插屏
AppInterstitialAdManager.getInstance().loadAd(activity);
// // 插屏
AppRewardAdManager.getInstance().load(activity);
}
@Override
public void onActivityStarted(Activity activity) {
// Updating the currentActivity only when an ad is not showing.
if (appOpenAdManager == null){
return;
}
if (!appOpenAdManager.isShowingAd) {
currentActivity = activity;
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
@Override
public void onActivityDestroyed(Activity activity) {}
/** Interface definition for a callback to be invoked when an app open ad is complete. */
public interface OnShowAdCompleteListener {
void onShowAdComplete();
}
/** LifecycleObserver method that shows the app open ad when the app moves to foreground. */
@OnLifecycleEvent(Lifecycle.Event.ON_START)
protected void onMoveToForeground() {
if (appOpenAdManager == null){
return;
}
// Show the ad (if available) when the app moves to foreground.
appOpenAdManager.showAdIfAvailable(currentActivity,
new OnShowAdCompleteListener() {
@Override
public void onShowAdComplete() {
// Empty because the user will go back to the activity that shows the ad.
}
});
}
}
2.AdManage.java
package org.cocos2dx.javascript;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.LinearLayout;
//import com.applovin.mediation.ads.MaxAdView;
//import org.cocos2dx.javascript.ads.AdsOpen;
//import org.cocos2dx.javascript.ads.MyAdsBanner;
//import org.cocos2dx.javascript.ads.MyAdsInterstitial;
//import org.cocos2dx.javascript.ads.MyAdsReward;
import org.cocos2dx.javascript.admob.AppInterstitialAdManager;
import org.cocos2dx.javascript.admob.AppRewardAdManager;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
//import com.google.android.gms.ads.MobileAds;
//import com.google.android.gms.ads.RequestConfiguration;
//import static com.google.android.gms.ads.RequestConfiguration.MAX_AD_CONTENT_RATING_G;
//import static com.google.android.gms.ads.RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_TRUE;
public class AdManage {
private static final String AD_BANNER_UNIT_ID = "a31d888ffeceac47";//横幅广告ID
private static final String AD_UNIT_ID = "18809e94fe00d416"; //插页广告
private static final String AD_VIDEO_ID = "d7332bd29973e1f3";//激励视频广告ID
public static final String AD_OPEN_ID = "40e08fd08473b7e8";//开屏视频广告ID
private AppActivity mainActive = null;
private static AdManage mInstace = null;
// private MaxAdView adView;
private LinearLayout bannerLayout;
private String adPos;
public final String TAG = "ADManage";
private int screenWidth;
// private MyAdsBanner admobBanner = new MyAdsBanner();
// private MyAdsInterstitial admobInterstitial = new MyAdsInterstitial();
// private MyAdsReward admobRewarded = new MyAdsReward();
// private AdsOpen admobOpenManager;
//-----------类型常量-------------
private static String BANNER_TYPE = "0";
private static String INTERSTITIAL_TYPE = "1";
private static String NATIVE_TYPE = "2";
private static String SPLASH_TYPE = "5";
private static String REWARDED_TYPE = "8";
//----------------------
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(Activity activity) {
this.mainActive = (AppActivity) activity;
// admobInterstitial.createInterstitialAd(activity);
// admobRewarded.createRewardedAd(activity);
}
public void initBanner(Context context) {
// admobBanner.createBannerAd(context);
}
public String getUnitID(String type){
if(type.equals(BANNER_TYPE)){
return AD_BANNER_UNIT_ID;
}else if(type.equals(REWARDED_TYPE)){
return AD_VIDEO_ID;
}else if(type.equals(INTERSTITIAL_TYPE)){
return AD_UNIT_ID;
}else{
return "";
}
}
/*
显示google 开屏广告
*/
public static void showOpenAd(){
// Log.d(AdManage.getInstance().TAG, "jsb调用banner");
// AdManage.getInstance().admobOpenManager.showAdIfReady();
}
/*
加载google banner广告
*/
public void loadBannerAd() {
// AdManage.getInstance().admobBanner.adView.loadAd();
}
/*
显示google banner广告
*/
public static void showBannerAd(String pos){
// Log.d(AdManage.getInstance().TAG, "jsb调用banner");
// AdManage.getInstance().admobBanner.adView.loadAd();
}
/*
隐藏google banner广告
*/
public static void hideBannerAd(){
// Log.d(AdManage.getInstance().TAG, "jsb隐藏banner");
// AdManage.getInstance().admobBanner.adView;
}
public static void loadInterstitalAd(){
// AdManage.getInstance().admobInterstitial.interstitialAd.loadAd();
}
public static void showInterstitialAd() {
Log.d(AdManage.getInstance().TAG, "jsb调用插屏");
// if ( MyAdsInterstitial.interstitialAd.isReady() )
// {
// MyAdsInterstitial.interstitialAd.showAd();
// }else {
// MyAdsInterstitial.interstitialAd.loadAd();
// }
AppInterstitialAdManager.getInstance().showAd(AdManage.getInstance().mainActive);
}
public static void initVideoAd(){
// AdManage.getInstance().admobRewarded.rewardedAd.loadAd();
}
//展示广告
public static void showRewardVideoAd(){
Log.d(AdManage.getInstance().TAG, "jsb调用激励视频");
// if ( AdManage.getInstance().admobRewarded.rewardedAd.isReady() )
// {
// AdManage.getInstance().admobRewarded.rewardedAd.showAd();
// }else {
// AdManage.getInstance().admobRewarded.rewardedAd.loadAd();
// }
AppRewardAdManager.getInstance().show(AdManage.getInstance().mainActive);
}
// public void rewardCallBack() {
// AppActivity app = this.mainActive;
// app.runOnGLThread(new Runnable() {
// @Override
// public void run() {
// Cocos2dxJavascriptJavaBridge.evalString("window.PlatformApi.getVideoReward()");
// Log.d(AdManage.getInstance().TAG, "call Rewarded");
// }
// });
// }
//用于cocos监听视频广告播放完成
public static boolean videoRewardedListener(){
return AdManage.getInstance().isVideoRewarded;
}
//用于cocos监听视频广告播放关闭
public static boolean videoCloseListener(){
return AdManage.getInstance().isVideoClose;
}
public boolean networkConnect() {
return true;
}
}
在android studio中的android 里app文件夹的org.cocos2dx.javascript创建包名为admob的package
添加以下几个脚本
1.AppBannerManager.java
package org.cocos2dx.javascript.admob;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.DisplayCutout;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.widget.RelativeLayout;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import java.lang.reflect.Field;
public class AppBannerManager {
public AppBannerManager(Activity activity){
// banner
// Create a new ad view.
Window w = activity.getWindow();
// Insets insets = getSafeInsets(w);
ViewGroup vg = (ViewGroup) w.getDecorView();
// create banner view and container manually
RelativeLayout rl = new RelativeLayout(activity);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_TOP);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
rl.setLayoutParams(lp);
vg.addView(rl);
AdView adview = new AdView(activity);
rl.addView(adview);
adview.setAdUnitId("ca-app-pub-2912341234436825/1575966545");
adview.setAdSize(AdSize.BANNER);
adview.setBackgroundColor(Color.TRANSPARENT);
RelativeLayout.LayoutParams bannerLp = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
bannerLp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
bannerLp.addRule(RelativeLayout.CENTER_HORIZONTAL);
adview.setLayoutParams(bannerLp);
AdRequest adRequest = new AdRequest.Builder().build();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
adview.loadAd(adRequest);
}
});
}
private class Insets {
public int top = 0;
public int bottom = 0;
public int left = 0;
public int right = 0;
}
private Insets getSafeInsets(Window w) {
Insets i = new Insets();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
return i;
}
WindowInsets wi = w.getDecorView().getRootWindowInsets();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.P) {
return i;
}
DisplayCutout dc = wi.getDisplayCutout();
if (dc == null) {
return i;
}
i.top = dc.getSafeInsetTop();
i.bottom = dc.getSafeInsetBottom();
i.left = dc.getSafeInsetLeft();
i.right = dc.getSafeInsetRight();
return i;
}
private RelativeLayout.LayoutParams getLayoutParams(String[] alignments, Insets insets){
RelativeLayout.LayoutParams bannerLp = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
try {
if (alignments != null) {
for (int i = 0; i < alignments.length; i++) {
String a = alignments[i];
Field filed = RelativeLayout.class.getDeclaredField(a);
int rule = filed.getInt(RelativeLayout.class);
if( rule == RelativeLayout.ALIGN_TOP ){
bannerLp.topMargin = insets.top;
}else if( rule == RelativeLayout.ALIGN_BOTTOM){
bannerLp.bottomMargin = insets.bottom;
}else if( rule == RelativeLayout.ALIGN_LEFT){
bannerLp.leftMargin = insets.left;
}else if( rule == RelativeLayout.ALIGN_RIGHT){
bannerLp.rightMargin = insets.right;
}
bannerLp.addRule(rule);
}
}
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return bannerLp;
}
}
2.AppInterstitialAdManager.java
package org.cocos2dx.javascript.admob;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.ads.AdActivity;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import org.cocos2dx.javascript.AppActivity;
public class AppInterstitialAdManager {
private static AppInterstitialAdManager mInstace = null;
public static AppInterstitialAdManager getInstance() {
if (null == mInstace) {
mInstace = new AppInterstitialAdManager();
}
return mInstace;
}
private InterstitialAd mInterstitialAd = null;
private static final String TAG = "Interstitial";
Context mycontext = null;
private boolean isload = false;
public void loadAd(Context context){
AdRequest adRequest = new AdRequest.Builder().build();
mycontext = context;
mInterstitialAd = null;
isload = true;
InterstitialAd.load(context,"ca-app-pub-2912341234436825/1468155339", adRequest,
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
isload = false;
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error
Log.d(TAG, loadAdError.toString());
isload = false;
}
});
}
public void showAd(Activity activity){
if (mInterstitialAd == null){
if (!isload){
// Activity activity = (AdActivity) mycontext;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
loadAd(activity);
}
});
}
return;
}
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
@Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
@Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
mInterstitialAd = null;
// Activity activity = (AdActivity) mycontext;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
loadAd(activity);
}
});
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
mInterstitialAd = null;
// Activity activity = (AdActivity) mycontext;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
loadAd(activity);
}
});
}
@Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}
@Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
// Activity activity = (AdActivity) mycontext;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
mInterstitialAd.show(activity);
}
});
}
}
3.AppOpenAdManager.java
package org.cocos2dx.javascript.admob;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.appopen.AppOpenAd;
import org.cocos2dx.javascript.AppActivity;
import org.cocos2dx.javascript.GlobalApplication;
import java.util.Date;
public class AppOpenAdManager {
private static final String LOG_TAG = "AppOpenAdManager";
private static final String AD_UNIT_ID = "ca-app-pub-2912341234436825/4441803032";
public static long startTime;
private AppOpenAd appOpenAd = null;
private boolean isLoadingAd = false;
public static boolean isShowingAd = false;
/** Constructor. */
public AppOpenAdManager(Context context) {
this.loadAd(context);
}
/** Request an ad. */
private void loadAd(Context context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
return;
}
isLoadingAd = true;
AdRequest request = new AdRequest.Builder().build();
AppOpenAd.load(
context, AD_UNIT_ID, request,
new AppOpenAd.AppOpenAdLoadCallback() {
@Override
public void onAdLoaded(AppOpenAd ad) {
// Called when an app open ad has loaded.
Log.d(LOG_TAG, "Ad was loaded.");
appOpenAd = ad;
isLoadingAd = false;
if ((new Date()).getTime() - startTime < 3000){
showAdIfAvailable((AppActivity) context,
new GlobalApplication.OnShowAdCompleteListener() {
@Override
public void onShowAdComplete() {
// Empty because the user will go back to the activity that shows the ad.
Log.d(LOG_TAG, "Ad was showed.");
}
});
}
}
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
// Called when an app open ad has failed to load.
Log.d(LOG_TAG, loadAdError.getMessage());
isLoadingAd = false;
}
});
}
/** Check if ad exists and can be shown. */
private boolean isAdAvailable() {
return appOpenAd != null;
}
/** Shows the ad if one isn't already showing. */
public void showAdIfAvailable(
@NonNull final Activity activity,
@NonNull GlobalApplication.OnShowAdCompleteListener onShowAdCompleteListener){
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(LOG_TAG, "The app open ad is already showing.");
return;
}
// If the app open ad is not available yet, invoke the callback then load the ad.
if (!isAdAvailable()) {
Log.d(LOG_TAG, "The app open ad is not ready yet.");
onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
return;
}
appOpenAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
@Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, "Ad dismissed fullscreen content.");
appOpenAd = null;
isShowingAd = false;
onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, adError.getMessage());
appOpenAd = null;
isShowingAd = false;
onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
}
@Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d(LOG_TAG, "Ad showed fullscreen content.");
}
});
isShowingAd = true;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
appOpenAd.show(activity);
}
});
}
}
4.AppRewardAdManager.java
package org.cocos2dx.javascript.admob;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
import org.cocos2dx.javascript.AppActivity;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
public class AppRewardAdManager {
private static AppRewardAdManager mInstace = null;
public static AppRewardAdManager getInstance() {
if (null == mInstace) {
mInstace = new AppRewardAdManager();
}
return mInstace;
}
private boolean isload = false;
private RewardedAd rewardedAd = null;
private static final String TAG = "RewardedAd";
Context mycontext = null;
public void load(Context context) {
mycontext = context;
AdRequest adRequest = new AdRequest.Builder().build();
rewardedAd = null;
isload = true;
RewardedAd.load(context, "ca-app-pub-2912341234436825/3303534070",
adRequest, new RewardedAdLoadCallback() {
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error.
Log.d(TAG, loadAdError.toString());
rewardedAd = null;
isload = false;
}
@Override
public void onAdLoaded(@NonNull RewardedAd ad) {
rewardedAd = ad;
Log.d(TAG, "Ad was loaded.");
isload = false;
}
});
}
public void show(Activity activity){
if (rewardedAd == null){
if (!isload){
// Activity activity = (AppActivity) mycontext;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
load(activity);
}
});
}
return;
}
rewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
@Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
rewardedAd = null;
// Activity activity = (AppActivity) mycontext;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
load(activity);
}
});
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
rewardedAd = null;
// Activity activity = (AppActivity) mycontext;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
load(activity);
}
});
}
@Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}
@Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
// Activity activity = (AppActivity) mycontext;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
rewardedAd.show(activity,new OnUserEarnedRewardListener() {
@Override
public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
// Handle the reward.
Log.d(TAG, "The user earned the reward.");
int rewardAmount = rewardItem.getAmount();
String rewardType = rewardItem.getType();
rewardCallBack((AppActivity) activity);
}
});
}
});
}
public void rewardCallBack(AppActivity activity) {
// AppActivity app =(AppActivity) mycontext;
activity.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxJavascriptJavaBridge.evalString("window.PlatformApi.getVideoReward()");
Log.d(TAG, "call Rewarded");
}
});
}
}