facebook / react-native

A framework for building native applications using React
https://reactnative.dev
MIT License
119.26k stars 24.35k forks source link

[RN 0.68.2] [New Arch] [Android] App immediately crashes if New Arch enabled #34563

Closed alexkrav closed 1 year ago

alexkrav commented 2 years ago

Description

Error log for Release build:

2022-09-01 11:25:59.480 16179-16179/? E/IterableApi:  ❤️ Iterable SDK must be initialized with an API key and user email/userId before calling SDK methods
2022-09-01 11:25:59.538 16179-16179/? E/com.evernote.lifecycle: about to send foreground
2022-09-01 11:25:59.595 16179-16179/? E/unknown:ReactRootView: Unable to update root layout specs for ReactRootView: no rootViewTag set yet
2022-09-01 11:25:59.723 16179-16253/? E/log: error java.lang.ClassNotFoundException: com.facebook.react.fabric.StateWrapperImpl
2022-09-01 11:25:59.724 16179-16253/? E/SoLoader: couldn't find DSO to load: libfabricjni.so caused by: com.facebook.react.fabric.StateWrapperImpl result: 0

    --------- beginning of crash
2022-09-01 11:25:59.724 16179-16253/? E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
    Process: com.evernote.pre, PID: 16179
    java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libfabricjni.so caused by: com.facebook.react.fabric.StateWrapperImpl result: 0
        at com.facebook.soloader.SoLoader.g(SoLoader.java:50)
        at com.facebook.soloader.SoLoader.t(SoLoader.java:19)
        at com.facebook.soloader.SoLoader.s(SoLoader.java:1)
        at com.facebook.soloader.SoLoader.q(SoLoader.java:7)
        at com.facebook.soloader.SoLoader.p(SoLoader.java:1)
        at com.facebook.react.fabric.d.a(FabricSoLoader.java:4)
        at com.facebook.react.fabric.ComponentFactory.<clinit>(ComponentFactory.java:1)
        at d7.a$a$a.getJSIModuleProvider(MainApplicationReactNativeHost.java:1)
        at com.facebook.react.bridge.JSIModuleHolder.getJSIModule(JSIModuleHolder.java:5)
        at com.facebook.react.bridge.JSIModuleRegistry.getModule(JSIModuleRegistry.java:2)
        at com.facebook.react.bridge.CatalystInstanceImpl.getJSIModule(CatalystInstanceImpl.java:1)
        at com.facebook.react.uimanager.t0.h(UIManagerHelper.java:9)
        at com.facebook.react.uimanager.t0.g(UIManagerHelper.java:1)
        at com.facebook.react.r.q(ReactInstanceManager.java:4)
        at com.facebook.react.r.e0(ReactInstanceManager.java:17)
        at com.facebook.react.r.i(ReactInstanceManager.java:1)
        at com.facebook.react.r$f$b.run(ReactInstanceManager.java:1)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:1)
        at android.os.Looper.loopOnce(Looper.java:226)
        at android.os.Looper.loop(Looper.java:313)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:8)
        at java.lang.Thread.run(Thread.java:920)
     Caused by: java.lang.ClassNotFoundException: com.facebook.react.fabric.StateWrapperImpl
        at java.lang.Runtime.nativeLoad(Native Method)
        at java.lang.Runtime.nativeLoad(Runtime.java:1121)
        at java.lang.Runtime.load0(Runtime.java:927)
        at java.lang.System.load(System.java:1620)
        at com.facebook.soloader.SoLoader$a.a(SoLoader.java:19)
        at com.facebook.soloader.c.a(DirectApkSoSource.java:7)
        at com.facebook.soloader.SoLoader.g(SoLoader.java:10)
        at com.facebook.soloader.SoLoader.t(SoLoader.java:19) 
        at com.facebook.soloader.SoLoader.s(SoLoader.java:1) 
        at com.facebook.soloader.SoLoader.q(SoLoader.java:7) 
        at com.facebook.soloader.SoLoader.p(SoLoader.java:1) 
        at com.facebook.react.fabric.d.a(FabricSoLoader.java:4) 
        at com.facebook.react.fabric.ComponentFactory.<clinit>(ComponentFactory.java:1) 
        at d7.a$a$a.getJSIModuleProvider(MainApplicationReactNativeHost.java:1) 
        at com.facebook.react.bridge.JSIModuleHolder.getJSIModule(JSIModuleHolder.java:5) 
        at com.facebook.react.bridge.JSIModuleRegistry.getModule(JSIModuleRegistry.java:2) 
        at com.facebook.react.bridge.CatalystInstanceImpl.getJSIModule(CatalystInstanceImpl.java:1) 
        at com.facebook.react.uimanager.t0.h(UIManagerHelper.java:9) 
        at com.facebook.react.uimanager.t0.g(UIManagerHelper.java:1) 
        at com.facebook.react.r.q(ReactInstanceManager.java:4) 
        at com.facebook.react.r.e0(ReactInstanceManager.java:17) 
        at com.facebook.react.r.i(ReactInstanceManager.java:1) 
        at com.facebook.react.r$f$b.run(ReactInstanceManager.java:1) 
        at android.os.Handler.handleCallback(Handler.java:938) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:1) 
        at android.os.Looper.loopOnce(Looper.java:226) 
        at android.os.Looper.loop(Looper.java:313) 
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:8) 
        at java.lang.Thread.run(Thread.java:920) 
2022-09-01 11:26:01.352 1003-1038/? E/ANDR-PERF-UTIL: Failed to update node /proc/16179/sched_boost with value 0
2022-09-01 11:26:01.353 1003-1038/? E/ANDR-PERF-OPTSHANDLER: can't reset task 16179

Error log for Debug:

2022-09-01 12:58:45.630 23851-23851/com.evernote E/IterableApi:  ❤️ Iterable SDK must be initialized with an API key and user email/userId before calling SDK methods
2022-09-01 12:58:45.742 23851-23851/com.evernote E/com.evernote.lifecycle: about to send foreground
2022-09-01 12:58:45.784 23851-23851/com.evernote E/unknown:ReactRootView: Unable to update root layout specs for ReactRootView: no rootViewTag set yet
2022-09-01 12:58:47.896 23851-23988/com.evernote E/SoLoader: couldn't find DSO to load: libneutron_appmodules.so
        SoSource 0: com.facebook.soloader.DirectorySoSource[root = /data/app/~~6vb5Y33tOOGx14cJr59SdQ==/com.evernote-UNelvWwuvY8xAGtp6t4CMw==/lib/arm64 flags = 0]
        SoSource 1: com.facebook.soloader.DirectApkSoSource[root = (/data/app/~~6vb5Y33tOOGx14cJr59SdQ==/com.evernote-UNelvWwuvY8xAGtp6t4CMw==/base.apk!/lib/arm64-v8a, )]
        SoSource 2: com.facebook.soloader.DirectorySoSource[root = /system/lib64 flags = 2]
        SoSource 3: com.facebook.soloader.DirectorySoSource[root = /vendor/lib64 flags = 2]
        Native lib dir: /data/app/~~6vb5Y33tOOGx14cJr59SdQ==/com.evernote-UNelvWwuvY8xAGtp6t4CMw==/lib/arm64
     result: 0

    --------- beginning of crash
2022-09-01 12:58:47.897 23851-23988/com.evernote E/AndroidRuntime: FATAL EXCEPTION: create_react_context
    Process: com.evernote, PID: 23851
    java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libneutron_appmodules.so
        SoSource 0: com.facebook.soloader.DirectorySoSource[root = /data/app/~~6vb5Y33tOOGx14cJr59SdQ==/com.evernote-UNelvWwuvY8xAGtp6t4CMw==/lib/arm64 flags = 0]
        SoSource 1: com.facebook.soloader.DirectApkSoSource[root = (/data/app/~~6vb5Y33tOOGx14cJr59SdQ==/com.evernote-UNelvWwuvY8xAGtp6t4CMw==/base.apk!/lib/arm64-v8a, )]
        SoSource 2: com.facebook.soloader.DirectorySoSource[root = /system/lib64 flags = 2]
        SoSource 3: com.facebook.soloader.DirectorySoSource[root = /vendor/lib64 flags = 2]
        Native lib dir: /data/app/~~6vb5Y33tOOGx14cJr59SdQ==/com.evernote-UNelvWwuvY8xAGtp6t4CMw==/lib/arm64
     result: 0
        at com.facebook.soloader.SoLoader.doLoadLibraryBySoName(SoLoader.java:1127)
        at com.facebook.soloader.SoLoader.loadLibraryBySoNameImpl(SoLoader.java:943)
        at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:855)
        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:802)
        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:772)
        at com.evernote.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate.maybeLoadOtherSoLibraries(MainApplicationTurboModuleManagerDelegate.java:37)
        at com.facebook.react.turbomodule.core.TurboModuleManagerDelegate.<init>(TurboModuleManagerDelegate.java:29)
        at com.facebook.react.ReactPackageTurboModuleManagerDelegate.<init>(ReactPackageTurboModuleManagerDelegate.java:32)
        at com.evernote.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate.<init>(MainApplicationTurboModuleManagerDelegate.java:22)
        at com.evernote.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate$Builder.build(MainApplicationTurboModuleManagerDelegate.java:29)
        at com.evernote.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate$Builder.build(MainApplicationTurboModuleManagerDelegate.java:26)
        at com.facebook.react.ReactPackageTurboModuleManagerDelegate$Builder.build(ReactPackageTurboModuleManagerDelegate.java:146)
        at com.facebook.react.ReactInstanceManager.createReactContext(ReactInstanceManager.java:1369)
        at com.facebook.react.ReactInstanceManager.access$1200(ReactInstanceManager.java:138)
        at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:1111)
        at java.lang.Thread.run(Thread.java:920)

Version

0.68.2

Output of npx react-native info

