当前位置:   article > 正文

CososCreator (Android)-AppLovin MAX 广告聚合平台接入+Firebase统计_a problem occurred evaluating project ':game'. > p

a problem occurred evaluating project ':game'. > plugin with id 'com.android

CososCreator 2.4.4

Android Studio :4.2.1

接入SDK有:接max聚合及中介平台(Admob,FB, applovin,pangle,mintegral,vungle,unity),和Firebase 统计

1、构建Android工程

 2、升级gradle版本

升级完后可能出现如下问题:

a)A problem occurred evaluating project ':game'.
> Plugin with id 'com.android.feature' not found. 

解决参考链接: 
Cocos Creator Android原生项目升级gradle版本 - Creator 2.x - Cocos中文社区gradle 版本原来版本 :4.10.3(插件3.2.0) 升级后版本: 5.6.4(插件3.6.3) gradle路径:jsb-default/frameworks/runtime-src/proj.android-studi…https://forum.cocos.org/t/topic/103837

 

b)Execution failed for task ':food:mergeDebugAssets'.
> Could not copy file 'F:\Hopemobi\food_B\build\jsb-link\assets\internal' to 'F:\Hopemobi\food_B\build\jsb-link\frameworks\runtime-src\proj.android-studio\app\task ':food:mergeDebugAssets' property 'outputDir'\assets\internal'.
   > Failed to create parent directory 'F:\Hopemobi\food_B\build\jsb-link\frameworks\runtime-src\proj.android-studio\app\task ':food:mergeDebugAssets' property 'outputDir'' when creating directory 'F:\Hopemobi\food_B\build\jsb-link\frameworks\runtime-src\proj.android-studio\app\task ':food:mergeDebugAssets' property 'outputDir'\assets\internal'

app/build.gradle(资源复制丢失)

原因:构建失败

路径:jsb-default/frameworks/runtime-src/proj.android-studio/app/build.gradle

  1. android.applicationVariants.all { variant ->
  2. // delete previous files first
  3. delete "${buildDir}/intermediates/merged_assets/${variant.dirName}"
  4. //修改 报警错误 API 'variant.getMergeAssets()' is obsolete and has been replaced with 'variant.getMergeAssetsProvider()'.It will be removed at the end of 2019.
  5. // variant.mergeAssets.doLast {
  6. variant.mergeAssetsProvider.get().doLast{
  7. def sourceDir = "${buildDir}/../../../../.."
  8. copy {
  9. from "${sourceDir}/assets"
  10. into outputDir.dir("assets")
  11. into outputDir.dir("assets")
  12. }
  13. copy {
  14. from "${sourceDir}/src"
  15. into "${outputDir}/src"
  16. into outputDir.dir("src")
  17. }
  18. copy {
  19. from "${sourceDir}/jsb-adapter"
  20. into "${outputDir}/jsb-adapter"
  21. into outputDir.dir("jsb-adapter")
  22. }
  23. copy {
  24. from "${sourceDir}/main.js"
  25. from "${sourceDir}/project.json"
  26. into outputDir
  27. }
  28. }
  29. }

c) 将项目选择为游戏项目,运行

 

 3、AppLovin Max聚合接入(具体接入根据官方来,本文提供一些接入问题)

官方文档:

 MAX Mediation Documentationhttps://dash.applovin.com/documentation/mediation/android/getting-started/integration添加到应用程序级 build.gradle中加入:

  1. repositories {
  2. google()
  3. mavenCentral()
  4. }
  5. dependencies {
  6. implementation 'com.applovin:applovin-sdk:+'
  7. }
  1. android {
  2. compileOptions {
  3. sourceCompatibility = JavaVersion.VERSION_1_8
  4. targetCompatibility = JavaVersion.VERSION_1_8
  5. }
  6. }
注意: AppLovin SDK 要求您将 minSdkVersion 设置为 16 或以上。

 添加 SDK 密钥:<meta-data>元素到你的AndroidManifest.xml

<meta-data android:name="applovin.sdk.key"
           android:value="YOUR_SDK_KEY_HERE"/>

添加到应用程序级 build.gradle 文件

apply plugin: 'applovin-quality-service'
applovin {
       apiKey "YOUR_AD_REVIEW_KEY_HERE"
}

添加到根级 build.gradle 文件

  1. buildscript {
  2. repositories {
  3. maven { url 'https://artifacts.applovin.com/android' }
  4. }
  5. dependencies {
  6. classpath "com.applovin.quality:AppLovinQualityServiceGradlePlugin:+"
  7. }
  8. }

d)This project uses AndroidX dependencies, but the android.useAndroidX property is not enabled

This project uses AndroidX dependencies, but the android.useAndroidX property is not enabled的解决_7DO的博客-CSDN博客

gradle.properties中加入:

android.useAndroidX=true
android.enableJetifier=true

e)Execution failed for task ':food:processReleaseMainManifest'.
> Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 19 declared in library [com.google.android.gms:play-services-ads:21.3.0] 

PROP_MIN_SDK_VERSION=21

f)Manifest merger failed : Apps targeting Android 12 and higher are required to specify an explicit v

Manifest merger failed : Apps targeting Android 12 and higher are required to specify an explicit v_lplj717的博客-CSDN博客

g)Expiring Daemon because JVM heap space is exhausted

Expiring Daemon because JVM heap space is exhausted_auccy的博客-CSDN博客_expiring daemon

在 gradle.properties 文件中添加

org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=512m

f)Could not determine the dependencies of task ':food:lintVitalRelease'.
> Could not resolve all artifacts for configuration ':food:debugCompileClasspath'.
   > Could not find com.pangle.global:ads-sdk:4.8.1.0.

buildscript和allprojects和subprojects的区别.Android Studio_厚积而薄发ing的博客-CSDN博客_android subprojects

