16. 导入开源库 java.lang.NoClassDefFoundError: rx.plugins.RxJavaPlugins

来源:互联网 发布:淘宝产品推广方案 编辑:程序博客网 时间:2024/05/29 18:17

问题:

在自己项目中新导入一个开源库的Library,编译也成功运行在手机上开始出现异常,不过当时手机版本高于或等于21时却正常。报错信息:

java.lang.NoClassDefFoundError: rx.plugins.RxJavaPlugins

其实后面还有一些有关RXjava使用文件的提示显示,但是之前使用Rxjava都是正常的,而导入一个library后开始出错,错误肯定不在Rxjava上,所以真正错误是前面半句。

java.lang.NoClassDefFoundError


原因:

问题的原因是项目没有初始化 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
  • 2 在app文件夹下的 build.gradle文件中添加multidex 包依赖
    compile 'com.android.support:multidex:1.0.0'
  • 3 将项目自定义的Application继承MultiDexApplication,或者直接在自定义Application中重写方法,代码如下:
     @Override    protected void attachBaseContext(Context base) {        super.attachBaseContext(base);        MultiDex.install(this);    }

再次编译,问题即可解决。

此问题主要是由ART程序引发的版本问题,有关java.lang.NoClassDefFoundError的异常都可照此方法解决。



在 stackoverflow中找到相应的解答:
http://stackoverflow.com/questions/37619596/rxjava-noclassdeffounderror-rx-plugins-rxjavaplugins-on-api-16

希望对你们有帮助 :)

2 0
原创粉丝点击