√ ~/stash/neutron/>yarn react-native info yarn run v1.22.19 $ /Users/alexkrav/stash/neutron/node_modules/.bin/react-native info warn Package marked-terminal has been ignored because it contains invalid configuration. Reason: Package subpath './package.json' is not defined by "exports" in /Users/alexkrav/stash/neutron/node_modules/marked-terminal/package.json info Fetching system and libraries information... System: OS: macOS 12.2 CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz Memory: 226.80 MB / 16.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 16.15.0 - /var/folders/y6/tl91k7_15xb6fjsgr1817yw40000gp/T/yarn--1662056691464-0.747260586704783/node Yarn: 1.22.19 - /var/folders/y6/tl91k7_15xb6fjsgr1817yw40000gp/T/yarn--1662056691464-0.747260586704783/yarn npm: 8.5.5 - ~/.nvm/versions/node/v16.15√ ~/stash/neutron/>yarn react-native info yarn run v1.22.19 $ /Users/alexkrav/stash/neutron/node_modules/.bin/react-native info warn Package marked-terminal has been ignored because it contains invalid configuration. Reason: Package subpath './package.json' is not defined by "exports" in /Users/alexkrav/stash/neutron/node_modules/marked-terminal/package.json info Fetching system and libraries information... System: OS: macOS 12.2 CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz Memory: 226.80 MB / 16.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 16.15.0 - /var/folders/y6/tl91k7_15xb6fjsgr1817yw40000gp/T/yarn--1662056691464-0.747260586704783/node Yarn: 1.22.19 - /var/folders/y6/tl91k7_15xb6fjsgr1817yw40000gp/T/yarn--1662056691464-0.747260586704783/yarn npm: 8.5.5 - ~/.nvm/versions/node/v16.15.0/bin/npm Watchman: 2022.05.30.00 - /usr/local/bin/watchman Managers: CocoaPods: 1.11.3 - /Users/alexkrav/.rbenv/shims/pod SDKs: iOS SDK: Platforms: DriverKit 21.4, iOS 15.5, macOS 12.3, tvOS 15.4, watchOS 8.5 Android SDK: API Levels: 23, 28, 29, 30, 31 Build Tools: 27.0.3, 28.0.3, 29.0.2, 29.0.3, 30.0.2, 30.0.3, 31.0.0, 31.0.0 System Images: android-27 | Google Play Intel x86 Atom, android-28 | Google APIs Intel x86 Atom, android-29 | Google APIs Intel x86 Atom, android-29 | Google Play Intel x86 Atom, android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom, android-31 | Google APIs Intel x86 Atom_64 Android NDK: 21.4.7075529 IDEs: Android Studio: 4.1 AI-201.8743.12.41.7042882 Xcode: 13.4.1/13F100 - /usr/bin/xcodebuild Languages: Java: 11.0.15 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 17.0.2 => 17.0.2 react-native: 0.68.2 => 0.68.2 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found ✨ Done in 3.58s..0/bin/npm Watchman: 2022.05.30.00 - /usr/local/bin/watchman Managers: CocoaPods: 1.11.3 - /Users/alexkrav/.rbenv/shims/pod SDKs: iOS SDK: Platforms: DriverKit 21.4, iOS 15.5, macOS 12.3, tvOS 15.4, watchOS 8.5 Android SDK: API Levels: 23, 28, 29, 30, 31 Build Tools: 27.0.3, 28.0.3, 29.0.2, 29.0.3, 30.0.2, 30.0.3, 31.0.0, 31.0.0 System Images: android-27 | Google Play Intel x86 Atom, android-28 | Google APIs Intel x86 Atom, android-29 | Google APIs Intel x86 Atom, android-29 | Google Play Intel x86 Atom, android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom, android-31 | Google APIs Intel x86 Atom_64 Android NDK: 21.4.7075529 IDEs: Android Studio: 4.1 AI-201.8743.12.41.7042882 Xcode: 13.4.1/13F100 - /usr/bin/xcodebuild Languages: Java: 11.0.15 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 17.0.2 => 17.0.2 react-native: 0.68.2 => 0.68.2 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found ✨ Done in 3.58s.

Steps to reproduce

yarn install yarn run android

alexkrav commented 2 years ago

I've found the similar release crash log in #33065 reported by gabrieldonadel. That issue was closed but I could not find info how the crash was handled.

cortinico commented 2 years ago

If New Arch is enabled: app crashes immediately after start (short time splash screen visible) in both Debug and PreRelease builds. LOCAL_MODULE := neutron_appmodules

You most likely missed some of the configuration in your build.gradle. Can you share the file?

alexkrav commented 2 years ago

Thank you @cortinico Here is my app/build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply from: "$rootDir/gradle/version.gradle"

// apply plugin: "com.facebook.react"

import java.util.regex.Matcher
import java.util.regex.Pattern

import com.android.build.OutputFile
import com.android.build.gradle.internal.dsl.SigningConfig
import org.apache.tools.ant.taskdefs.condition.Os

