software-mansion / react-native-reanimated

React Native's Animated library reimplemented
https://docs.swmansion.com/react-native-reanimated/
MIT License
8.85k stars 1.29k forks source link

Unable to lunch Android app with react-native-reanimated@2.17.0 #4408

Closed josealanyamatrix closed 10 months ago

josealanyamatrix commented 1 year ago

Description

Even the app build is created successfully and the file ib/arm64-v8a/libreanimated.so exists, the error below comes out when the app is launched in the device.

ERROR  Error: Exception in HostFunction: java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "_ZdlPvSt11align_val_t" referenced by "/data/app/~~fynXGyPp6IZfvRTcI2VsZA==/app.examkl.debug-Cv4pN6CcTrP5D8avkDMOjg==/base.apk!/lib/arm64-v8a/libreanimated.so"..., js engine: hermes
 ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
      This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
 ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
      This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes

package.json:

{
  "react-native": "0.67.5",
  "react-native-reanimated": "2.17.0",
  "react-native-vision-camera": "2.15.4",
}

android/app/build.gradle

project.ext.react = [
    enableHermes: true, 
    bundleInDebug: true,
    bundleInQuality: true,
    devDisabledInQuality: true,
    bundleInStaging: true,
    devDisabledInStaging: true,
    deleteDebugFilesForVariant: {
        def v -> v.name.toLowerCase().contains('release') || v.name.toLowerCase().contains('quality') || v.name.toLowerCase().contains('staging')
    },
]

project.ext.reanimated = [
    buildFromSource: true
]
...
...

android {
 ...
 ...
...
   packagingOptions {
        pickFirst 'lib/arm64-v8a/libreanimated.so'
        ...
    }
}

Steps to reproduce

  1. Connect your Android device to computer
  2. $ yarn android:dev

Snack or a link to a repository

Working on that

Reanimated version

2.17.0

React Native version

0.67.5

Platforms

Android

JavaScript runtime

None

Workflow

None

Architecture

None

Build type

None

Device

None

Device model

Samsung Galaxy A52s 5G (Android 12)

Acknowledgements

Yes

github-actions[bot] commented 1 year ago

Hey! 👋

The issue doesn't seem to contain a minimal reproduction.

Could you provide a snack or a link to a GitHub repository under your username that reproduces the problem?

tomekzaw commented 1 year ago

Hey @josealanyamatrix, thanks for reporting this issue. Can you please check if Reanimated 2.15.0 (instead of 2.17.0) works for you?

josealanyamatrix commented 1 year ago

hello @tomekzaw Thanks for your answer. I did it and it does not work.

ERROR Error: Exception in HostFunction: java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "_ZdlPvSt11align_val_t" referenced by "/data/app/~~dTw0epXSMSFy8iaGIFMoPQ==/app.examkl.debug-N7qn7eCfvO8flyWVJ8-lZg==/base.apk!/lib/arm64-v8a/libreanimated.so"..., js engine: hermes ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes

Before my testing, I did the following steps:

  1. ./gradlew clean 2../gradlew cleanBuildCache
  2. $ rm -rf node_modules
  3. remove manually the android/.gradle
  4. yarn install
  5. yarn upgrade react-native-reanimated@2.15.0 (my current version is 2.9.1 which have a security vulnerability)
  6. yarn start --reset-cache
  7. yarn android:dev

This error persists event the android/app/build/intermediates/stripped_native_libs/debug/out/lib/arm64-v8a/libreanimated.so exists. do I need set up something else in the build.gradle?

Below you find my configuration with build.gradle

android/build.gradle

buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 23
        compileSdkVersion = 31
        targetSdkVersion = 31
        ndkVersion = "21.4.7075529"
        pdfViewerVersion = "3.2.0-beta.1"
        pdfViewerRepo = "com.github.mhiew"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.2.2")
        classpath("com.google.gms:google-services:4.3.10")
        classpath("com.google.firebase:firebase-crashlytics-gradle:2.9.2")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenCentral()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        maven { url 'https://www.jitpack.io' }
        maven {
                url "..."
              }
    }
}

android/app/build.gradle

apply plugin: "com.android.application"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: "com.google.gms.google-services"
apply plugin: "com.google.firebase.crashlytics"

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. 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,
    bundleInDebug: true,
    bundleInQuality: true,
    devDisabledInQuality: true,
    bundleInStaging: true,
    devDisabledInStaging: true,
    deleteDebugFilesForVariant: {
        def v -> v.name.toLowerCase().contains('release') || v.name.toLowerCase().contains('quality') || v.name.toLowerCase().contains('staging')
    },
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.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 = 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:+'

