在Android Stdio中使用gradle打包相对来说比较容易,因为AS集成了gradle。
只需在根目录下调用gradle assembleDebug
命令就可在app\build\outputs\apk目录下看到新的apk文件。
1. 添加签名
签名配置,这个配置可以在buildTypes
中被引用
signingConfigs {
commonConfigs {
storeFile file('demo.keystore')
keyAlias 'demo'
keyPassword '123456'
storePassword '123456'
}
}
buildTypes {
release {
signingConfig signingConfigs.commonConfigs
}
}
在【BuildVariants】视图的【Build Variant】下选择【release】就可以成功加签。
2. 多环境打包
在AndroidManifest.xml
中定义一个${xx}
的变量
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="${app_label_name}"
android:theme="@style/AppTheme">
... ...
</application
在buildTypes
实现定义,既可以直接定义,也可以引用string
变量
buildTypes {
debug {
manifestPlaceholders=[app_label_name:"demo_debug"]
}
release {
manifestPlaceholders=[app_label_name:"@string/app_name"]
signingConfig signingConfigs.commonConfigs
}
}
resvalue
来修改字段的值,buildConfigField
会在BuildConfig
里面添加参数
buildTypes {
debug {
manifestPlaceholders=[app_label_name:"demo_debug"]
resValue 'string', 'welcome', 'hello world'
buildConfigField 'boolean', 'Log', 'true'
}
release {
manifestPlaceholders=[app_label_name:"@string/app_name"]
resValue 'string', 'welcome', 'welcome to app'
buildConfigField 'boolean', 'Log', 'false'
signingConfig signingConfigs.commonConfigs
}
}
其他配置
buildTypes {
release {
zipAlignEnabled true //是否支持zipAlign
shrinkResources true // 移除无用的resource文件
minifyEnabled true //是否启动混淆
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
3. 多渠道打包
在AndroidManifest.xml
文件中会有以下配置,来表明使用哪种渠道
<meta-data android:value="${channel_name}" android:name="UMENG_CHANNEL"/>
配置productFlavors
productFlavors {
TX {
manifestPlaceholders.put("channel_name", "Tencent")
}
WDJ {
manifestPlaceholders.put("channel_name", "WanDouJia")
}
}
打包时可以选择不同的环境和渠道,例如gradle assembleTXDebug
或者gradle assembleRelease
等。
4. 修改包名
定义一个时间方法,来设置包的名称
def releaseTime() {
return new Date().format("yyyyMMdd-HHmm")
}
在android下添加
android {
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith(".apk")) {
def fileName = outputFile.name.replace(".apk",
"-${releaseTime()}.apk");
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}