1. 程式人生 > >導入開源庫 java.lang.NoClassDefFoundError: rx.plugins.RxJavaPlugins

導入開源庫 java.lang.NoClassDefFoundError: rx.plugins.RxJavaPlugins

ima eve -s plugin ons 文件 cat art inf

問題:

在自己項目中新導入一個開源庫的Library,編譯也成功運行在手機上開始出現異常,不過當時手機版本高於或等於21時卻正常。報錯信息:

java.lang.NoClassDefFoundError: rx.plugins.RxJavaPlugins
  • 1

其實後面還有一些有關RXjava使用文件的提示顯示,但是之前使用Rxjava都是正常的,而導入一個library後開始出錯,錯誤肯定不在Rxjava上,所以真正錯誤是前面半句。

java.lang.NoClassDefFoundError
  • 1


原因:

問題的原因是項目沒有初始化 MultiDex 選項!

官方文檔中有說明:Multidex support for Android 5.0 and higher

Android 5.0 and higher uses a runtime called ART which natively supports loading multiple dex files from application APK files. ART performs pre-compilation at application install time which scans for classes(..N).dex files and compiles them into a single .oat file for execution by the Android device. For more information on the Android 5.0 runtime, see Introducing ART. This is the reason why your app is working fine on API level 21.

總體而言,Android 5.0及以上版本有使用一個名為ART的耗時操作,它支持從應用程序的APK文件中加載多個dex文件。 ART在應用程序安裝時執行預編譯,掃描類(.. N).dex文件,並將其編譯為單個.oat文件,以供Android設備執行。

以上也就是應用程序可以API級別21上正常工作的原因。




解決方法:

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can use the multidex support library, which becomes part of the primary DEX file of your app and then manages access to the additional DEX files and the code they contain.

以上是對於Android版本在5.0之前也就是低於5.0時的解決辦法(3個步驟,缺一不可):
技術分享圖片

  • 1 在app文件夾下的 build.gradle文件指定位置添加:
multiDexEnabled true
  • 1
  • 2 在app文件夾下的 build.gradle文件中添加multidex 包依賴
    compile ‘com.android.support:multidex:1.0.0‘
  • 1
  • 3 將項目自定義的Application繼承MultiDexApplication,或者直接在自定義Application中重寫方法,代碼如下:
     @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
  • 1
  • 2
  • 3
  • 4
  • 5

再次編譯,問題即可解決。

此問題主要是由ART程序引發的版本問題,有關java.lang.NoClassDefFoundError的異常都可照此方法解決。

導入開源庫 java.lang.NoClassDefFoundError: rx.plugins.RxJavaPlugins