在android項目中添加第三方jar包雖然不是一個很複雜的問題,但是確實給很多開發人員帶來了不小的困擾。我自己就曾經碰到過calss not found exception、error inflating class等本質都是第三方jar包未被真正識別但報錯指向其他問題的狀況,碰到這類問題時我們很容易會被這些指向不夠準確的報錯誤導,因此正確地添加第三方jar包就顯得很重要。網上關於這個問題的資訊也比較雜亂,因此希望藉此文章對這個問題進行明確的解釋和解答。
首先要說的是為什麼會出現這個問題?我們在以往開發java程式的過程中都已經習慣於通過add external 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的dalvik虛擬機器不能直接處理編譯過的java .class檔案,因此直接添加第三方jar包需要經過一定的處理才能被android項目正常識別並使用。以下是他提供的步驟:
- 下載第三方jar包
- 在android項目下建立一個libs目錄(就我理解及測試的經驗,名稱並不固定,你完全可以取其他名稱)
- 在eclipse中右鍵點擊libs目錄,依次選擇Import -> General -> File System,選中jar包所在目錄, 然後選中這個目錄下的jar包
註:到這一步為止你就成功地把jar包添加到項目中(但是還沒有被android的虛擬機器識別,因此如果這時你使用jar包中的類,編譯都無法通過)
4.右鍵點擊項目名,依次選擇Build Path -> Configure Build Path,選擇library選項卡。點擊右邊的add jars,選擇libs目錄下的jar包
註:這一步就協助android虛擬機器來處理之前添加的jar包
理論上到這一步應該就可以正常使用了,但是如果到這一步你調試還會出錯的話可以嘗試右鍵點擊libs目錄,選擇build path –> configure as source folder ,基本上到這一步就可以正常使用第三方jar包,繼續你的android開發之旅了