/**
 * 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',
        // bundleCommand: "ram-bundle",
        enableHermes: true,  // clean and rebuild if changing
]

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
String ANDROID_SPLIT_ARCHES = System.getenv('ANDROID_SPLIT_ARCHES')
if (ANDROID_SPLIT_ARCHES == true) {
    enableSeparateBuildPerCPUArchitecture = true
}

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = true

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc-intl:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and mirrored here.  If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get('enableHermes', false)

/**
 * Architectures to build native code for in debug.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

//react {
//    reactRoot = rootProject.file("../node_modules/react-native/")
//    codegenDir = rootProject.file("../node_modules/react-native-codegen/")
//}

android {
    // ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    kotlinOptions {
        jvmTarget=11
    }

    aaptOptions {
        noCompress "html"
    }

    defaultConfig {
        applicationId 'com.evernote'
        minSdkVersion rootProject.ext.minSdkVersion
        compileSdkVersion rootProject.ext.compileSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        vectorDrawables.useSupportLibrary = true

        // abifilters cannot be active with split architectures
        if (enableSeparateBuildPerCPUArchitecture != true) {
            ndk {
                 abiFilters (*reactNativeArchitectures())
            }
        }

        renderscriptTargetApi 23
        renderscriptSupportModeEnabled true

        buildConfigField 'boolean', 'TEST_ENVIRONMENT', 'false'
        buildConfigField 'boolean', 'IS_NEW_ARCHITECTURE_ENABLED', isNewArchitectureEnabled().toString()

        if (isNewArchitectureEnabled()) {
            // We configure the NDK build only if you decide to opt-in for the New Architecture.
            externalNativeBuild {
                ndkBuild {
                    arguments "APP_PLATFORM=android-21",
                            "APP_STL=c++_shared",
                            "NDK_TOOLCHAIN_VERSION=clang",
                            "GENERATED_SRC_DIR=$buildDir/generated/source",
                            "PROJECT_BUILD_DIR=$buildDir",
                            "REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
                            "REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build"
                    cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
                    cppFlags "-std=c++17"
                    // Make sure this target name is the same you specify inside the
                    // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
                    targets "neutron_appmodules"
                    // Fix for windows limit on number of character in file paths and in command lines
                    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                        arguments "NDK_APP_SHORT_COMMANDS=true"
                    }
                }
            }
            if (!enableSeparateBuildPerCPUArchitecture) {
                ndk {
                    abiFilters (*reactNativeArchitectures())
                }
            }
        }

        println "Features: $rootProject.properties.features"
        rootProject.properties.features.each { featureName, enabled ->
            buildConfigField 'boolean', featureName, enabled ?: "false"
        }

        missingDimensionStrategy 'react-native-camera', 'general'
        // react-native-iap: we only use the Google Play flavor
        missingDimensionStrategy 'store', 'play'
        multiDexEnabled true

        manifestPlaceholders = [
                requestLegacyExternalStorage: "true",
                profileFromShell: "false",
                profileEnabled: "false"
        ]
    }

    if (isNewArchitectureEnabled()) {
        // We configure the NDK build only if you decide to opt-in for the New Architecture.
        externalNativeBuild {
            ndkBuild {
                path "$projectDir/src/main/jni/Android.mk"
            }
        }
        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        afterEvaluate {
            // If you wish to add a custom TurboModule or component locally,
            // you should uncomment this line.
            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
            android.applicationVariants.all { def variant ->
                def variantName = variant.name.capitalize()
                def preVariantBuildTask = tasks.findByName("pre${variantName}Build")
                println("=======> variantName="+variantName + " preVariantBuildTask.name=" + preVariantBuildTask.name);

                // Due to a bug inside AGP, we have to explicitly set a dependency
                // between configureNdkBuild* tasks and the preBuild tasks.
                // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
                if (variantName.endsWith("Debug")) {
                    preVariantBuildTask.dependsOn(packageReactNdkDebugLibs)
                    configureNdkBuildDebug.dependsOn(preVariantBuildTask)
                    reactNativeArchitectures().each { architecture ->
                        println("=======> architecture="+architecture );

                        tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
                            dependsOn(preVariantBuildTask.name)
                        }
                    }
                }
                if (variantName.endsWith("Release")) {
                    preVariantBuildTask.dependsOn(packageReactNdkReleaseLibs)
                    configureNdkBuildRelease.dependsOn(preVariantBuildTask)
                    reactNativeArchitectures().each { architecture ->
                        tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
                            dependsOn(preVariantBuildTask.name)
                        }
                    }
                }
            }
        }
    }

//    if (isNewArchitectureEnabled()) {
//        // We configure the NDK build only if you decide to opt-in for the New Architecture.
//        externalNativeBuild {
//            ndkBuild {
//                path "$projectDir/src/main/jni/Android.mk"
//            }
//        }
//        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
//        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
//            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
//            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
//            into("$buildDir/react-ndk/exported")
//        }
//        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
//            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
//            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
//            into("$buildDir/react-ndk/exported")
//        }
//        afterEvaluate {
//            // If you wish to add a custom TurboModule or component locally,
//            // you should uncomment this line.
//            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
//            preRegularDebugBuild.dependsOn(packageReactNdkDebugLibs)
//            preRegularReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
//
//            // Due to a bug inside AGP, we have to explicitly set a dependency
//            // between configureNdkBuild* tasks and the preBuild tasks.
//            // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
//            configureNdkBuildRelease.dependsOn(preRegularReleaseBuild)
//            configureNdkBuildDebug.dependsOn(preRegularDebugBuild)
//            reactNativeArchitectures().each { architecture ->
//                tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
//                    dependsOn("preRegularDebugBuild")
//                }
//                tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
//                    dependsOn("preRegularReleaseBuild")
//                }
//            }
//        }
//    }

    externalNativeBuild {
        cmake {
            version "3.10.2.4988404"
        }
    }

    flavorDimensions 'internalBuildType'

    signingConfigs {
        debug {
            println("Using debug keystore");
            def props = new Properties()
            file("../keystores/debug.keystore.properties").withInputStream { props.load(it) }

            keyAlias  props.getProperty("key.alias")
            storeFile  file(props.getProperty("key.store"))
            storePassword props.getProperty("key.store.password")
            keyPassword  props.getProperty("key.alias.password")
        }
    }

    buildTypes {
        release {
            buildConfigField 'String', 'CEC_HOST', '"https://cec.svc.evernote.com"'
            buildConfigField 'String', 'CEC_API_KEY', '"neutron"'
            buildConfigField 'String', 'CEC_SECRET', '"A75B7C90-AA91-4567-93A4-A843F776E411"'
            // enable code shrinking
            // minifyEnabled true
            // enable resource shrinking
            // shrinkResources true
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
        debug {
            buildConfigField 'String', 'CEC_HOST', '"https://cec.svc-stage.evernote.com"'
            buildConfigField 'String', 'CEC_API_KEY', '"neutron"'
            buildConfigField 'String', 'CEC_SECRET', '"9E31F2FC-ECD7-4809-8044-15B6363E6C25"'

            signingConfig signingConfigs.debug

            manifestPlaceholders = [
                    requestLegacyExternalStorage: "false",
                    profileFromShell: "true",
                    profileEnabled: "true"
            ]
        }
    }

    productFlavors {
        regular {
            ext {
                useProductionKeystore = true
            }
        }

        pre {
            applicationIdSuffix '.pre'
            ext {
                useProductionKeystore = false
            }
        }

        automation {
            applicationIdSuffix '.automation'
            buildConfigField 'boolean', 'TEST_ENVIRONMENT', 'true'
            ext {
                useProductionKeystore = false
            }

            manifestPlaceholders = [
                    requestLegacyExternalStorage: "true",
                    profileFromShell: "true",
                    profileEnabled: "true"
            ]
        }

        preview {
            buildConfigField 'boolean', 'PRIVATE_PREVIEW', 'true'
            ext {
                useProductionKeystore = false
            }
        }
    }

    android.productFlavors.each { flavor ->
        if (flavor.ext.useProductionKeystore) {
            println("Building flavor [${flavor.name}] - use production keystore if available")
            flavor.signingConfig = getSigninConfigProduction()
        } else {
            println("Building flavor [${flavor.name}] - use local keystore")
            flavor.signingConfig = getSigninConfigLocal()
        }
    }

    splits {
        abi {
            enable enableSeparateBuildPerCPUArchitecture
            reset()
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    // 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 =
                defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }
        }
    }

    packagingOptions {
        pickFirst '**/arm64-v8a/libc++_shared.so'
        pickFirst '**/arm64-v8a/libjsc.so'
        pickFirst '**/armeabi-v7a/libc++_shared.so'
        pickFirst '**/armeabi-v7a/libjsc.so'
        pickFirst '**/x86/libc++_shared.so'
        pickFirst '**/x86/libjsc.so'
        pickFirst '**/x86_64/libc++_shared.so'
        pickFirst '**/x86_64/libjsc.so'

        pickFirst '**/arm64-v8a/libneutron_appmodules.so'
        pickFirst '**/armeabi-v7a/libneutron_appmodules.so'
        pickFirst '**/x86/libneutron_appmodules.so'
        pickFirst '**/x86_64/libneutron_appmodules.so'

        pickFirst '**/app/**/arm64-v8a/lib*.so'
        pickFirst '**/app/**/armeabi-v7a/lib*.so'
        pickFirst '**/app/**/x86/lib*.so'
        pickFirst '**/app/**/x86_64/lib*.so'

        /**
         * https://developer.android.com/ndk/guides/abis.html?hl=en#sa
         * Note: Historically the NDK supported ARMv5 (armeabi), and 32-bit and 64-bit MIPS,
         * but support for these ABIs was removed in NDK r17.
         */
        exclude 'lib/armeabi/**'
        exclude 'lib/mips/**'
        exclude 'lib/mips64/**'

        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/gradle/incremental.annotation.processors'
        exclude 'META-INF/*.kotlin_module'
    }

    aaptOptions {
        noCompress 'png', 'js', 'json'
    }

    subprojects {
        beforeEvaluate { project ->
            if (project.hasProperty('android')) {
                android {
                    compileSdkVersion rootProject.ext.compileSdkVersion
                    buildToolsVersion rootProject.ext.buildToolsVersion
                }
            }
        }
    }
}

dependencies {
    // Make sure to put android-jsc at the top

    // implementation "org.webkit:android-jsc-intl:r245459"
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.facebook.react:react-native:+'  // From node_modules

    if (enableHermes) {
        def hermesPath = '../../node_modules/hermes-engine/android/';
        debugImplementation files(hermesPath + 'hermes-debug.aar')
        releaseImplementation files(hermesPath + 'hermes-release.aar')
    } else {
        implementation jscFlavor
    }
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0'
    implementation project(':react-native-iap')
    implementation 'com.facebook.fresco:animated-base-support:1.3.0'
    implementation 'com.facebook.fresco:fresco:2.0.0'
    implementation 'com.facebook.soloader:soloader:0.10.4'
    implementation 'com.facebook.fresco:animated-gif:2.6.0'
    implementation 'com.github.Iterable.iterable-android-sdk:iterableapi:3.2.7-beta1'
    implementation 'com.android.support:support-core-utils:28.0.0'
    implementation project(':react-native-image-crop-picker')
    implementation project(':@react-native-community_async-storage')
    implementation project(':react-native-webview')
    implementation project(':en-react-native-workers')
    implementation project(':appcenter-crashes')
    implementation project(':appcenter')
    implementation project(':react-native-sqlite-storage')
    implementation project(':react-native-trait-collection')
    implementation project(':en-react-native-local-notifications')
    implementation project(':react-native-remote-notifications')
    implementation project(':en-react-native-eventsource')
    implementation project(':react-native-device-performance')
    implementation project(':react-native-modal-translucent')
    implementation project(':react-native-web-server')
    implementation project(':en-react-native-resource-cache')
    implementation project(':external-intents')
    implementation project(':editor-helper')
    implementation project(':editor-webview')
    implementation project(':widget-helper')
    implementation project(':audio-manager')
    implementation project(':keyboard-helper')
    implementation project(':rn-fetch-blob')
    implementation project(':biometrics')
    implementation project(':secrets-handler')
    implementation project(':lifecycle')
    implementation project(':root-view-background')
    implementation project(':react-native-keychain')
    implementation project(':remote-config-manager')
    implementation project(':react-native-background-fetch')
    implementation project(':legacy-upgrade')
    implementation project(':log-helper')
    implementation project(':async-task-helper')
    implementation project(':en-search-engine-react-native')
    implementation project(':neutron-performance')
    implementation project(':react-native-background-timer')
    implementation project(':react-native-haptic-feedback')
    implementation project(':react-native-rate')
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "androidx.appcompat:appcompat:${rootProject.ext.androidXVersion}"
    implementation "androidx.recyclerview:recyclerview:1.1.0"
    // implementation "androidx.gridlayout:gridlayout:1.1.0"
    // For control over item selection of both touch and mouse driven selection
    implementation "androidx.recyclerview:recyclerview-selection:1.1.0-rc03"
    implementation 'com.google.firebase:firebase-messaging:19.0.0'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"  // From node_modules
    implementation("io.reactivex.rxjava2:rxkotlin:$kotlin_rx_version")
    implementation "com.evernote.native:commons:${rootProject.ext.internal_artifact_version}"
    implementation "com.evernote.conduit:cachediteminfo:${rootProject.ext.internal_artifact_version}"
    implementation "com.evernote.neutron:reactcommons:${rootProject.ext.internal_artifact_version}"
    implementation "com.evernote.native:resources:${rootProject.ext.internal_artifact_version}"
    implementation "com.evernote.performance:pieprofiler:${rootProject.ext.internal_artifact_version}"
    implementation "com.squareup.okhttp3:okhttp-urlconnection:4.4.1"

    // IAP dependencies
    implementation 'com.android.billingclient:billing:.4.0.0'

    // Kochava dependencies
    implementation 'com.google.android.gms:play-services-ads-identifier:15.0.1'
    implementation 'com.android.installreferrer:installreferrer:1.0'
    implementation 'com.google.android.instantapps:instantapps:1.1.0'

    // Flipper dependencies
    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }
}