/**
 * 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 nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    dexOptions {
        javaMaxHeapSize "3g"
    }

    configurations.all {
        resolutionStrategy {
            force 'androidx.browser:browser:1.3.0'
        }
    }

    defaultConfig {
        applicationId "examkl.com"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 10
        versionName "0.1.0"
        resValue 'string', "CODE_PUSH_APK_BUILD_TIME", String.format("\"%d\"", System.currentTimeMillis())
        multiDexEnabled true
        resValue "string", "build_config_package", "examkl.com"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
           ...
        }
        release {
           ...
        }
    }
    buildTypes {
        debug {
            applicationIdSuffix ".debug"
            resValue "string", "app_name", "examkl"
            signingConfig signingConfigs.debug
            // versionNameSuffix 'Deb'
            if (nativeArchitectures) {
                ndk {
                    abiFilters nativeArchitectures.split(',')
                }
            }
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.release
            shrinkResources enableProguardInReleaseBuilds
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
             resValue "string", "app_name", "examkl"
        }
        quality{
            signingConfig signingConfigs.debug
            applicationIdSuffix ".quality"
            resValue "string", "app_name", "examkl-QA"
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            matchingFallbacks = ['debug']
        }
        staging{
            signingConfig signingConfigs.release
            applicationIdSuffix ".staging"
            resValue "string", "app_name", "examkl-UAT"
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            matchingFallbacks = ['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:
            // 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)
            }

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

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar", "*.aar"])
    implementation files('libs/mcpsdk.aar')
    implementation files('libs/WafMobileSdk.aar')
    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    implementation ("androidx.appcompat:appcompat:1.3.1") {
      version {
        strictly '1.3.1'
      }
    }
    implementation project(':react-native-screens')
    implementation project(':react-native-reanimated')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-safe-area-context')
    implementation project(':react-native-aes-crypto')
    implementation project(':lottie-react-native')
    //Zensdesk SKD
    implementation group: 'com.zendesk', name: 'chat', version: '3.3.6'
    implementation group: 'com.zendesk', name: 'messaging', version: '5.2.5'
    implementation group: 'com.zendesk', name: 'chat-providers', version: '3.3.6'
    implementation group: 'com.zendesk', name: 'answerbot', version: '3.1.0'
    implementation group: 'com.zendesk', name: 'support', version: '5.1.1'
    //WAF SDK
    implementation 'com.google.code.gson:gson:2.8.9'
    implementation 'org.bouncycastle:bcprov-jdk15on:1.69'
    //Push notifications
    implementation "com.google.firebase:firebase-core:15.0.2"
    implementation "com.google.firebase:firebase-messaging:15.0.2"
    implementation platform('com.google.firebase:firebase-bom:30.4.1')
    //Google Analytics y Crashlytics
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-crashlytics'

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

    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) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        qualityImplementation files(hermesPath + "hermes-debug.aar")
        stagingImplementation files(hermesPath + "hermes-release.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

// 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)
josealanyamatrix commented 1 year ago

hello @tomekzaw

I upgraded to RN 0.70.6 and app is working properly using debug build type. However, we are facing another error when we use another build type so, is this related to reanimated?

Crash

Process: examkl.com.quality, PID: 16055
java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes-executor-release.so
    SoSource 0: com.facebook.soloader.ApkSoSource[root = /data/data/examkl.com.quality/lib-main flags = 1]
    SoSource 1: com.facebook.soloader.DirectorySoSource[root = /data/app/~~RQeXkiGhMgy_2diUu6NEUA==/examkl.com.quality-SLGtgv9diOXKxRCZKW0L5A==/lib/arm64 flags = 0]
    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/~~RQeXkiGhMgy_2diUu6NEUA==/examkl.com.quality-SLGtgv9diOXKxRCZKW0L5A==/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.facebook.hermes.reactexecutor.HermesExecutor.loadLibrary(HermesExecutor.java:30)
    at com.facebook.hermes.reactexecutor.HermesExecutor.<clinit>(HermesExecutor.java:19)
    at com.facebook.react.ReactInstanceManagerBuilder.getDefaultJSExecutorFactory(ReactInstanceManagerBuilder.java:393)
    at com.facebook.react.ReactInstanceManagerBuilder.build(ReactInstanceManagerBuilder.java:343)
    at com.facebook.react.ReactNativeHost.createReactInstanceManager(ReactNativeHost.java:96)
    at com.facebook.react.ReactNativeHost.getReactInstanceManager(ReactNativeHost.java:42)
    at examkl.com.MainApplication.onCreate(MainApplication.java:62)
    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1211)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:7482)
    at android.app.ActivityThread.access$1600(ActivityThread.java:310)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2283)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at android.app.ActivityThread.main(ActivityThread.java:8641)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1133)

package.json

 {
  "react-native": "0.70.6",
  "react-native-reanimated": "2.10.0",
  "react-native-vision-camera": "2.15.4",
  "react-native-gesture-handler": "2.9.0"
}

android/app/build.gradle

apply plugin: "com.android.application"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

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
    bundleInDebug: true,
    bundleInQuality: true,
    devDisabledInQuality: true,
    bundleInStaging: true,
    devDisabledInStaging: true,
    deleteDebugFilesForVariant: {
        def v -> v.name.toLowerCase().contains('release') || v.name.toLowerCase().contains('quality') || v.name.toLowerCase().contains('staging')
    },
]

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 = 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:+'

/**
 * 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 in debug.
 */
