一、簡介
平時開發都知道,我們要上線的時候需要在Android studio打包apk文件,可是默認的打包名是app-release.apk或者app-debug.apk這樣的名字,太沒有辨識度了。
下面我們就來看看Android Studio是怎樣來批量修改生成的apk文件名的。
二、代碼實現
1、 Gradle 3.0以下版本
在app的build.gradle文件添加如下代碼:
android {
...
//簽名
signingConfigs{
release{
storeFile file("xxxx.jks")
storePassword '123456'
keyAlias 'xxxx'
keyPassword '123456'
}
debug{
storeFile file("xxxx.jks")
storePassword '123456'
keyAlias 'xxxx'
keyPassword '123456'
}
}
productFlavors{
google{
manifestPlaceholders = [
SDKChannel: "google",
app_name : "@string/app_name"
]
}
baidu{
manifestPlaceholders = [
SDKChannel: "baidu",
app_name : "@string/app_name"
]
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
//整理優化apk文件的工具,它能提高系統和應用的運行效率,更快的讀寫apk中的資源,降低內存的使用
zipAlignEnabled true
}
debug{
signingConfig signingConfigs.debug
}
}
applicationVariants.all { variant ->
variant.outputs.each{ output ->
if(output.outputFile != null
&& output.outputFile.name.endsWith('.apk')){
def apkFile = new File(
output.outputFile.getParent(),
"SDK_${variant.flavorName}_${variant.buildType.name}_V${variant.versionName}_${buildTime()}.apk"
)
output.outputFile = apkFile
}
}
}
}
def buildTime(){
def date = new Date()
def formattedDate = date.format('yyyyMMddHHmm')
return formattedDate
}
2、Gradle 3.0以上版本
android {
...
//簽名
signingConfigs{
release{
storeFile file("xxxx.jks")
storePassword '123456'
keyAlias 'xxxx'
keyPassword '123456'
}
debug{
storeFile file("xxxx.jks")
storePassword '123456'
keyAlias 'xxxx'
keyPassword '123456'
}
}
productFlavors{
google{
manifestPlaceholders = [
SDKChannel: "google",
app_name : "@string/app_name"
]
}
baidu{
manifestPlaceholders = [
SDKChannel: "baidu",
app_name : "@string/app_name"
]
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
//整理優化apk文件的工具,它能提高系統和應用的運行效率,更快的讀寫apk中的資源,降低內存的使用
zipAlignEnabled true
}
debug{
signingConfig signingConfigs.debug
}
}
android.applicationVariants.all {variant ->
variant.outputs.all {
//在這裏修改apk文件名,引號內的字符串都可以隨便定義
outputFileName = "SDK_${variant.flavorName}_${variant.buildType.name}_V${variant.versionName}_${buildTime()}.apk"
}
}
}
def buildTime(){
def date = new Date()
def formattedDate = date.format('yyyyMMddHHmm')
return formattedDate
}
說明:
-
{variant.flavorName}
:渠道名稱; -
{variant.buildType.name}
:release或debug包; -
{variant.versionName}
:版本名稱; -
{buildTime()}
:當前時間;
打包結果如下: