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

Gradle for Android 學習筆記(一):從 gradlew 到變體與簽名配置

編輯:關於 Android 程式設計

Gradle 是 Android 的官方建置系統,概念不算難,但設定檔的寫法相當自由,入門時容易迷失在各種寫法裡。這篇從最基礎的命令與任務概念開始,一路談到 buildTypes、SourceSets、多渠道打包與簽名配置。

零、一個基本觀念

每一個 build.gradle 檔代表一個 project,而一個 project 會有多個 tasks。Android 專案裡的 task 大致分為 Android tasks、build tasks、build setup tasks、help tasks、install tasks 等幾類。

一、常用 gradlew 命令

gradlew -help              // 查看說明
gradlew tasks              // 列出 root project 的 task
gradlew tasks --all        // 列出所有詳細 task
gradlew -v                 // 查看 Gradle 版本等資訊
gradlew assembleDebug      // 產出 debug 版 APK,位於 app/build/outputs/apk
gradlew aD                 // 縮寫亦可
gradlew :app:assembleDebug // 指定 module 執行

記住縮寫規則能省下不少打字時間:assembleDebug 可縮成 assDeb 或 aD,Gradle 會自動匹配唯一對應的任務名稱。

二、Android Tasks 速覽

Base tasks 只定義不實作:assemble、clean、check、build。

Android tasks 則給出實際行為:

  • assemble:為每個 build type 各產出一個 APK,預設依賴 assembleDebug 與 assembleRelease。
  • clean:清除所有編譯產物。
  • check:執行 Lint 檢查,若發現問題可中斷編譯。
  • build:等同 assemble 加 check 一起跑。

三、在根專案統一管理多個 Module

如果工程裡有多個 Android 模組,可以把共同設定抽到根專案的 allprojects:

allprojects {
    apply plugin: 'com.android.application'
    android {
        compileSdkVersion 24
        buildToolsVersion "24.0.0"
    }
}

這種寫法要求所有 Module 都是 Android app,彈性較差。更好的方式是在根專案宣告 ext {}:

ext {
    compileSdkVersion = 24
    buildToolsVersion = "24.0.0"
}

各模組再引用:

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
}

這樣升級 SDK 版本時只需要改一處,而且不會硬性綁定 plugin 型別。

四、自定義 task

ext {
    local = "hello local"
}

task print << {
    println local
    println ok   // task 也能讀取 gradle.properties 中的設定
}

在 gradle.properties 中:

ok = 'hello property'

五、使用 Native Library

Android 預設支援 native library,只要在 Module 中建立 jniLibs 目錄:

android {
    sourceSets.main {
        jniLibs.srcDir 'src/main/libs'
    }
}

若要用到 .aar 檔:

repositories {
    flatDir {
        dirs 'aars'
    }
}
dependencies {
    compile(name: 'libraryname', ext: 'aar')
}

六、Dependency 的幾種配置

  • compile:預設方式,絕大多數依賴都用它。
  • apk:只加入打包,不參與編譯,作為純 jar 依賴使用。
  • provided:編譯時可用,但不會被打進 APK,作為純 jar 依賴使用。這兩種方式在把 library 專案當 jar 用時,容易引發錯誤,需留意。
  • testCompile:單元測試的依賴。
  • androidTestCompile:儀器測試的依賴。
  • debugCompile:僅 debug 版本的依賴。
  • releaseProvided:release 版本不打包。

理解這些配置的核心,是弄清楚「編譯期可見性」與「執行期打包」是兩個獨立維度。

七、自定義 buildTypes

模組預設會有 release 與 debug 兩種 build type(debug 是隱式的)。除了覆寫它們的屬性,也可以自行新增:

android {
    buildTypes {
        release { ... }
        debug { ... }

        my {
            initWith buildTypes.debug   // 複製 debug 的所有屬性
            applicationIdSuffix ".my"
            versionNameSuffix "-my"
            buildConfigField "boolean", "LOG_DEBUG", "true"
        }
    }
}

initWith 表示完整繼承另一個 build type 的設定,之後再覆寫差異部分。

applicationIdSuffix ".my" 的效果是讓 applicationId 加上後綴:

debug 的 applicationId: com.example
my 的 applicationId:    com.example.my

因為 applicationId 不同,這兩個 APK 可以在同一台裝置上共存,常用來區分免費版與付費版,或測試版與正式版。

buildConfigField 則是往 BuildConfig 類別裡塞自訂常數:

buildConfigField "boolean", "LOG_DEBUG", "true"
buildConfigField "String", "API_URL", "\"https://staging.example.com/api\""

使用時:

if (BuildConfig.LOG_DEBUG) {
    Log.e(TAG, message);
}

把這類判斷封裝成日誌工具類,就能依 debug/release 統一控制日誌開關,不必到處寫 if。

八、SourceSets:為不同 build type 準備不同程式碼

當你新增了一個名為 staging 的 build type,並希望它使用自己的程式碼與資源時,需要手動建立一個與 build type 同名的目錄:

在 staging 目錄下放自己的資源,會在合併時覆蓋 main 中的同名資源。例如 main 的 string.xml:

<resources>
    <string name="app_name">Application</string>
    <string name="hello">hello</string>
</resources>

staging 目錄的 string.xml:

<resources>
    <string name="app_name">Application Staging</string>
</resources>

合併後的結果是:

<resources>
    <string name="app_name">Application Staging</string>
    <string name="hello">hello</string>
</resources>

也就是說,staging 有定義的項目被覆寫,沒定義的則沿用 main。若 staging 目錄完全沒有該資源,就直接使用 main 的版本。這個「逐項覆蓋」的機制,是 SourceSets 最實用的地方。

九、Multiflavtor variants:多渠道打包

最簡單的場景是 App 要上架多個應用市場:

android {
    productFlavors {
        xiaomi {
            applicationId "com.example.application"
        }
        "360" {
            applicationId "com.example.application"
        }
    }
}

若需求變成「同時要分免費版與付費版」,就要引入維度的概念:

android {
    flavorDimensions 'price', 'store'

    productFlavors {
        xiaomi { flavorDimension "store" }
        "360"  { flavorDimension "store" }
        free   { flavorDimension "price" }
        price  { flavorDimension "price" }
    }
}

flavorDimensions 是一個陣列,宣告了 price 與 store 兩個維度,每個 flavor 都要指派到其中一個維度。上表共兩個維度(price 的 [free, price] 與 store 的 [xiaomi, 360]),再加上 buildType 的 [debug, release],會組合出:

xiaomi-free-debug    xiaomi-free-release
360-free-debug       360-free-release
xiaomi-price-debug   xiaomi-price-release
360-price-debug      360-price-release

組合數量會隨維度相乘快速膨脹,這也是下一節 variant filter 存在的原因。

十、Variant filters:過濾不需要的變體

這段設定放在 android { } 內外皆可:

android.variantFilter { variant ->
    if (!variant.buildType.name.equals('debug')) {
        variant.getFlavors().each() { flavor ->
            if (!flavor.name.equals('xiaomi')) {
                variant.setIgnore(true);
            }
        }
    }
}

效果就是過濾掉一部分變體,不再為它們建置:

十一、Signing configurations:簽名配置

最基本的形式,一般只需要配置一個 release:

android {
    signingConfigs {
        release {
            storeFile file("release.keystore")
            storePassword "storepassword"
            keyAlias "keyAlias"
            keyPassword "keyPassword"
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }
}

這樣打 release 包時就會自動帶上簽名。

若希望所有版本都簽名,可以在 defaultConfig 中指定:

defaultConfig {
    signingConfig signingConfigs.release
}

若只想針對某個渠道簽名:

android {
    productFlavors {
        xiaomi {
            signingConfig signingConfigs.release
        }
    }
}

更進階的情況是每個渠道使用各自的簽名檔:

android {
    signingConfigs {
        release { ... }
        xiaomi  { ... }
        baidu   { ... }
    }
    buildTypes {
        release {
            productFlavors.xiaomi.signingConfig signingConfigs.xiaomi
            productFlavors.baidu.signingConfig signingConfigs.baidu
        }
    }
}

實務提醒:正式專案裡不要把 keystore 密碼以明文寫在 build.gradle 並提交進版控,應改用 gradle.properties(不進版控)、環境變數或 CI 的 secret 機制注入,這點在下一篇會再談。

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