天天看點

Android安卓開發-eclipse正确添加第三方jar包

本文轉載自http://www.cnblogs.com/developerY/archive/2013/04/18/3027997.html,在此對原作者表示感謝!

在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:

  1. Download the library to your host development system.
  2. Create a new folder, libs, in your Eclipse/Android project.
  3. 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).
  4. 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).
  5. 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:

  1. Includes a Dalvik-converted JAR in your Android project.
  2. 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項目正常識别并使用。以下是他提供的步驟:

  1. 下載下傳第三方jar包
  2. 在android項目下建立一個libs目錄(就我了解及測試的經驗,名稱并不固定,你完全可以取其他名稱)
  3. 在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開發之旅了

繼續閱讀