Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Gradle 從 Android Studio 匯出 jar 包並打包 assets

編輯:關於 Android 程式設計

最近在做一个供其他開發者使用的 SDK,因此必須輸出成 jar 包。Eclipse 有現成的「Export Java Project」功能,但 Android Studio 1.0 並未提供匯出 jar 的圖形介面,得靠 Gradle 自己寫任務。

步驟一:把模組設為 Library

在 module 的 build.gradle 中把 plugin 換成 library:

apply plugin: 'com.android.library'

這樣 build 之後,Android Studio 會在 module/build/intermediates/bundles/release/ 底下產生一支名為 classes.jar 的檔案(這個路徑在後續版本可能改變)。如果你的專案沒有用到 assets 等資源檔,直接把這支 jar 複製出去就能用了。

步驟二:把 jar 複製到 outputs 目錄

在 module 的 build.gradle 加上兩個任務:

task clearJar(type: Delete) {
    delete 'build/outputs/yourname.jar'
}

task makeJar(type: Copy) {
    from('build/intermediates/bundles/release/')
    into('build/outputs/')
    include('classes.jar')
    rename('classes.jar', 'yourname.jar')
}

makeJar.dependsOn(clearJar, build)

執行 gradle makeJar,就會在 build/outputs/ 下得到重新命名的 jar。先刪再複製,是為了避免舊檔殘留造成混淆。

步驟三:把 assets 一起打包進去

如果你的 SDK 需要附帶 assets 資源,這部分就稍微 tricky。這裡用一個有點非主流的做法:利用檔案依賴來打包。

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    provided files('src/main/assets')
    compile 'com.android.support:appcompat-v7:21.0.3'
}

關鍵是第三行。有兩個細節一定要注意:

  1. 需要在 assets 目錄下再建一層名為 assets 的子目錄,把要打包的檔案放在這個子目錄裡。
  2. 只有把 minifyEnabled 設為 true,assets 才會被打進 jar。原因沒有深究,反正做 SDK 本來就需要混淆。

附:ProGuard 設定參考

-libraryjars 'C:/Soft/android/adtsdk/platforms/android-19/android.jar'
-optimizations !code/simplification/arithmetic
-allowaccessmodification
-repackageclasses ''
-keepattributes *Annotation*
-dontpreverify
-dontwarn android.support.**

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider

-keep public class * extends android.view.View {
    public <init>(android.content.Context);
    public <init>(android.content.Context, android.util.AttributeSet);
    public <init>(android.content.Context, android.util.AttributeSet, int);
    public void set*(...);
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class * extends android.content.Context {
    public void *(android.view.View);
    public void *(android.view.MenuItem);
}

-keepclassmembers class * extends android.os.Parcelable {
    static ** CREATOR;
}

-keepclassmembers class **.R$* {
    public static <fields>;
}

-keepclassmembers class * {
    @android.webkit.JavascriptInterface <methods>;
}

這份設定主要在保留四大元件、自訂 View 的建構子、Parcelable 的 CREATOR、R 資源 id,以及加了 JavascriptInterface 註解的方法——這些都是被系統或反射呼叫、混淆後一定會出問題的部分。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved