Android 使用 Gradle 打包 - 簽名配置
序言
最近正好在專案裡用到了 Gradle 打包的配置,順便總結一下。
一般的 apk 打包型別分為 debug 和 release:debug 開啟日誌,不進行混淆,用於測試;release 關閉日誌,開啟混淆,用於正式釋出。在 Android Studio 裡面,生成的 debug 包使用了 AS 預設的簽名,而 release 包沒有簽名。如果我們需要定製,比如生成 debug 和 release 包後,自動進行簽名,就需要在 gradle 配置檔案裡面加上 apk 簽名的配置。
android { ...... // 配置 release 的簽名信息 signingConfigs { release { storeFile storePassword keyAlias keyPassword } } // 讀取簽名配置 getSigningProperties() buildTypes { // debug 和 release 使用同樣的簽名 debug { signingConfig signingConfigs.release } release { minifyEnabled true shrinkResources true zipAlignEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.release // 修改生成的 apk 檔名,輸出 apk 名稱:MyApp_v1.0.0_2017-11-10_debug.apk applicationVariants.all { variant -> def suffix if (variant.buildType.name == 'release') { suffix = 'release' } else { suffix = 'debug' } variant.outputs.each { output -> def outputFile = output.outputFile if (outputFile != null && outputFile.name.endsWith('.apk')) { def fileName = "MyApp_v${defaultConfig.versionName}_${releaseTime()}_${suffix}.apk" output.outputFile = new File(outputFile.parent, fileName) } } } } } ...... } // 讀取簽名配置 def getSigningProperties() { def propFile = file('../signing.properties') if (propFile.exists() && propFile.canRead()) { def props = new Properties() props.load(new FileInputStream(propFile)) if (props.containsKey('STORE_FILE') && props.containsKey('STORE_PASSWORD') && props.containsKey('KEY_ALIAS') && props.containsKey('KEY_PASSWORD')) { android.signingConfigs.release.storeFile = file('../' + props['STORE_FILE']) android.signingConfigs.release.storePassword = props['STORE_PASSWORD'] android.signingConfigs.release.keyAlias = props['KEY_ALIAS'] android.signingConfigs.release.keyPassword = props['KEY_PASSWORD'] } else { println 'signing.properties are found but some entries are missed!' android.buildTypes.release.signingConfig = null } } else { println 'signing.properties are not found!' android.buildTypes.release.signingConfig = null } } // 定義打包時間 static def releaseTime() { return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC")) }
其中,簽名配置檔案(signing.properties)和簽名檔案(.jks)存放在專案工程的根目錄,它們不需要加入版本控制。這是 signing.properties,可以根據需要自己修改。
STORE_FILE=RichiePersonal.jks STORE_PASSWORD=ExamplePassword KEY_ALIAS=ExampleKeyAlias KEY_PASSWORD=ExampleKeyPassword
最後,我們通過 Gradle 命令就可以完成打包工作,生成的 apk 檔名像是這樣:MyApp_v1.0.0_2017-11-10_debug.apk。
命令格式:gradlew project:task
gradlew app:assembleDebug
或者
gradlew app:assembleRelease
Gradle 構建的功能還是蠻強大的,從簽名的配置就能看出,此外還有自定義構建型別、多工程全域性配置、多渠道打包等待,這裡就不多介紹了,感興趣的朋友請自行了解。
【附錄】

資料圖
需要資料的朋友可以加入Android架構交流QQ群聊:513088520
點選連結加入群聊【Android移動架構總群】: 加入群聊
獲取免費學習視訊,學習大綱另外還有像高階UI、效能優化、架構師課程、NDK、混合式開發(ReactNative+Weex)等Android高階開發資料免費分享。