invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.7k stars 2.22k forks source link

[Android] Banner ads mediation not working (:fire:) #2377

Closed ghost closed 5 years ago

ghost commented 5 years ago

Issue (:fire:)

Similar to #1792 mediation not working with banners.

I've set up Admob with mediated Facebook ads. Testing with the Admob mediation test suite, I can get both ads. So I know my setup is OK.

Looking at the 5.5.4 branch it looks like the suggested fix is similar. That is from #1792

"Changing getContext() into getActivity() fixed the problem, however I do not know if this is the right solution. (I modified the following line)"

The official docs seem to point to using activity instead of context,

AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
// TODO: Add adView to your view hierarchy.

(Source: https://developers.google.com/admob/android/banner)

Looking at the firebase code I tried to figure out how to hotfix, but it seems similar to the interstitial fix:

  RNFirebaseAdmobInterstitial(final String adUnitString, final RNFirebaseAdMob adMobInstance) {
    adUnit = adUnitString;
    adMob = adMobInstance;

    Activity activity = adMob.getActivity();
    // Some ads won't work without passing activity, or the app will crash
    if (activity == null) {
      interstitialAd = new InterstitialAd(adMob.getContext());
    } else {
      interstitialAd = new InterstitialAd(activity);
    }

I was looking to try to do something like:

  public ReactViewGroup createViewInstance(ThemedReactContext themedReactContext, final RNFirebaseAdMob adMobInstance) {
    context = themedReactContext;
    viewGroup = new ReactViewGroup(themedReactContext);
    emitter = themedReactContext.getJSModule(RCTEventEmitter.class);

    adMob = adMobInstance;

    Activity activity = adMob.getActivity();
    AdView adView;

    // Some ads won't work without passing activity, or the app will crash
    if (activity == null) {
      adView = new AdView(context);
    } else {
      adView = new AdView(activity); // needed for mediation to work I think
    }

    viewGroup.addView(adView);
    setAdListener();

    return viewGroup;
  }

Project Files

Android

Click To Expand

#### Have you converted to AndroidX? No - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { buildToolsVersion = "28.0.3" minSdkVersion = 16 compileSdkVersion = 28 targetSdkVersion = 28 supportLibVersion = "28.0.0" } repositories { google() jcenter() } dependencies { classpath("com.android.tools.build:gradle:3.4.0") classpath("com.google.gms:google-services:4.2.0") // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() google() jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } } } ``` #### `android/app/build.gradle`: ```groovy apply plugin: "com.android.application" import com.android.build.OutputFile /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation * entryFile: "index.android.js", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ project.ext.react = [ entryFile: "index.js" ] apply from: "../../node_modules/react-native/react.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false repositories { maven { url "https://s3.amazonaws.com/moat-sdk-builds" } } android { compileSdkVersion rootProject.ext.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.smashappz.ezecalc" minSdkVersion rootProject.ext.minSdkVersion multiDexEnabled true targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1907080 versionName "19.07.08" } signingConfigs { release { if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) { storeFile file(MYAPP_UPLOAD_STORE_FILE) storePassword MYAPP_UPLOAD_STORE_PASSWORD keyAlias MYAPP_UPLOAD_KEY_ALIAS keyPassword MYAPP_UPLOAD_KEY_PASSWORD } } } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } buildTypes { release { minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" signingConfig signingConfigs.release } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = versionCodes.get(abi) * 1048576 + defaultConfig.versionCode } } } } dependencies { implementation project(':react-native-ad-consent') implementation project(':react-native-sentry') implementation project(':react-native-tts') implementation project(':react-native-splash-screen') implementation project(':react-native-secure-key-store') implementation project(':react-native-linear-gradient') implementation project(':react-native-gesture-handler') implementation project(':react-native-firebase') implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}" implementation 'com.android.support:multidex:1.0.3' implementation "com.facebook.react:react-native:+" // From node_modules implementation "com.google.android.gms:play-services-base:16.1.0" implementation "com.google.firebase:firebase-core:16.0.9" implementation "com.google.firebase:firebase-ads:17.2.1" implementation 'com.facebook.android:audience-network-sdk:5.4.0' implementation 'com.google.ads.mediation:facebook:5.4.0.0' implementation 'com.mopub.volley:mopub-volley:2.0.0' implementation('com.mopub:mopub-sdk:5.7.0@aar') { transitive = true } implementation 'com.google.ads.mediation:mopub:5.7.0.0' } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.compile into 'libs' } apply plugin: 'com.google.gms.google-services' ``` #### `android/settings.gradle`: ```groovy include ':react-native-tts' include ':react-native-firebase' project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android') include ':react-native-ad-consent' project(':react-native-ad-consent').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-ad-consent/android') include ':react-native-sentry' project(':react-native-sentry').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sentry/android') project(':react-native-tts').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-tts/android') include ':react-native-secure-key-store' project(':react-native-secure-key-store').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-secure-key-store/android') include ':react-native-linear-gradient' project(':react-native-linear-gradient').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-linear-gradient/android') include ':react-native-gesture-handler' project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android') include ':react-native-secure-key-store' project(':react-native-secure-key-store').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-secure-key-store/android') include ':react-native-splash-screen' project(':react-native-splash-screen').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-splash-screen/android') rootProject.name = 'ezecalc' include ':app' ``` #### `MainApplication.java`: ```java package com.smashappz.ezecalc; import android.app.Application; import com.facebook.react.ReactApplication; import de.bnass.RNAdConsent.RNAdConsentPackage; import io.sentry.RNSentryPackage; import net.no_mad.tts.TextToSpeechPackage; import org.devio.rn.splashscreen.SplashScreenReactPackage; import com.reactlibrary.securekeystore.RNSecureKeyStorePackage; import com.BV.LinearGradient.LinearGradientPackage; import com.swmansion.gesturehandler.react.RNGestureHandlerPackage; import io.invertase.firebase.RNFirebasePackage; import io.invertase.firebase.admob.RNFirebaseAdMobPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new RNAdConsentPackage(), new RNSentryPackage(), new TextToSpeechPackage(), new SplashScreenReactPackage(), new RNSecureKeyStorePackage(), new LinearGradientPackage(), new RNGestureHandlerPackage(), new RNFirebasePackage(), new RNFirebaseAdMobPackage() ); } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } } ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` info React Native Environment Info: System: OS: Linux 4.15 Linux Mint 18.3 (Sylvia) CPU: (8) x64 AMD FX(tm)-8320 Eight-Core Processor Memory: 2.32 GB / 11.63 GB Shell: 4.3.48 - /bin/bash Binaries: Node: 10.16.0 - ~/node/bin/node Yarn: 1.16.0 - ~/.yarn/bin/yarn npm: 6.10.1 - ~/node/bin/npm SDKs: Android SDK: API Levels: 23, 24, 27, 28, 29 Build Tools: 28.0.3, 29.0.0 System Images: android-28 | Google Play Intel x86 Atom npmPackages: react: 16.8.3 => 16.8.3 react-native: 0.59.9 => 0.59.9 npmGlobalPackages: react-native-cli: 2.0.1 ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [ ] Android - [ ] **iOS** but have not tested behavior on Android - [x] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `5.5.4` - **`Firebase` module(s) you're using that has the issue:** - `Admob` - **Are you using `TypeScript`?** - `N`


mikehardy commented 5 years ago

Could you propose this as a PR?

ghost commented 5 years ago

I made the following code change to a local version of the package, it compiled ok but failed on the bundling when running the app. This could work:

In RNFirebaseAdMobBanner:

import android.app.Activity;

...

public class RNFirebaseAdMobBanner extends SimpleViewManager<ReactViewGroup> {

...

  @Override
  public ReactViewGroup createViewInstance(ThemedReactContext themedReactContext) {
    context = themedReactContext;
    emitter = context.getJSModule(RCTEventEmitter.class);

    viewGroup = new ReactViewGroup(context);
    Activity activity = context.getCurrentActivity();
    viewGroup.addView(new AdView(activity == null ? context : activity));

    setAdListener();
    return viewGroup;
  }
stale[bot] commented 5 years ago

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

stale[bot] commented 5 years ago

Closing this issue after a prolonged period of inactivity. If this is still present in the latest release, please feel free to create a new issue with up-to-date information.

babyrusa commented 3 years ago

@smashappz Hi there, I'm trying to implement mediation as well. Have you tried this in IOS? I'm facing some compilation issue but I'm not sure if I have to install something else.

mikehardy commented 3 years ago

specify "some compilation issues" (that is: paste the text of the full compilation error message inside triple-backticks here) and perhaps someone has seen it before and can help

babyrusa commented 3 years ago

@mikehardy It's building for ios simulator but linking in object file built for ios for GoogleMobileAdsMediationFacebook I did some googling and know this is an issue with XCode 12. So I've been doing some tweaking with Podfile and build setting (now it's saying different things but I think after Googling more I will find a solution since it happened often with xcode 12)

mikehardy commented 3 years ago

You'll need to be very careful with your xcodebuild build settings - you can set them in a post_install in your Podfile, and the trick is to include or exclude the right architectures. Those errors are typical when you are dealing with old libraries built before .xcframeworks existed and they only had one arm64 library slot so they filled it with the release (ios) version of the library not the debug (ios simulator) version because it's more important. If you're on apple silicon you might try doing the whole thing using rosetta 2.