在buildscript,allprojects 中都添加上 

 

 最终根级 build.gradle 文件

  1. // Top-level build file where you can add configuration options common to all sub-projects/modules.
  2. buildscript {
  3. repositories {
  4. google()
  5. jcenter()
  6. maven { url 'https://artifacts.applovin.com/android' }
  7. maven { url "https://artifact.bytedance.com/repository/pangle" }
  8. maven { url "https://dl-maven-android.mintegral.com/repository/mbridge_android_sdk_oversea" }
  9. }
  10. dependencies {
  11. classpath 'com.android.tools.build:gradle:4.2.1'
  12. classpath 'com.applovin.quality:AppLovinQualityServiceGradlePlugin:+'
  13. classpath 'com.google.gms:google-services:4.3.14' //firebase
  14. // NOTE: Do not place your application dependencies here; they belong
  15. // in the individual module build.gradle files
  16. }
  17. }
  18. allprojects {
  19. repositories {
  20. google()
  21. jcenter()
  22. flatDir {
  23. dirs 'libs'
  24. }
  25. maven { url "https://artifact.bytedance.com/repository/pangle" }
  26. maven { url "https://dl-maven-android.mintegral.com/repository/mbridge_android_sdk_oversea" }
  27. }
  28. }
  29. task clean(type: Delete) {
  30. delete rootProject.buildDir
  31. }

  最终根级 build.gradle 文件

  1. import org.apache.tools.ant.taskdefs.condition.Os
  2. apply plugin: 'com.android.application'
  3. apply plugin: 'applovin-quality-service'
  4. apply plugin: 'com.google.gms.google-services'
  5. applovin {
  6. // NOTE: DO NOT CHANGE - this is NOT your AppLovin MAX SDK key - this is a derived key.
  7. apiKey 'e8dPgaJuOF6-3xeoEizRgzB34eU-yLeAmiXTMhPFLstzUTpTF20SaWC8y3n0wbxVCXoHhdet1wyp9-MUBs__iy'
  8. }
  9. android {
  10. compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger()
  11. buildToolsVersion '30.0.2'
  12. defaultConfig {
  13. applicationId "com.starqbaby.FastFood"
  14. minSdkVersion PROP_MIN_SDK_VERSION
  15. targetSdkVersion PROP_TARGET_SDK_VERSION
  16. versionCode 12
  17. versionName "1.0.12"
  18. externalNativeBuild {
  19. ndkBuild {
  20. if (!project.hasProperty("PROP_NDK_MODE") || PROP_NDK_MODE.compareTo('none') != 0) {
  21. // skip the NDK Build step if PROP_NDK_MODE is none
  22. targets 'cocos2djs'
  23. arguments 'NDK_TOOLCHAIN_VERSION=clang'
  24. def module_paths = [project.file("D:/CocosDashboard_1.0.14/resources/.editors/Creator/2.4.4/resources/cocos2d-x"),
  25. project.file("D:/CocosDashboard_1.0.14/resources/.editors/Creator/2.4.4/resources/cocos2d-x/cocos"),
  26. project.file("D:/CocosDashboard_1.0.14/resources/.editors/Creator/2.4.4/resources/cocos2d-x/external")]
  27. if (Os.isFamily(Os.FAMILY_WINDOWS)) {
  28. arguments 'NDK_MODULE_PATH=' + module_paths.join(";")
  29. }
  30. else {
  31. arguments 'NDK_MODULE_PATH=' + module_paths.join(':')
  32. }
  33. arguments '-j' + Runtime.runtime.availableProcessors()
  34. abiFilters.addAll(PROP_APP_ABI.split(':').collect{it as String})
  35. }
  36. }
  37. }
  38. }
  39. sourceSets.main {
  40. java.srcDirs "../src", "src"
  41. res.srcDirs "../res", 'res'
  42. jniLibs.srcDirs "../libs", 'libs'
  43. manifest.srcFile "AndroidManifest.xml"
  44. }
  45. compileOptions {
  46. sourceCompatibility = JavaVersion.VERSION_1_8
  47. targetCompatibility = JavaVersion.VERSION_1_8
  48. }
  49. externalNativeBuild {
  50. ndkBuild {
  51. if (!project.hasProperty("PROP_NDK_MODE") || PROP_NDK_MODE.compareTo('none') != 0) {
  52. // skip the NDK Build step if PROP_NDK_MODE is none
  53. path "jni/Android.mk"
  54. }
  55. }
  56. }
  57. signingConfigs {
  58. release {
  59. if (project.hasProperty("RELEASE_STORE_FILE")) {
  60. storeFile file(RELEASE_STORE_FILE)
  61. storePassword RELEASE_STORE_PASSWORD
  62. keyAlias RELEASE_KEY_ALIAS
  63. keyPassword RELEASE_KEY_PASSWORD
  64. }
  65. }
  66. }
  67. buildTypes {
  68. release {
  69. debuggable false
  70. jniDebuggable false
  71. renderscriptDebuggable false
  72. minifyEnabled true
  73. shrinkResources true
  74. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  75. if (project.hasProperty("RELEASE_STORE_FILE")) {
  76. signingConfig signingConfigs.release
  77. }
  78. externalNativeBuild {
  79. ndkBuild {
  80. arguments 'NDK_DEBUG=0'
  81. }
  82. }
  83. }
  84. debug {
  85. debuggable true
  86. jniDebuggable true
  87. renderscriptDebuggable true
  88. externalNativeBuild {
  89. ndkBuild {
  90. arguments 'NDK_DEBUG=1'
  91. }
  92. }
  93. }
  94. }
  95. }
  96. android.applicationVariants.all { variant ->
  97. // delete previous files first
  98. delete "${buildDir}/intermediates/merged_assets/${variant.dirName}"
  99. //修改 报警错误 API 'variant.getMergeAssets()' is obsolete and has been replaced with 'variant.getMergeAssetsProvider()'.It will be removed at the end of 2019.
  100. // variant.mergeAssets.doLast {
  101. variant.mergeAssetsProvider.get().doLast{
  102. def sourceDir = "${buildDir}/../../../../.."
  103. copy {
  104. from "${sourceDir}/assets"
  105. into outputDir.dir("assets")
  106. into outputDir.dir("assets")
  107. }
  108. copy {
  109. from "${sourceDir}/src"
  110. into "${outputDir}/src"
  111. into outputDir.dir("src")
  112. }
  113. copy {
  114. from "${sourceDir}/jsb-adapter"
  115. into "${outputDir}/jsb-adapter"
  116. into outputDir.dir("jsb-adapter")
  117. }
  118. copy {
  119. from "${sourceDir}/main.js"
  120. from "${sourceDir}/project.json"
  121. into outputDir
  122. }
  123. }
  124. }
  125. dependencies {
  126. implementation fileTree(dir: '../libs', include: ['*.jar','*.aar'])
  127. implementation fileTree(dir: 'libs', include: ['*.jar','*.aar'])
  128. implementation fileTree(dir: "D:/CocosDashboard_1.0.14/resources/.editors/Creator/2.4.4/resources/cocos2d-x/cocos/platform/android/java/libs", include: ['*.jar'])
  129. implementation project(':libcocos2dx')
  130. implementation 'com.applovin:applovin-sdk:+'
  131. // Import the Firebase BoM
  132. implementation platform('com.google.firebase:firebase-bom:31.1.1')
  133. // Declare the dependency for the Firebase SDK for Google Analytics
  134. implementation 'com.google.firebase:firebase-analytics'
  135. //其他中介广告源
  136. //Admob
  137. implementation 'com.applovin.mediation:google-adapter:+'
  138. //FB
  139. implementation 'com.applovin.mediation:facebook-adapter:+'
  140. //vungle
  141. implementation 'com.applovin.mediation:vungle-adapter:+'
  142. //unity
  143. implementation 'com.applovin.mediation:unityads-adapter:+'
  144. //pangle
  145. implementation 'com.applovin.mediation:bytedance-adapter:+'
  146. //mintegral
  147. implementation 'com.applovin.mediation:mintegral-adapter:+'
  148. implementation 'androidx.recyclerview:recyclerview:1.1.0'
  149. }

 AdsBanner.java

  1. package org.cocos2dx.javascript.ads;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.util.Log;
  5. import android.view.Gravity;
  6. import android.view.View;
  7. import android.view.ViewGroup;
  8. import android.widget.FrameLayout;
  9. import android.widget.LinearLayout;
  10. import com.applovin.mediation.MaxAd;
  11. import com.applovin.mediation.MaxAdViewAdListener;
  12. import com.applovin.mediation.MaxError;
  13. import com.applovin.mediation.ads.MaxAdView;
  14. import com.starqbaby.FastFood.R;
  15. import org.cocos2dx.javascript.AdManage;
  16. import org.cocos2dx.javascript.AppActivity;
  17. public class AdsBanner {
  18. private Context mainActive = null;
  19. private ViewGroup rootView;
  20. private MaxAdView mAdView;
  21. private String adPos;
  22. private int screenWidth;
  23. //-----------类型常量-------------
  24. private static String BANNER_TYPE = "0";
  25. //获得广告位id
  26. private static String AD_Banner_ID;
  27. public void init(Context context,int wid){
  28. this.mainActive = context;
  29. this.screenWidth = wid;
  30. AD_Banner_ID = AdManage.getInstance().getUnitID(BANNER_TYPE);
  31. }
  32. /*
  33. 加载banner广告
  34. */
  35. public void loadBannerAd() {
  36. //请求banner
  37. AdManage.getInstance().FAEventSuccess("Mobi_40101",AD_Banner_ID,BANNER_TYPE);
  38. mAdView = new MaxAdView(AD_Banner_ID,this.mainActive );
  39. // Stretch to the width of the screen for banners to be fully functional
  40. int width = ViewGroup.LayoutParams.WRAP_CONTENT;
  41. // Banner height on phones and tablets is 50 and 90, respectively
  42. int heightPx = this.mainActive.getResources().getDimensionPixelSize( R.dimen.banner_height );
  43. FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( width, heightPx ) ;
  44. params.gravity=Gravity.TOP;
  45. //params.leftMargin = this.screenWidth /2;
  46. Log.d(AdManage.getInstance().TAG, "screenWidth"+this.screenWidth);
  47. mAdView.setLayoutParams(params);
  48. //Set background or background color for banners to be fully functional
  49. //adView.setBackgroundColor( ... );
  50. rootView= (ViewGroup)((Activity) this.mainActive).findViewById(android.R.id.content);
  51. rootView.addView( mAdView );
  52. mAdView.setVisibility(View.VISIBLE);
  53. // Load the ad
  54. mAdView.loadAd();
  55. //banner监听
  56. mAdView.setListener(new MaxAdViewAdListener() {
  57. // MAX Ad Listener
  58. @Override
  59. public void onAdLoaded(final MaxAd maxAd)
  60. {
  61. Log.d(AdManage.getInstance().TAG, "onAdLoaded: (banner)");
  62. //successFAEvent("loadBannerAd");
  63. AdManage.getInstance().FAEventSuccess("Mobi_40201",AD_Banner_ID,BANNER_TYPE);
  64. }
  65. @Override
  66. public void onAdLoadFailed(final String adUnitId, final MaxError error)
  67. {
  68. Log.d(AdManage.getInstance().TAG, "onAdFailedToLoad: (banner)"+error);
  69. String errorMessage = error.getMessage();
  70. //加载错误事件
  71. int errorCode = error.getCode();
  72. //failFAEvent(errorCode,"banner");
  73. //-----
  74. //广告填充失败
  75. AdManage.getInstance().FAEventFail("Mobi_40201",AD_Banner_ID,BANNER_TYPE,String.valueOf(errorCode),errorMessage);
  76. }
  77. @Override
  78. public void onAdDisplayFailed(final MaxAd maxAd, final MaxError error) {}
  79. @Override
  80. public void onAdClicked(final MaxAd maxAd)
  81. {
  82. //广告点击
  83. AdManage.getInstance().FAEventSuccess("Mobi_40401",AD_Banner_ID,BANNER_TYPE);
  84. }
  85. @Override
  86. public void onAdExpanded(final MaxAd maxAd) {}
  87. @Override
  88. public void onAdCollapsed(final MaxAd maxAd) {}
  89. @Override
  90. public void onAdDisplayed(final MaxAd maxAd) { /* DO NOT USE - THIS IS RESERVED FOR FULLSCREEN ADS ONLY AND WILL BE REMOVED IN A FUTURE SDK RELEASE */ }
  91. @Override
  92. public void onAdHidden(final MaxAd maxAd) { /* DO NOT USE - THIS IS RESERVED FOR FULLSCREEN ADS ONLY AND WILL BE REMOVED IN A FUTURE SDK RELEASE */ }
  93. });
  94. }
  95. /*
  96. banner广告
  97. */
  98. public void showBannerAd(String pos){
  99. AppActivity mActivity = (AppActivity)this.mainActive;
  100. this.adPos = pos;
  101. int mWidth = this.screenWidth;
  102. //一定要确保在UI线程操作
  103. mActivity.runOnUiThread(new Runnable() {
  104. @Override
  105. public void run() {
  106. Log.d(AdManage.getInstance().TAG, "showBannerAd: adPos "+adPos);
  107. FrameLayout.LayoutParams params=(FrameLayout.LayoutParams )mAdView.getLayoutParams();
  108. if(adPos.equals("top")){
  109. params.gravity=Gravity.TOP;
  110. params.leftMargin = 0;
  111. }else if(adPos.equals("top-left")){
  112. params.gravity=Gravity.TOP;
  113. params.leftMargin = -mWidth /2;
  114. }else if(adPos.equals("bottom")){
  115. params.gravity=Gravity.BOTTOM;
  116. params.leftMargin = 0;
  117. }else if(adPos.equals("bottom-left")){
  118. params.gravity=Gravity.BOTTOM;
  119. params.leftMargin = -mWidth /2;
  120. }
  121. mAdView.setLayoutParams(params);
  122. mAdView.setVisibility(View.VISIBLE);
  123. }
  124. });
  125. }
  126. /*
  127. 隐藏 banner广告
  128. */
  129. public void hideBannerAd(){
  130. //有用接口,先注释,取消隐藏banner
  131. AppActivity mActivity = (AppActivity)this.mainActive;
  132. //一定要确保在UI线程操作
  133. mActivity.runOnUiThread(new Runnable() {
  134. @Override
  135. public void run() {
  136. Log.d(AdManage.getInstance().TAG, "hideBannerAd");
  137. mAdView.setVisibility(View.INVISIBLE);
  138. }
  139. });
  140. }
  141. }