if (isNewArchitectureEnabled()) {
    // If new architecture is enabled, we let you build RN from source
    // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
    // This will be applied to all the imported transtitive dependency.
    configurations.all {
        resolutionStrategy.dependencySubstitution {
            substitute(module("com.facebook.react:react-native"))
                    .using(project(":ReactAndroid")).because("On New Architecture we're building React Native from source")
        }
    }
}

// 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.implementation
    into 'libs'
}

task copyCE(type: Copy) {
    println('Delete web (CE/Ink/Skitch) files from prior build')
    delete 'src/main/assets/web'
    println('Copying web (CE/Ink/Skitch) files')
    from '../../assets/web'
    into 'src/main/assets/web'
    println('web (CE/Ink/Skitch) files copied')
}
preBuild.dependsOn(copyCE)
task copyFiles(type: Copy) {
    println('copy clipper files')
    from '../../assets/web/webclipper/clipper.js'
    into 'src/main/assets/'
}
preBuild.dependsOn(copyFiles)

preBuild.dependsOn(copyCE)

project.gradle.buildFinished {
    println('Deleting web (CE/Ink/Skitch) files after build')
    delete 'src/main/assets/web'
}

repositories {
    mavenCentral()
    maven {
        url 'https://maven.vpn.etonreve.com/repo'
    }
}

Boolean isDebug() {
    return getGradle().getStartParameter().getTaskRequests().toString().toLowerCase().contains("debug")
}

SigningConfig getSigninConfigProduction() {
    if (env.hasReleaseKeyStore) {
        println("Using build environment's release keystore:regularRelease")

        SigningConfig aConfig = new SigningConfig("regularRelease")
        aConfig.keyAlias = release_key_alias
        aConfig.storeFile = file("${System.env.ANDROID_HOME}/keys/AndroidKeystore.keystore")
        aConfig.storePassword = release_key_store_password
        aConfig.keyPassword = release_key_password

        return aConfig
    } else {
        return getSigninConfigLocal()
    }
}

SigningConfig getSigninConfigDebug() {
    println("Using debug keystore:debug")
    def props = new Properties()
    file("../keystores/debug.keystore.properties").withInputStream { props.load(it) }

    SigningConfig aConfig = new SigningConfig("debug")
    aConfig.keyAlias = props.getProperty("key.alias")
    aConfig.storeFile = file(props.getProperty("key.store"))
    aConfig.storePassword = props.getProperty("key.store.password")
    aConfig.keyPassword = props.getProperty("key.alias.password")

    return aConfig
}

SigningConfig getSigninConfigLocal() {
    if (!isDebug()) {
        println("Using local release keystore");
        def props = new Properties()
        file("../keystores/release.keystore.properties").withInputStream { props.load(it) }

        SigningConfig aConfig = new SigningConfig("preRelease")
        aConfig.keyAlias = props.getProperty("key.release.alias")
        aConfig.storeFile = file(props.getProperty("key.release.store"))
        aConfig.storePassword = props.getProperty("key.release.store.password")
        aConfig.keyPassword = props.getProperty("key.release.alias.password")

        return aConfig
    } else {
        return getSigninConfigDebug()
    }
}

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

