React Native Android java.lang.ClassNotFoundException:找不到类

Posted

技术标签:

【中文标题】React Native Android java.lang.ClassNotFoundException:找不到类【英文标题】:React Native Android java.lang.ClassNotFoundException: Didn't find class 【发布时间】:2021-11-02 16:04:37 【问题描述】:

我正在为 androidios 构建一个 react native 的应用程序。它始终在两个平台上都有效,但突然之间我在启动(android)时崩溃并出现以下 logcat 错误:

09-05 02:07:55.872  8212  8212 E AndroidRuntime: java.lang.RuntimeException: Unable to instantiate application androidx.multidex.MultiDexApplication: java.lang.ClassNotFoundException: Didn't find class "androidx.multidex.MultiDexApplication" on path: DexPathList[[],nativeLibraryDirectories=[/data/app/~~Pm6z6nHOPLkadQA1g99noQ==/com.vinity-ituqFvK7uqibzRT_uF-6lg==/lib/arm64, /data/app/~~Pm6z6nHOPLkadQA1g99noQ==/com.vinity-ituqFvK7uqibzRT_uF-6lg==/base.apk!/lib/arm64-v8a, /system/lib64]]
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.app.LoadedApk.makeApplication(LoadedApk.java:1332)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.app.ActivityThread.handleMakeApplication(ActivityThread.java:7475)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:7446)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.app.ActivityThread.access$1500(ActivityThread.java:301)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2148)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:106)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:246)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:8512)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
09-05 02:07:55.872  8212  8212 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.multidex.MultiDexApplication" on path: DexPathList[[],nativeLibraryDirectories=[/data/app/~~Pm6z6nHOPLkadQA1g99noQ==/com.vinity-ituqFvK7uqibzRT_uF-6lg==/lib/arm64, /data/app/~~Pm6z6nHOPLkadQA1g99noQ==/com.vinity-ituqFvK7uqibzRT_uF-6lg==/base.apk!/lib/arm64-v8a, /system/lib64]]
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:207)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.app.Instrumentation.newApplication(Instrumentation.java:1158)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    at android.app.LoadedApk.makeApplication(LoadedApk.java:1324)
09-05 02:07:55.872  8212  8212 E AndroidRuntime:    ... 10 more

任何帮助将不胜感激!顺便说一句,IOS 运行良好。

更新

Android 清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  package="com.vinity">

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.android.vending.BILLING" />

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_icon"
      android:resource="@drawable/ic_stat_onesignal_default" />
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="rn-push-notification-channel-id-4-300" />
        
    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme"
      android:hasCode="false"
      android:usesCleartextTraffic="true" tools:targetApi="28"> 
      <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
      android:value="true"/>
     <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
      android:resource="@color/white"/>
      <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
        android:launchMode="singleTask"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
    </application>
</manifest>

这是我的 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.google.gms.google-services'
apply plugin: "com.android.application"

import com.android.build.OutputFile

ext 
    googlePlayServicesVersion = "+" // default: "+"
    firebaseMessagingVersion = "21.1.0" // default: "21.1.0"



/**
 * 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: false,  // 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

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

android 
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions 
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    

    defaultConfig 
        applicationId "com.vinity"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 5
        versionName "0.1.2"
        missingDimensionStrategy 'store', 'play'

    
    splits 
        abi 
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        
    
    signingConfigs 
        debug 
            storeFile file(MYAPP_UPLOAD_STORE_FILE)
            storePassword MYAPP_UPLOAD_STORE_PASSWORD
            keyAlias MYAPP_UPLOAD_KEY_ALIAS
            keyPassword MYAPP_UPLOAD_KEY_PASSWORD
        
        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"
        
    

    // 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 platform('com.google.firebase:firebase-bom:28.4.0')
    implementation 'com.google.firebase:firebase-analytics'
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    implementation "androidx.multidex:multidex:2.0.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) 
        def hermesPath = "../../node_modules/hermes-engine/android/"
        debugImplementation files(hermesPath + "hermes-debug.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.compile
    into 'libs'


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

如 android 开发者文档 https://developer.android.com/studio/build/multidex 中所述,不需要手动启用 multidex,因为它默认为 minsdkversion 21 启用。

我尝试在 buildconfig 中添加 multiDexEnabled true,但没有成功。

【问题讨论】:

你能分享你的 app/build.gradle 和 Manifest 吗? ***.com/questions/54349646/… 试试这个解决方案 在主帖中添加了 build.gradle 和 android manifest。 你是如何构建你的应用程序的? 我正在使用 react-native run-android 并且还在 android studio 中测试了该建筑。 (使用 macbook pro) 【参考方案1】:

在 Android Manifest 中更改 name 属性。

这样

<application
      android:name="android.support.multidex.MultiDexApplication"

尝试使用 npx react-native run-android 构建应用

【讨论】:

java.lang.RuntimeException:无法实例化应用程序 android.support.multidex.MultiDexApplication:java.lang.ClassNotFoundException:在路径上找不到类“android.support.multidex.MultiDexApplication”:DexPathList [[],nativeLibraryDirectories=[/data/app/~~4SZeaKomryJo7hcc_sdS1w==/com.vinity-xhaNVaQYufZ7DTuC1FiT4Q==/lib/arm64, /data/app/~~4SZeaKomryJo7hcc_sdS1w==/com.vinity-xhaNVaQYufZ7DTuC1FiT4Q==/base .apk!/lib/arm64-v8a, /system/lib64]] 尝试使用 npx react-native run-android 构建应用 撤消清单并尝试使用上述命令构建 尝试给出与原始问题相同的错误

以上是关于React Native Android java.lang.ClassNotFoundException:找不到类的主要内容,如果未能解决你的问题,请参考以下文章

react-native android genymotion错误java.util.concurrent.ExecutionException:

如何使用控制台在 React Native Android 中调试 Java 代码

react-native修改android包名

react-native修改android包名

React Native Android java.lang.ClassNotFoundException:找不到类

Realm React-Native:从 JS(反应本机代码)和 android(java)访问相同的领域