AdsInterstitial.java

  1. package org.cocos2dx.javascript.ads;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.os.Handler;
  5. import android.util.Log;
  6. import android.widget.Toast;
  7. import androidx.annotation.NonNull;
  8. import com.applovin.mediation.MaxAd;
  9. import com.applovin.mediation.MaxAdListener;
  10. import com.applovin.mediation.MaxError;
  11. import com.applovin.mediation.ads.MaxInterstitialAd;
  12. import org.cocos2dx.javascript.AdManage;
  13. import org.cocos2dx.javascript.AppActivity;
  14. import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
  15. import java.util.concurrent.TimeUnit;
  16. public class AdsInterstitial implements MaxAdListener {
  17. private static String INTERSTITIAL_TYPE = "1"; //类型常量
  18. private static String AD_INTERSTITIAL_ID;//正式插屏
  19. private static MaxInterstitialAd interstitialAd;
  20. private int insUnitIdIdex = 0;
  21. private int insReLoadTime = 1; //插屏加载失败时,允许重新加载几次插屏
  22. private int curInsReloadTime = 0; //当前插屏重新加载次数
  23. private Context mainActive = null;
  24. public void init(Context context){
  25. this.mainActive = context;
  26. AD_INTERSTITIAL_ID = AdManage.getInstance().getUnitID(INTERSTITIAL_TYPE);
  27. }
  28. private int retryAttempt;
  29. public void loadInterstitalAd(){
  30. AppActivity mActivity = (AppActivity)this.mainActive;
  31. AdsInterstitial mUser=this;
  32. mActivity.runOnUiThread(new Runnable() {
  33. @Override
  34. public void run() {
  35. Log.d(AdManage.getInstance().TAG, "loadInterstitalAd....: "+AdsInterstitial.AD_INTERSTITIAL_ID);
  36. //successFAEvent("LoadInterstitalAd");
  37. //插屏广告请求
  38. AdManage.getInstance().FAEventSuccess("Mobi_40101",AdsInterstitial.AD_INTERSTITIAL_ID,INTERSTITIAL_TYPE);
  39. MaxInterstitialAd interstitialAd = new MaxInterstitialAd( AdsInterstitial.AD_INTERSTITIAL_ID, mActivity );
  40. // Load the first ad
  41. AdsInterstitial.interstitialAd=interstitialAd;
  42. interstitialAd.setListener(mUser);
  43. interstitialAd.loadAd();
  44. }
  45. });
  46. }
  47. public void showInterstitialAd() {
  48. // Show the ad if it's ready. Otherwise toast and restart the game.
  49. Log.d(AdManage.getInstance().TAG, "showInterstitial: ");
  50. AppActivity mActivity = (AppActivity)this.mainActive;
  51. //一定要确保在UI线程操作
  52. mActivity.runOnUiThread(new Runnable() {
  53. @Override
  54. public void run() {
  55. if (AdsInterstitial.interstitialAd != null && interstitialAd.isReady()) {
  56. interstitialAd.showAd();
  57. } else {
  58. Toast.makeText((Activity) mActivity, "Ad did not load", Toast.LENGTH_SHORT).show();
  59. }
  60. AdManage.getInstance().FAEventSuccess("Mobi_40301", AdsInterstitial.AD_INTERSTITIAL_ID, INTERSTITIAL_TYPE);
  61. }
  62. });
  63. }
  64. @Override
  65. public void onAdLoaded(MaxAd ad) {
  66. Log.i(AdManage.getInstance().TAG, "onAdLoaded(AdsInterstitial)");
  67. //加载插屏广告成功
  68. AdManage.getInstance().FAEventSuccess("Mobi_40201",AdsInterstitial.AD_INTERSTITIAL_ID,INTERSTITIAL_TYPE);
  69. retryAttempt = 0;
  70. }
  71. @Override
  72. public void onAdLoadFailed(String adUnitId, MaxError error) {
  73. String error1 =String.format("code: %d, message: %s",error.getCode(), error.getMessage());
  74. Log.d(AdManage.getInstance().TAG, "AdsInterstitial Failed : " + error1);
  75. String errorMessage = error.getMessage();
  76. //加载错误事件
  77. int errorCode = error.getCode();
  78. //failFAEvent(errorCode,"InterstitalAd");
  79. //-----
  80. //广告填充失败
  81. AdManage.getInstance().FAEventFail("Mobi_40201",AdsInterstitial.AD_INTERSTITIAL_ID,INTERSTITIAL_TYPE,String.valueOf(errorCode),errorMessage);
  82. //Toast.makeText((Activity) mActivity, "onAdFailedToLoad() with error: " + error1, Toast.LENGTH_SHORT).show();
  83. retryAttempt++;
  84. long delayMillis = TimeUnit.SECONDS.toMillis( (long) Math.pow( 2, Math.min( 6, retryAttempt ) ) );
  85. new Handler().postDelayed(new Runnable()
  86. {
  87. @Override
  88. public void run()
  89. {
  90. interstitialAd.loadAd();
  91. }
  92. }, delayMillis );
  93. }
  94. @Override
  95. public void onAdDisplayFailed(MaxAd ad, MaxError error) {
  96. Log.d(AdManage.getInstance().TAG, "onAdDisplayFailed");
  97. interstitialAd.loadAd();
  98. }
  99. @Override
  100. public void onAdDisplayed(MaxAd ad) {
  101. Log.d(AdManage.getInstance().TAG, "onAdDisplayed");
  102. }
  103. @Override
  104. public void onAdClicked(MaxAd ad) {
  105. Log.d(AdManage.getInstance().TAG, "onAdClicked");
  106. }
  107. @Override
  108. public void onAdHidden(MaxAd ad) {
  109. Log.d(AdManage.getInstance().TAG, "onAdHidden");
  110. interstitialAd.loadAd();
  111. AppActivity app = (AppActivity) this.mainActive;
  112. app.runOnGLThread(new Runnable() {
  113. @Override
  114. public void run() {
  115. Cocos2dxJavascriptJavaBridge.evalString("window.PlatformApi.getInterstitalHidden()");
  116. Log.d(AdManage.getInstance().TAG, "AdsInterstitial call onAdHidden");
  117. }
  118. });
  119. }
  120. }

AdsRewarded.java

  1. package org.cocos2dx.javascript.ads;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.os.Handler;
  5. import android.util.Log;
  6. import android.widget.Toast;
  7. import androidx.annotation.NonNull;
  8. import com.applovin.mediation.MaxAd;
  9. import com.applovin.mediation.MaxError;
  10. import com.applovin.mediation.MaxReward;
  11. import com.applovin.mediation.MaxRewardedAdListener;
  12. import com.applovin.mediation.ads.MaxRewardedAd;
  13. import org.cocos2dx.javascript.AdManage;
  14. import org.cocos2dx.javascript.AppActivity;
  15. import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
  16. import java.util.concurrent.TimeUnit;
  17. public class AdsRewarded {
  18. private Context mainActive = null;
  19. private static MaxRewardedAd mRewardedAd;
  20. private static String REWARDED_TYPE = "8"; //类型常量
  21. private static String AD_VIDEO_ID;//激励视频广告ID(正式)
  22. public void init(Context context){
  23. this.mainActive = context;
  24. AD_VIDEO_ID = AdManage.getInstance().getUnitID(REWARDED_TYPE);
  25. }
  26. private static int retryAttempt;
  27. public void initVideoAd(){
  28. AppActivity mActivity = (AppActivity) this.mainActive;
  29. //一定要确保在UI线程操作
  30. mActivity.runOnUiThread(new Runnable() {
  31. @Override
  32. public void run() {
  33. AdManage.getInstance().FAEventSuccess("Mobi_40101",AdsRewarded.AD_VIDEO_ID,REWARDED_TYPE);
  34. MaxRewardedAd rewardedAd = MaxRewardedAd.getInstance( AdsRewarded.AD_VIDEO_ID,mActivity );
  35. rewardedAd.setListener(new MaxRewardedAdListener() {
  36. @Override
  37. public void onAdLoaded(MaxAd ad) {
  38. Log.d(AdManage.getInstance().TAG, "onAdLoaded.(AdsRewarded)");
  39. AdManage.getInstance().FAEventSuccess("Mobi_40201",AdsRewarded.AD_VIDEO_ID,REWARDED_TYPE);
  40. AdsRewarded.retryAttempt=0;
  41. }
  42. @Override
  43. public void onAdLoadFailed(String adUnitId, MaxError error) {
  44. String error1 =String.format("code: %d, message: %s",error.getCode(), error.getMessage());
  45. Log.d(AdManage.getInstance().TAG, "AdsInterstitial Failed : " + error1);
  46. String errorMessage = error.getMessage();
  47. int errorCode = error.getCode();
  48. AdManage.getInstance().FAEventFail("Mobi_40202",AdsRewarded.AD_VIDEO_ID,REWARDED_TYPE,String.valueOf(errorCode),errorMessage);
  49. AdsRewarded.retryAttempt++;
  50. long delayMillis = TimeUnit.SECONDS.toMillis( (long) Math.pow( 2, Math.min( 6, retryAttempt ) ) );
  51. new Handler().postDelayed(new Runnable()
  52. {
  53. @Override
  54. public void run()
  55. {
  56. AdsRewarded.mRewardedAd.loadAd();
  57. }
  58. }, delayMillis );
  59. }
  60. @Override
  61. public void onAdDisplayFailed(MaxAd ad, MaxError error) {
  62. AdsRewarded.mRewardedAd.loadAd();
  63. }
  64. @Override
  65. public void onAdClicked(MaxAd ad) {
  66. }
  67. @Override
  68. public void onAdDisplayed(MaxAd ad) {
  69. }
  70. @Override
  71. public void onAdHidden(MaxAd ad) {
  72. AdsRewarded.mRewardedAd.loadAd();
  73. AppActivity app = mActivity;
  74. app.runOnGLThread(new Runnable() {
  75. @Override
  76. public void run() {
  77. Cocos2dxJavascriptJavaBridge.evalString("window.PlatformApi.getVideoHidden()");
  78. Log.d(AdManage.getInstance().TAG, "AdsRewarded call onAdHidden");
  79. }
  80. });
  81. }
  82. @Override
  83. public void onRewardedVideoStarted(MaxAd ad) {
  84. }
  85. @Override
  86. public void onRewardedVideoCompleted(MaxAd ad) {
  87. }
  88. @Override
  89. public void onUserRewarded(MaxAd ad, MaxReward reward) {
  90. Log.d(AdManage.getInstance().TAG, "The user earned the reward.");
  91. int rewardAmount = reward.getAmount();
  92. String rewardType = reward.getLabel();
  93. Log.d(AdManage.getInstance().TAG, "call before");
  94. AppActivity app = mActivity;
  95. app.runOnGLThread(new Runnable() {
  96. @Override
  97. public void run() {
  98. Cocos2dxJavascriptJavaBridge.evalString("window.PlatformApi.getVideoReward()");
  99. Log.d(AdManage.getInstance().TAG, "call Rewarded");
  100. }
  101. });
  102. //successFAEvent("EarnedReward");
  103. AdManage.getInstance().FAEventSuccess("Mobi_40301",AdsRewarded.AD_VIDEO_ID,REWARDED_TYPE);
  104. }
  105. });
  106. AdsRewarded.mRewardedAd = rewardedAd;
  107. rewardedAd.loadAd();
  108. }
  109. });
  110. }
  111. //展示广告
  112. public void showRewardVideoAd(){
  113. AppActivity mActivity = (AppActivity) this.mainActive;
  114. mActivity.runOnUiThread(new Runnable() {
  115. @Override
  116. public void run() {
  117. if (AdsRewarded.mRewardedAd != null&&AdsRewarded.mRewardedAd.isReady()) {
  118. AdsRewarded.mRewardedAd.showAd();
  119. } else {
  120. Log.d(AdManage.getInstance().TAG, "The rewarded ad wasn't ready yet.");
  121. Toast.makeText((Activity) mActivity, "Ad did not load", Toast.LENGTH_SHORT).show();
  122. }
  123. }
  124. });
  125. }
  126. }