apply from: file('../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle'); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'
cortinico commented 2 years ago

The build file is quite complicated, with a lot of commented code so is a bit hard to follow. It seems 'fine' at first. Can I ask you to share also your src/main/jni/Android.mk file?

Plus having a smaller reproducer here would really help 👍

alexkrav commented 2 years ago

@cortinico Here is my src/main/jni/Android.mk:

THIS_DIR := $(call my-dir)
include $(REACT_ANDROID_DIR)/Android-prebuilt.mk
# If you wish to add a custom TurboModule or Fabric component in your app you
# will have to include the following autogenerated makefile.
# include $(GENERATED_SRC_DIR)/codegen/jni/Android.mk
include $(CLEAR_VARS)
LOCAL_PATH := $(THIS_DIR)
# You can customize the name of your application .so file here.
LOCAL_MODULE := neutron_appmodules
LOCAL_C_INCLUDES := $(LOCAL_PATH)
LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp)
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)
# If you wish to add a custom TurboModule or Fabric component in your app you
# will have to uncomment those lines to include the generated source
# files from the codegen (placed in $(GENERATED_SRC_DIR)/codegen/jni)
#
# LOCAL_C_INCLUDES += $(GENERATED_SRC_DIR)/codegen/jni
# LOCAL_SRC_FILES += $(wildcard $(GENERATED_SRC_DIR)/codegen/jni/*.cpp)
# LOCAL_EXPORT_C_INCLUDES += $(GENERATED_SRC_DIR)/codegen/jni
# Here you should add any native library you wish to depend on.
LOCAL_SHARED_LIBRARIES := \
  libfabricjni \
  libfbjni \
  libfolly_futures \
  libfolly_json \
  libglog \
  libjsi \
  libreact_codegen_rncore \
  libreact_debug \
  libreact_nativemodule_core \
  libreact_render_componentregistry \
  libreact_render_core \
  libreact_render_debug \
  libreact_render_graphics \
  librrc_view \
  libruntimeexecutor \
  libturbomodulejsijni \
  libyoga
LOCAL_CFLAGS := -DLOG_TAG=\"ReactNative\" -fexceptions -frtti -std=c++17 -Wall
include $(BUILD_SHARED_LIBRARY)

As of reproducing, for debug build it is just:

>yarn install 
>yarn run android

For release:

>yarn install 
>cd android && ./gradlew app:assemblePreRelease --stacktrace && cd ..
>adb install ./android/app/build/outputs/apk/regular/debug/app-pre-release.apk
[then run on device]

thank you

cortinico commented 2 years ago

They look fine, modulo the usage of flavors which might be the culprit here. Are you able to replicate the crash on a newly created app?

alexkrav commented 2 years ago

@cortinico replicate the crash on a newly created app: What is the easiest/fastest way to do this?

cortinico commented 2 years ago

@cortinico replicate the crash on a newly created app: What is the easiest/fastest way to do this?

npx react-native init MyProject

to create a new project. Edit it to replicate the crash and put it on a git repo so we can take a look at it.

alexkrav commented 2 years ago

I'll try Just hoped that there is a way to skip a lot of manual changes.

maulik54e commented 2 years ago

i'm getting the same error on RN 0.70.1 Also noticed in your gradle file that you haven’t changed

dependencies {
-  implementation "com.facebook.react:react-native:+"  // From node_modules
+  implementation project(":ReactAndroid")  // From node_modules

it's mentioned in https://reactnative.dev/docs/new-architecture-app-intro not sure it's related or necessary though

Noble12345 commented 2 years ago

Hello dear

roots-ai commented 2 years ago

Facing the same issue. How did this get resolved? Though I have cmake instead of ndk in build.gradle.

github-actions[bot] commented 2 years ago
:warning: Missing Reproducible Example
:information_source: It looks like your issue is missing a reproducible example. Please provide a Snack or a repository that demonstrates the issue you are reporting in a minimal, complete, and reproducible manner.
zyzo commented 2 years ago

@roots-ai I got it working with cmake using this change

  android {
      defaultConfig  {
         [...]
         if (isNewArchitectureEnabled()) {
              // We configure the CMake build only if you decide to opt-in for the New Architecture.
              externalNativeBuild {
                  cmake {
                      arguments "-DPROJECT_BUILD_DIR=$buildDir",
                          "-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
                          "-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
                          "-DNODE_MODULES_DIR=$rootDir/../node_modules",
                          "-DANDROID_STL=c++_shared"
                  }
              }
              if (!enableSeparateBuildPerCPUArchitecture) {
                  ndk {
                      abiFilters (*reactNativeArchitectures())
                  }
              }
          }
     }

    if (isNewArchitectureEnabled()) {
        // We configure the NDK build only if you decide to opt-in for the New Architecture.
        externalNativeBuild {
            cmake {
                path "$projectDir/src/main/jni/CMakeLists.txt"
            }
        }
        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        afterEvaluate {
            // If you wish to add a custom TurboModule or component locally,
            // you should uncomment this line.
            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
            android.applicationVariants.all { def variant ->
                def variantName = variant.name.capitalize()
                def preVariantBuildTask = tasks.findByName("pre${variantName}Build")

                if (variantName.endsWith("Debug")) {
                    // Due to a bug inside AGP, we have to explicitly set a dependency
                      // between configureNdkBuild* tasks and the preBuild tasks.
                      // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
                      preVariantBuildTask.dependsOn(packageReactNdkDebugLibs)

                      configureCMakeDebug.dependsOn(preVariantBuildTask)
                      reactNativeArchitectures().each { architecture ->
                          tasks.findByName("configureCMakeDebug[${architecture}]")?.configure {
                              dependsOn(preVariantBuildTask.name)
                          }
                      }
                  }
                  if (variantName.endsWith("Release")) {
                      preVariantBuildTask.dependsOn(packageReactNdkReleaseLibs)
                      configureCMakeRelWithDebInfo.dependsOn(preVariantBuildTask)
                      reactNativeArchitectures().each { architecture ->
                          tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure {
                              dependsOn(preVariantBuildTask.name)
                          }
                      }
                  }
              }
          }
      }
  [...]
}
mMarcos208 commented 1 year ago

the same issue with react native 0.70.6 and cmake.

my android/app/build.gradle

buildscript {
    repositories {
        gradlePluginPortal()
    }
    dependencies {
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.10, 0.99.99]'
    }
}

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services'

