標籤:
1.首先要使用 android sdk 提供的命令列工具處理已有的項目:
1 cd YourProjectDir2 android update project -p ./
2.上一步產生的 build.xml 中,會有一個對 custom_rules.xml 的引用,這個引用是可選的,沒有 custom_rules.xml 也不會影響編譯。但這個檔案正好是用來添加自訂編譯步驟的,要把 assets 資源添加到 jar 包中,就要建立這個檔案。在工程目錄下建立 custom_rules.xml 後,將以下內容添加到其中:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project name="custom_rules"> 3 <target name="-post-compile" if="${project.is.library}"> 4 <echo>Post Compile: add assests from ${asset.absolute.dir} to ${out.library.jar.file}</echo> 5 <jar destfile="${out.library.jar.file}" update="true"> 6 <zipfileset dir="${asset.absolute.dir}" prefix="assets" excludes="**/*.java ${android.package.excludes}"/> 7 </jar> 8 <echo>Post Compile: rename ${out.library.jar.file} to ${out.absolute.dir}/${standalone.jar.file}.jar</echo> 9 <delete file="${out.absolute.dir}/${standalone.jar.file}.jar" quiet="true"/>10 <rename src="${out.library.jar.file}" dest="${out.absolute.dir}/${standalone.jar.file}.jar"/>11 </target>12 </project>
其中standalone.jar.file 是定義在 local.properties 中的一個配置,表示你要產生的 jar 包的名字,當然你要寫在別的地方也不是不行。這段代碼做的事情就是在 compile 之後打一個 jar 包,把 assets 目錄中的檔案都壓縮到 jar 包的 assets 目錄中。然後將老版本的 jar 包刪除,並將剛產生的 jar 包改成我們要的名字。這樣打出來的 jar 包中會包含 assets 資源,apk 可以直接引用。為了不產生命名衝突,建議將 jar 包中的 assets 資源都放在一個以庫名稱命名的子目錄中,這樣 apk 中的資源就不會和庫裡的資源衝突了。
3.為了使用 eclipse 調試,我們還需要配置 eclipse 工程(手上的項目暫時還不方便切換 android studio,以後再說),實現調用 ant 自動編譯。首先你的 path 環境變數裡肯定要有 ant,windows 平台建議安裝 winant,mac 平台直接安裝 ant 就好。然後要配置 eclipse,達到每次修改原檔案都自動調用 ant 編譯的效果。具體方法是點擊 project->properties,選擇 builders,添加一個 builder,配置。然後把所有預設的 builder 都不選,只勾選新添加的 builder 即可。
注意,這種做法的前提是我的工程並不算大,自動編譯還能跟上修改,如果是大工程,還是不要自動編譯了。
如何發布帶靜態資源的庫——android 篇