AdManage.java(广告管理) 

  1. package org.cocos2dx.javascript;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.util.Log;
  5. import android.view.Gravity;
  6. import android.view.View;
  7. import android.view.ViewGroup;
  8. import android.widget.FrameLayout;
  9. import android.widget.LinearLayout;
  10. import android.widget.Toast;
  11. import androidx.annotation.NonNull;
  12. import com.applovin.mediation.MaxAd;
  13. import com.applovin.mediation.MaxAdListener;
  14. import com.applovin.mediation.MaxAdViewAdListener;
  15. import com.applovin.mediation.MaxError;
  16. import com.applovin.mediation.MaxReward;
  17. import com.applovin.mediation.MaxRewardedAdListener;
  18. import com.applovin.mediation.ads.MaxAdView;
  19. import com.applovin.mediation.ads.MaxInterstitialAd;
  20. import com.applovin.mediation.ads.MaxRewardedAd;
  21. import com.applovin.sdk.AppLovinSdk;
  22. import com.applovin.sdk.AppLovinSdkConfiguration;
  23. import org.cocos2dx.javascript.ads.AdsBanner;
  24. import org.cocos2dx.javascript.ads.AdsInterstitial;
  25. import org.cocos2dx.javascript.ads.AdsRewarded;
  26. import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
  27. import com.google.android.gms.ads.MobileAds;
  28. import com.google.android.gms.ads.RequestConfiguration;
  29. import static com.google.android.gms.ads.RequestConfiguration.MAX_AD_CONTENT_RATING_G;
  30. import static com.google.android.gms.ads.RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_TRUE;
  31. public class AdManage {
  32. private static final String AD_BANNER_UNIT_ID = "id";//横幅广告ID
  33. private static final String AD_UNIT_ID = "id"; //插页广告
  34. private static final String AD_VIDEO_ID = "id";//激励视频广告ID
  35. private Context mainActive = null;
  36. private static AdManage mInstace = null;
  37. private MaxAdView adView;
  38. private LinearLayout bannerLayout;
  39. private String adPos;
  40. public final String TAG = "ADManage";
  41. private int screenWidth;
  42. private AdsBanner admobBanner = new AdsBanner();
  43. private AdsInterstitial admobInterstitial = new AdsInterstitial();
  44. private AdsRewarded admobRewarded = new AdsRewarded();
  45. //-----------类型常量-------------
  46. private static String BANNER_TYPE = "0";
  47. private static String INTERSTITIAL_TYPE = "1";
  48. private static String NATIVE_TYPE = "2";
  49. private static String SPLASH_TYPE = "5";
  50. private static String REWARDED_TYPE = "8";
  51. //----------------------
  52. private static boolean isVideoRewarded = false;
  53. private static boolean isVideoClose = false;
  54. public static AdManage getInstance() {
  55. if (null == mInstace) {
  56. mInstace = new AdManage();
  57. }
  58. return mInstace;
  59. }
  60. public void init(Context context, int wid) {
  61. this.mainActive = context;
  62. this.screenWidth = wid;
  63. //初始化广告 SDK.
  64. // Make sure to set the mediation provider value to "max" to ensure proper functionality
  65. AppLovinSdk.getInstance( context ).setMediationProvider( "max" );
  66. AppLovinSdk.initializeSdk( context, new AppLovinSdk.SdkInitializationListener() {
  67. @Override
  68. public void onSdkInitialized(final AppLovinSdkConfiguration configuration)
  69. {
  70. // AppLovin SDK is initialized, start loading ads
  71. Log.d(AdManage.getInstance().TAG, "onInitializationComplete: ");
  72. FAEvent("Mobi_10001"); //广告初始化事件
  73. }
  74. } );
  75. //亲子同乐计划
  76. // RequestConfiguration requestConfiguration = MobileAds.getRequestConfiguration()
  77. // .toBuilder()
  78. // .setMaxAdContentRating(MAX_AD_CONTENT_RATING_G)
  79. // .setTagForChildDirectedTreatment(TAG_FOR_CHILD_DIRECTED_TREATMENT_TRUE)
  80. // .build();
  81. // MobileAds.setRequestConfiguration(requestConfiguration);
  82. admobBanner.init(this.mainActive,this.screenWidth);
  83. admobInterstitial.init(this.mainActive);
  84. admobRewarded.init(this.mainActive);
  85. loadBannerAd();
  86. loadInterstitalAd();
  87. initVideoAd();
  88. //开启广告测试界面
  89. //AppLovinSdk.getInstance( this.mainActive ).showMediationDebugger();
  90. //this.GetGAID(this.mainActive);
  91. }
  92. public String getUnitID(String type){
  93. if(type.equals(BANNER_TYPE)){
  94. return AD_BANNER_UNIT_ID;
  95. }else if(type.equals(REWARDED_TYPE)){
  96. return AD_VIDEO_ID;
  97. }else if(type.equals(INTERSTITIAL_TYPE)){
  98. return AD_UNIT_ID;
  99. }else{
  100. return "";
  101. }
  102. }
  103. public void GetGAID(Context context)
  104. {
  105. String GAID="";
  106. Context mActivity = context;
  107. new Thread(new Runnable() {
  108. public void run() {
  109. try {
  110. AdvertisingIdClient.Info adInfo = AdvertisingIdClient
  111. .getAdvertisingIdInfo(mActivity);
  112. String advertisingId = adInfo.getId();
  113. Log.d(AdManage.getInstance().TAG, "advertisingId: "+advertisingId);
  114. // Log.i("ABC", "advertisingId" + advertisingId);
  115. // Log.i("ABC", "optOutEnabled" + optOutEnabled);
  116. } catch (Exception e) {
  117. e.printStackTrace();
  118. }
  119. }
  120. }).start();
  121. }
  122. //---------旧版本失败打点------------
  123. public static void failFAEvent(int errorCode,String type){
  124. String eventName = type;
  125. if(errorCode == 3){
  126. eventName = eventName +"_NoFill";
  127. }else{
  128. eventName = eventName +"_CallFailed";
  129. }
  130. FireBaseAnalyticsManager.getInstance().FAEvent(eventName);
  131. Log.d(AdManage.getInstance().TAG, "errcode = "+errorCode);
  132. Log.d(AdManage.getInstance().TAG, "eventName = "+eventName);
  133. }
  134. // //--------------------
  135. //--------------新版本失败打点-----------
  136. public static void FAEventFail(String eventId,String unitId,String adType,String errorCode,String errorMessage){
  137. String[] key = {"unit_id","ad_type","error_code","error_msg"};
  138. String[] value = {unitId,adType,errorCode,errorMessage};
  139. FireBaseAnalyticsManager.getInstance().FAEventWithParFAEventam(eventId,key,value);
  140. Log.d(AdManage.getInstance().TAG, "eventID : "+eventId+"call Fail");
  141. }
  142. //------------------
  143. //---旧版本打点---------
  144. public static void successFAEvent(String type){
  145. String eventName = type;
  146. eventName = type+"_Success";
  147. FireBaseAnalyticsManager.getInstance().FAEvent(eventName);
  148. Log.d(AdManage.getInstance().TAG, "eventName = "+eventName);
  149. }
  150. //----------新版本打点------------------
  151. public static void FAEventSuccess(String eventID,String unitId,String adType){
  152. String[] key = {"unit_id","ad_type"};
  153. String[] value = {unitId,adType};
  154. // AdManage.getInstance().FAEventWithParam(eventID,key,value);
  155. FireBaseAnalyticsManager.getInstance().FAEventWithParFAEventam(eventID,key,value);
  156. Log.d(AdManage.getInstance().TAG, "eventID : "+eventID+"call success "+unitId);
  157. }
  158. //---------------------------
  159. public void FAEvent(String eventName){
  160. FireBaseAnalyticsManager.getInstance().FAEvent(eventName);
  161. }
  162. public void FAEventWithParam(String eventName , String[] key , String[] value){
  163. FireBaseAnalyticsManager.getInstance().FAEventWithParFAEventam(eventName,key,value);
  164. }
  165. /*
  166. 加载google banner广告
  167. */
  168. public void loadBannerAd() {
  169. admobBanner.loadBannerAd();
  170. }
  171. /*
  172. 显示google banner广告
  173. */
  174. public static void showBannerAd(String pos){
  175. AdManage.getInstance().admobBanner.showBannerAd(pos);
  176. }
  177. /*
  178. 隐藏google banner广告
  179. */
  180. public static void hideBannerAd(){
  181. AdManage.getInstance().admobBanner.hideBannerAd();
  182. }
  183. public static void loadInterstitalAd(){
  184. AdManage.getInstance().admobInterstitial.loadInterstitalAd();
  185. }
  186. public static void showInterstitialAd() {
  187. AdManage.getInstance().admobInterstitial.showInterstitialAd();
  188. }
  189. public static void initVideoAd(){
  190. AdManage.getInstance().admobRewarded.initVideoAd();
  191. }
  192. //展示广告
  193. public static void showRewardVideoAd(){
  194. AdManage.getInstance().admobRewarded.showRewardVideoAd();
  195. }
  196. //用于cocos监听视频广告播放完成
  197. public static boolean videoRewardedListener(){
  198. return AdManage.getInstance().isVideoRewarded;
  199. }
  200. //用于cocos监听视频广告播放关闭
  201. public static boolean videoCloseListener(){
  202. return AdManage.getInstance().isVideoClose;
  203. }
  204. public boolean networkConnect() {
  205. return true;
  206. }
  207. }