import com.android.build.OutputFile
import org.apache.tools.ant.taskdefs.condition.Os

/**
 * 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. If none specified and
 *   // "index.android.js" exists, it will be used. Otherwise "index.js" is
 *   // default. Can be overridden with ENTRY_FILE environment variable.
 *   entryFile: "index.android.js",
 *
 *   // https://reactnative.dev/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // 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 = [
    enableHermes: true,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"
apply plugin: "com.bugsnag.android.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

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and that value will be read here. If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

/**
 * Architectures to build native code for.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.myapp"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 68
        versionName "4.1.1"
        multiDexEnabled true
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()

        if (isNewArchitectureEnabled()) {
            // We configure the CMake build only if you decide to opt-in for the New Architecture.
            externalNativeBuild {
                cmake {
                    arguments "-DPROJECT_BUILD_DIR=$buildDir",
                        "-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
                        "-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
                        "-DNODE_MODULES_DIR=$rootDir/../node_modules",
                        "-DANDROID_STL=c++_shared"
                }
            }
            if (!enableSeparateBuildPerCPUArchitecture) {
                ndk {
                    abiFilters (*reactNativeArchitectures())
                }
            }
        }
    }

    if (isNewArchitectureEnabled()) {
        // We configure the NDK build only if you decide to opt-in for the New Architecture.
        externalNativeBuild {
            cmake {
                path "$projectDir/src/main/jni/CMakeLists.txt"
            }
        }
        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        afterEvaluate {
            // If you wish to add a custom TurboModule or component locally,
            // you should uncomment this line.
            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
            preDebugBuild.dependsOn(packageReactNdkDebugLibs)
            preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)

            // Due to a bug inside AGP, we have to explicitly set a dependency
            // between configureCMakeDebug* tasks and the preBuild tasks.
            // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
            configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild)
            configureCMakeDebug.dependsOn(preDebugBuild)
            reactNativeArchitectures().each { architecture ->
                tasks.findByName("configureCMakeDebug[${architecture}]")?.configure {
                    dependsOn("preDebugBuild")
                }
                tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure {
                    dependsOn("preReleaseBuild")
                }
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        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
            }
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    packagingOptions {
        pickFirst '**/libhermes.so'
        pickFirst '**/libjsc.so'
        pickFirst "lib/armeabi-v7a/libc++_shared.so"
        pickFirst "lib/arm64-v8a/libc++_shared.so"
        pickFirst "lib/x86/libc++_shared.so"
        pickFirst "lib/x86_64/libc++_shared.so"
    }

    // 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:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
            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 =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation project(':react-native-config')

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        //noinspection GradleDynamicVersion
        implementation("com.facebook.react:hermes-engine:+") { // From node_modules
            exclude group:'com.facebook.fbjni'
        }
    } else {
        implementation jscFlavor
    }
}

if (isNewArchitectureEnabled()) {
    // If new architecture is enabled, we let you build RN from source
    // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
    // This will be applied to all the imported transtitive dependency.
    configurations.all {
        resolutionStrategy.dependencySubstitution {
            substitute(module("com.facebook.react:react-native"))
                    .using(project(":ReactAndroid"))
                    .because("On New Architecture we're building React Native from source")
            substitute(module("com.facebook.react:hermes-engine"))
                    .using(project(":ReactAndroid:hermes-engine"))
                    .because("On New Architecture we're building Hermes from source")
        }
    }
}

// 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.implementation
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

// https://github.com/oblador/react-native-vector-icons#android
project.ext.vectoricons = [
    iconFontNames: [ 'MaterialCommunityIcons.ttf' ]
]
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

// 2nd line, add a new apply:
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
bugsnag {
  uploadReactNativeMappings = true
}
cortinico commented 1 year ago

Hey all, Please share:

  1. The stacktrace of the crash
  2. A reproducer where we can see what's going on
github-actions[bot] commented 1 year ago

This issue is waiting for author's feedback since 24 days. Please provide the requested feedback or this will be closed in 7 days.

github-actions[bot] commented 1 year ago

This issue was closed because it has been stalled for 7 days with no activity.

github-actions[bot] commented 1 year ago

This issue was closed because the author hasn't provided the requested feedback after 7 days.