def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")

/**
 * 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

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

    defaultConfig {
        applicationId "examkl.com"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        resValue "string", "build_config_package", "examkl.com"

        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 {
           ...
        }
        release {
           ...
        }
    }
    buildTypes {
        debug {
            applicationIdSuffix ".debug"
            resValue "string", "app_name", "examkl-DEV"
            signingConfig signingConfigs.debug
            // versionNameSuffix 'Deb'
            if (nativeArchitectures) {
                ndk {
                    abiFilters nativeArchitectures.split(',')
                }
            }
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            shrinkResources enableProguardInReleaseBuilds
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            resValue "string", "app_name", "examkl"
        }
        quality{
            signingConfig signingConfigs.debug
            applicationIdSuffix ".quality"
            resValue "string", "app_name", "examkl-QA"
            // minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            matchingFallbacks = ['debug']
        }
        staging{
            signingConfig signingConfigs.release
            applicationIdSuffix ".staging"
            resValue "string", "app_name", "examkl-UAT"
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            matchingFallbacks = ['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:
            // 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 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-crashlytics'

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    // compile project(':react-native-view-pdf')

    //Zensdesk SKD
    implementation group: 'com.zendesk', name: 'chat', version: '3.3.6'
    implementation group: 'com.zendesk', name: 'messaging', version: '5.2.5'
    implementation group: 'com.zendesk', name: 'chat-providers', version: '3.3.6'
    implementation group: 'com.zendesk', name: 'answerbot', version: '3.1.0'
    implementation group: 'com.zendesk', name: 'support', version: '5.1.1'
    //

    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"
}

android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "31.0.0"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
        pdfViewerVersion = "3.2.0-beta.1"
        pdfViewerRepo = "com.github.mhiew"

        if (System.properties['os.arch'] == "aarch64") {
            // For M1 Users we need to use the NDK 24 which added support for aarch64
            ndkVersion = "24.0.8215888"
        } else {
            // Otherwise we default to the side-by-side NDK version from AGP.
            ndkVersion = "21.4.7075529"
        }
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:7.2.1")
        classpath("com.facebook.react:react-native-gradle-plugin")
        classpath("de.undercouch:gradle-download-task:5.0.1")
        classpath 'com.google.gms:google-services:4.3.15'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.9.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
        mavenCentral {
            // We don't want to fetch react-native from Maven Central as there are
            // older versions over there.
            content {
                excludeGroup "com.facebook.react"
            }
        }
        google()
        maven { url 'https://www.jitpack.io' }
    }
}

proguard-rules.pro

# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# Add any project specific keep options here:
-keep class examkl.com.BuildConfig { *; }
tlands commented 1 year ago

It's my understanding that you need to add the following to your proguard-rules.pro file

-keep class com.swmansion.reanimated.** { *; }

Latropos commented 10 months ago

@josealanyamatrix How is it going? Did you fix your problem changing proguard-rules.pro? Can we close this issue?

Aakash359 commented 9 months ago

Same issues facing on my device also with react native reanimated libaray pls someone help me to resolve this issues my react native version is react-native@0.73.0 and my react-native reanimated libaray version is "react-native-reanimated": "^2.9.1", i had tried most of the suitable version of reanimated libaray but none of them are working 😳😭😭😭😭 ERROR Error: Exception in HostFunction: java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "_ZN8facebook5react19ReadableNativeArrayC1EN5folly7dynamicE" referenced by "/data/app/~~pnEU736DIyw-xQPMEOGxBA==/com.service_app-nwbqGYGw96xYqyXKukd0Ig==/lib/arm64/libreanimated.so"..., js engine: hermes LOG Running "Service_App" with {"rootTag":11}

SaatwikRishi commented 9 months ago

https://docs.swmansion.com/react-native-reanimated/docs/guides/compatibility/