AppActivity
  1. package org.cocos2dx.javascript;
  2. import org.cocos2dx.lib.Cocos2dxActivity;
  3. import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
  4. import android.app.Service;
  5. import android.os.Bundle;
  6. import android.content.Intent;
  7. import android.content.res.Configuration;
  8. import android.os.Vibrator;
  9. import android.util.DisplayMetrics;
  10. import android.util.Log;
  11. import android.view.Display;
  12. import android.view.WindowManager;
  13. public class AppActivity extends Cocos2dxActivity {
  14. private static AppActivity app = null;
  15. private int screenWidth;
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. // Workaround in
  20. // https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
  21. if (!isTaskRoot()) {
  22. // Android launched another instance of the root activity into an existing task
  23. // so just quietly finish and go away, dropping the user back into the activity
  24. // at the top of the stack (ie: the last state of this task)
  25. // Don't need to finish it again since it's finished in super.onCreate .
  26. return;
  27. }
  28. // DO OTHER INITIALIZATION BELOW
  29. SDKWrapper.getInstance().init(this);
  30. //屏幕常亮
  31. getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  32. //管理初始化
  33. initManager();
  34. }
  35. public void initManager(){
  36. app = this;
  37. //初始化firebase
  38. FireBaseAnalyticsManager.getInstance().init(this);
  39. //初始化app跳转
  40. JumpToApp.getInstance().init(this);
  41. getSize();
  42. //初始化广告管理
  43. AdManage.getInstance().init(this,this.screenWidth);
  44. }
  45. public void getSize() {
  46. // Step 2 - Determine the screen width (less decorations) to use for the ad width.
  47. Display display = getWindowManager().getDefaultDisplay();
  48. DisplayMetrics outMetrics = new DisplayMetrics();
  49. display.getMetrics(outMetrics);
  50. int widthPixels = outMetrics.widthPixels;
  51. int heightPixels = outMetrics.heightPixels;
  52. float density = outMetrics.density;
  53. int adWidth = (int) (widthPixels / density)/2;
  54. this.screenWidth = widthPixels;
  55. Log.d(AdManage.getInstance().TAG, "widthPixels: "+widthPixels);
  56. Log.d(AdManage.getInstance().TAG, "heightPixels: "+heightPixels);
  57. Log.d(AdManage.getInstance().TAG, "density: "+density);
  58. Log.d(AdManage.getInstance().TAG, "adWidth: "+adWidth);
  59. }
  60. //跳谷歌商城下的游戏页面=============================
  61. // public static void getAppByGooglePlay(String appPkg){
  62. // JumpToApp.getInstance().getAppByGooglePlay(appPkg);
  63. // }
  64. public static void vibrate(int time){
  65. // Log.d("vibrate", "shakeeeee: ");
  66. Vibrator vib=(Vibrator)app.getSystemService(Service.VIBRATOR_SERVICE);
  67. vib.vibrate(time);
  68. }
  69. @Override
  70. public Cocos2dxGLSurfaceView onCreateView() {
  71. Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
  72. // TestCpp should create stencil buffer
  73. glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
  74. SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView, this);
  75. return glSurfaceView;
  76. }
  77. @Override
  78. protected void onResume() {
  79. super.onResume();
  80. SDKWrapper.getInstance().onResume();
  81. }
  82. @Override
  83. protected void onPause() {
  84. super.onPause();
  85. SDKWrapper.getInstance().onPause();
  86. }
  87. @Override
  88. protected void onDestroy() {
  89. super.onDestroy();
  90. // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
  91. if (!isTaskRoot()) {
  92. return;
  93. }
  94. SDKWrapper.getInstance().onDestroy();
  95. }
  96. @Override
  97. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  98. super.onActivityResult(requestCode, resultCode, data);
  99. SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data);
  100. }
  101. @Override
  102. protected void onNewIntent(Intent intent) {
  103. super.onNewIntent(intent);
  104. SDKWrapper.getInstance().onNewIntent(intent);
  105. }
  106. @Override
  107. protected void onRestart() {
  108. super.onRestart();
  109. SDKWrapper.getInstance().onRestart();
  110. }
  111. @Override
  112. protected void onStop() {
  113. super.onStop();
  114. SDKWrapper.getInstance().onStop();
  115. }
  116. @Override
  117. public void onBackPressed() {
  118. SDKWrapper.getInstance().onBackPressed();
  119. super.onBackPressed();
  120. }
  121. @Override
  122. public void onConfigurationChanged(Configuration newConfig) {
  123. SDKWrapper.getInstance().onConfigurationChanged(newConfig);
  124. super.onConfigurationChanged(newConfig);
  125. }
  126. @Override
  127. protected void onRestoreInstanceState(Bundle savedInstanceState) {
  128. SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState);
  129. super.onRestoreInstanceState(savedInstanceState);
  130. }
  131. @Override
  132. protected void onSaveInstanceState(Bundle outState) {
  133. SDKWrapper.getInstance().onSaveInstanceState(outState);
  134. super.onSaveInstanceState(outState);
  135. }
  136. @Override
  137. protected void onStart() {
  138. SDKWrapper.getInstance().onStart();
  139. super.onStart();
  140. }
  141. }
