Eclipse正确导入第三方jar包

原文地址为: Eclipse正确导入第三方jar包

原文链接


感触

最近有个强烈的感触,写android代码不能一味都是自己开发,别人开源的优秀代码一定要多学习,多利用,这样既能提高开发进度,也能保证开发质量。github上比较优秀的android开源项目: https://github.com/Trinea/android-open-project


常见问题

android中导入第三方jar包经常会遇到class not found exception, error inflating class等问题,本质上都是第三方的jar包没有被真正的识别。在java开发过程中,习惯于通过add extennal archives来添加第三方的jar包,之所以不能在android项目中用同样的方法引入第三方jar包的原因,下面是来自eclipse j2ee开发者之一Russ Bateman的解释:

I'm an Eclipse JEE developer and have been in the habit for many years of adding third-party libraries via the "User Library" mechanism in Build Path. Of course, there are at least 3 ways to add a third-party library, the one I use is the most elegant, in my humble opinion.

This will not work, however, for Android, whose Dalvik "JVM" cannot handle an ordinary Java-compiled class, but must have it converted to a special format. This does not happen when you add a library in the way I'm wont to do it.

Instead, follow the (widely available) instructions for importing the third-party library, then adding it using Build Path (which makes it known to Eclipse for compilation purposes). Here is the step-by-step:

Download the library to your host development system.
Create a new folder, libs, in your Eclipse/Android project.
Right-click libs and choose Import -> General -> File System, then Next, Browse in the filesystem to find the library's parent directory (i.e.: where you downloaded it to).
Click OK, then click the directory name (not the checkbox) in the left pane, then check the relevant JAR in the right pane. This puts the library into your project (physically).
Right-click on your project, choose Build Path -> Configure Build Path, then click the Libraries tab, then Add JARs..., navigate to your new JAR in the libs directory and add it. (This, incidentally, is the moment at which your new JAR is converted for use on Android.)
What you've done here accomplishes two things:

Includes a Dalvik-converted JAR in your Android project.
Makes Java definitions available to Eclipse in order to find the third-party classes when developing (that is, compiling) your project's source code.


Android导入第三方jar包

Russ Bateman的意思是:android的dalvik虚拟机不能直接处理编译过的java .class文件,因此直接添加第三方jar包需要经过一定的处理才能被android项目正确识别并使用,以下是他提供的步骤:
  1. 下载第三方jar包
  2. 在android项目下创建一个libs目录(我也实测过:libs目录本身就是存在的,直接使用即可)
  3. 在eclipse中右键点击libs目录,依次选择import->General->File System,选中jar包所在的目录,然后选中这个目录下的jar包(ps:到这一步为止,你就成功地把jar包添加到项目中,但是还没有被android的虚拟机识别,因此如果这时你使用jar包中的类,编译都无法通过)
  4. 右键点击项目名,依次选择Build Path -> Configure Build Path,选择library选项卡。点击右边的add jars,选择libs目录下的jar包(ps:这一步就帮助android虚拟机来处理之前添加的jar包)



转载请注明本文地址: Eclipse正确导入第三方jar包

猜你喜欢

转载自blog.csdn.net/wangchaoqi1985/article/details/80910070