JumpToApp.java
  1. package org.cocos2dx.javascript;
  2. import android.content.Context;
  3. import android.content.Intent;
  4. import android.content.pm.PackageInfo;
  5. import android.content.pm.PackageManager;
  6. import android.net.Uri;
  7. import android.text.TextUtils;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. //从商城获取app,或者打开本地
  11. public class JumpToApp {
  12. private static JumpToApp mInstace = null;
  13. //得到版本号
  14. public static String versionName;
  15. private Context mainActive = null;
  16. public static JumpToApp getInstance() {
  17. if (null == mInstace) {
  18. mInstace = new JumpToApp();
  19. }
  20. return mInstace;
  21. }
  22. public void init(Context context){
  23. mainActive = context;
  24. }
  25. //跳谷歌商城下的游戏页面=============================
  26. public static void getAppByGooglePlay(String appPkg){
  27. mInstace.appUpdate(JumpToApp.getInstance().mainActive,appPkg,"com.android.vending");
  28. }
  29. /**
  30. * 判断应用市场是否存在的方法
  31. * @param context
  32. * @param packageName
  33. * 主流应用商店对应的包名
  34. * com.android.vending -----Google Play
  35. * com.tencent.android.qqdownloader -----应用宝
  36. * com.qihoo.appstore -----360手机助手
  37. * com.baidu.appsearch -----百度手机助
  38. * com.xiaomi.market -----小米应用商店
  39. * com.wandoujia.phoenix2 -----豌豆荚
  40. * com.huawei.appmarket -----华为应用市场
  41. * com.taobao.appcenter -----淘宝手机助手
  42. * com.hiapk.marketpho -----安卓市场
  43. * cn.goapk.market -----安智市场
  44. * @return
  45. */
  46. public static boolean isAvilible(Context context, String packageName){
  47. // 获取packagemanager
  48. final PackageManager packageManager = context.getPackageManager();
  49. // 获取所有已安装程序的包信息
  50. List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
  51. // 用于存储所有已安装程序的包名
  52. List<String> pName = new ArrayList<String>();
  53. // 从pinfo中将包名字取出
  54. if (pinfo != null){
  55. for (int i = 0; i < pinfo.size(); i++){
  56. String pf = pinfo.get(i).packageName;
  57. pName.add(pf);
  58. }
  59. }
  60. // 判断pName中是否有目标程序的包名,有true,没有false
  61. return pName.contains(packageName);
  62. }
  63. //得到版本号
  64. public static void getVersionName(Context context){
  65. PackageManager manager = context.getPackageManager();
  66. try{
  67. PackageInfo info = manager.getPackageInfo(context.getPackageName(),0);
  68. versionName = info.versionName;
  69. }catch (PackageManager.NameNotFoundException e){
  70. e.printStackTrace();
  71. }
  72. }
  73. private void appUpdate(Context context,String appPkg, String marketPkg){
  74. //判断应用市场是否有包名
  75. if(isAvilible(context,appPkg)){
  76. Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPkg);
  77. context.startActivity(intent);
  78. }else if(isAvilible(context,marketPkg)){
  79. launchAppDetail(context,appPkg,marketPkg);
  80. }else { //没有,用浏览器打开地址进行下载
  81. //安装市场应用,那么根据后台返回的地址,用浏览器打开地址进行下载
  82. //Uri uri = Uri.parse(url);
  83. //Intent intent =new Intent(Intent.ACTION_VIEW, uri);
  84. //startActivity(intent);
  85. }
  86. //Toast.makeText(this,"立即更新",Toast.LENGTH_LONG).show();
  87. }
  88. /**
  89. * 启动到应用商店app详情界面
  90. * @param mContext
  91. * @param appPkg 目标App的包名
  92. * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面
  93. */
  94. //跳转更新
  95. public static void launchAppDetail(Context mContext, String appPkg, String marketPkg){
  96. try{
  97. if (TextUtils.isEmpty(appPkg)){
  98. return;
  99. }
  100. Uri uri = Uri.parse("market://details?id=" + appPkg);
  101. Intent intent =new Intent(Intent.ACTION_VIEW, uri);
  102. if (!TextUtils.isEmpty(marketPkg)){
  103. intent.setPackage(marketPkg);
  104. }
  105. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  106. mContext.startActivity(intent);
  107. }catch (Exception e){
  108. e.printStackTrace();
  109. }
  110. }
  111. }
FireBaseAnalyticsManager.java(打点统计)
  1. package org.cocos2dx.javascript;
  2. import android.content.Context;
  3. import android.os.Bundle;
  4. import android.util.Log;
  5. import com.google.firebase.analytics.FirebaseAnalytics;
  6. public class FireBaseAnalyticsManager {
  7. private static FireBaseAnalyticsManager mInstace = null;
  8. private FirebaseAnalytics mFirebaseAnalytics;
  9. private Context mainActive = null;
  10. private static final String Tag = "firebase";
  11. //private Map<String, Integer> eventCount =null;
  12. private static long beginTime ;
  13. private static long endTime ;
  14. public static FireBaseAnalyticsManager getInstance() {
  15. if (null == mInstace) {
  16. mInstace = new FireBaseAnalyticsManager();
  17. }
  18. return mInstace;
  19. }
  20. public void init(Context context){
  21. this.mainActive = context;
  22. mFirebaseAnalytics = FirebaseAnalytics.getInstance(context);
  23. }
  24. public static void FAEvent(String eventName){
  25. Log.d(Tag, "FAEvent"+eventName);
  26. Bundle params = new Bundle();
  27. // params.putString("value","nul");
  28. FireBaseAnalyticsManager.getInstance().mFirebaseAnalytics.logEvent(eventName, params);
  29. }
  30. public static void FAEventWithParFAEventam(String eventName , String[] key , String[] value){
  31. Log.d(Tag, "FAEventWithParFAEventam = "+eventName);
  32. int paramLength = key.length;
  33. Log.d(Tag, "paramLength"+paramLength);
  34. Bundle params = new Bundle();
  35. for(int i = 0;i<paramLength;i++){
  36. params.putString(key[i],value[i]);
  37. }
  38. FireBaseAnalyticsManager.getInstance().mFirebaseAnalytics.logEvent(eventName, params);
  39. }
  40. public static void FAEventWithParFAEventam(String eventName , String key , String value){
  41. Log.d(Tag, "FAEventWithParFAEventam = "+eventName);
  42. Bundle params = new Bundle();
  43. params.putString(key,value);
  44. FireBaseAnalyticsManager.getInstance().mFirebaseAnalytics.logEvent(eventName, params);
  45. }
  46. public static void FAEventBegin(String eventName){
  47. Log.d(Tag, "FAEventBegin = "+eventName);
  48. beginTime = System.currentTimeMillis();
  49. Bundle params = new Bundle();
  50. // params.putString("value","nul");
  51. FireBaseAnalyticsManager.getInstance().mFirebaseAnalytics.logEvent(eventName, params);
  52. }
  53. public static void FAEventEnd(String eventName){
  54. Log.d(Tag, "FAEventEnd = "+eventName);
  55. endTime = System.currentTimeMillis();
  56. double betweenTime = (endTime - beginTime)/1000.0;
  57. Bundle params = new Bundle();
  58. String.valueOf(betweenTime);
  59. params.putString("time", String.valueOf(betweenTime));
  60. FireBaseAnalyticsManager.getInstance().mFirebaseAnalytics.logEvent(eventName, params);
  61. Log.d(Tag, "eventTime = "+betweenTime);
  62. }
  63. }

cocos Android 互相调用

  1. import GameManager from "./GameManager";
  2. const { ccclass, property } = cc._decorator;
  3. @ccclass
  4. export default class PlatformApi {
  5. private static _instance: PlatformApi | null = null;
  6. public static get Instance() {
  7. if (!PlatformApi._instance) {
  8. window["PlatformApi"] = new PlatformApi();
  9. PlatformApi._instance = new PlatformApi()
  10. }
  11. // return PlatformApi._instance || (PlatformApi._instance = new PlatformApi());
  12. return PlatformApi._instance;
  13. }
  14. // 是否预加载激励广告
  15. public isLoadRewardAd: boolean = false;
  16. // 申请激励广告时间
  17. public showRewardVideoADTime: number = 0;
  18. public vibrateNum: number = 0;
  19. // 震动时间
  20. public VibrateTime: number = 0;
  21. // 是否ios平台
  22. public isPlatformIos() {
  23. let bIos = false;
  24. if (cc.sys.os == cc.sys.OS_IOS) {
  25. bIos = true;
  26. }
  27. return bIos;
  28. }
  29. /**
  30. *
  31. * @param dir bottom-lefte 左下 top 顶部居中 bottom 底部居中 top-lefte
  32. */
  33. public showBanner(dir: string) {
  34. cc.log("广告 showBanner");
  35. //eg
  36. //jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showBannerAd", "(Ljava/lang/String;)V", "bottom-left");
  37. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showBannerAd", "(Ljava/lang/String;)V", dir);
  38. }
  39. /**隐藏banner */
  40. public hideBanner() {
  41. cc.log("广告 hideBanner");
  42. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "hideBannerAd", "()V");
  43. }
  44. timeCount=120;
  45. //这个计时得在其他常驻节点上调用
  46. public UpdateInterstitialAd()
  47. {
  48. PlatformApi.Instance.timeCount++;
  49. //cc.log("timeCount "+PlatformApi.Instance.timeCount);
  50. }
  51. //展示插屏广告
  52. public showInterstitialAd(time=35) {
  53. cc.log("广告 插屏广告");
  54. //35秒内触发一次,不需要的话可以注释掉
  55. if (this.timeCount<time) {
  56. cc.log("广告 "+this.timeCount+" 短时间内重复触发");
  57. return;
  58. }
  59. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showInterstitialAd", "()V");
  60. }
  61. //展示激励广告
  62. public showRewardVideoAD() {
  63. // =================================
  64. let newTime = new Date().getTime();
  65. if ((newTime - PlatformApi.Instance.showRewardVideoADTime) < 5000) {
  66. cc.game.emit("_no_5_seconds_");
  67. // console.log("5秒内不能重复请求");
  68. return;
  69. }
  70. PlatformApi.Instance.showRewardVideoADTime = newTime;
  71. // =================================
  72. console.log("广告 激励广告");
  73. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AdManage", "showRewardVideoAd", "()V");
  74. }
  75. //
  76. public jumpToApp(appPkg: string) {
  77. if (cc.sys.os == cc.sys.OS_ANDROID) {
  78. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JumpToApp", "getAppByGooglePlay", "(Ljava/lang/String;)V", appPkg);
  79. } else if (cc.sys.os == cc.sys.OS_IOS) {
  80. jsb.reflection.callStaticMethod("CommonManager", "jumpToApp:", appPkg);
  81. }
  82. }
  83. // 打点
  84. public FAEvent(eventName: string) {
  85. cc.log("FAEvent 打点 = " + eventName);
  86. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/FireBaseAnalyticsManager", "FAEvent", "(Ljava/lang/String;)V", eventName);
  87. }
  88. public FAEventWithStringParam(eventName: string, key: string, value: string) {
  89. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/FireBaseAnalyticsManager", "FAEventWithParFAEventam", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", eventName, key, value);
  90. }
  91. public FAEventBegin(eventName: string) {
  92. cc.log("FAEventBegin 打点 = " + eventName);
  93. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/FireBaseAnalyticsManager", "FAEventBegin", "(Ljava/lang/String;)V", eventName);
  94. }
  95. public FAEventEnd(eventName: string) {
  96. cc.log("FAEventEnd 打点 = " + eventName);
  97. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/FireBaseAnalyticsManager", "FAEventEnd", "(Ljava/lang/String;)V", eventName);
  98. }
  99. // 回调=================================================================================
  100. // 安卓广告播放成功回调
  101. // 安卓广告播放成功回调
  102. public getVideoReward() {
  103. console.log("ADManage getVideoReward");
  104. cc.game.emit("_get_video_reward_");
  105. }
  106. // 广告回调失败是因为缺少库存,显示本地广告
  107. public showRewardVideoADFailByAndroid() {
  108. console.log("ADManage showRewardVideoADFailByAndroid");
  109. cc.game.emit("_show_reward_video_AD_fail_");
  110. }
  111. // 插屏广告关闭
  112. public getInterstitalHidden() {
  113. console.log("ADManage getInterstitalHidden");
  114. PlatformApi.Instance.timeCount=0;
  115. }
  116. //视频广告关闭
  117. public getVideoHidden() {
  118. console.log("ADManage getVideoHidden");
  119. PlatformApi.Instance.timeCount=0;
  120. }
  121. }

MAX  Mediation Debugger 使用说明(中介广告测试)

MAX Mediation Documentationhttps://dash.applovin.com/documentation/mediation/android/testing-networks/mediation-debugger AppLovinSdk.getInstance( this ).showMediationDebugger();

 

 

 

补充: 

升级cocos creator 为3.4.2 版本后发现AS目录结构不同了,在Project 模式下很多东西看不到了,所以选择Android模式更清晰点,

 

 升级gradle版本不在需要了。

安卓回掉cocos需要改成这样:

  1. CocosHelper.runOnGameThread(new Runnable() {
  2. @Override
  3. public void run() {
  4. CocosJavascriptJavaBridge.evalString("window.PlatformApi.getVideoReward()");
  5. Log.d(AdManage.getInstance().TAG, "call Rewarded");
  6. }
  7. });

 其他设置基本不变,根据提示修改就行

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/288924
推荐阅读
相关标签
  

闽ICP备14008679号