有没有办法在使用Android Studio构建期间访问当前的应用程序版本?我正在尝试将构建版本字符串包含在apk的文件名中。
我正在使用以下内容根据每晚构建的日期更改文件名,但是希望为包含版本名称的发布版本提供另一种风格。
productFlavors {
nightly {
signingConfig signingConfigs.debug
applicationVariants.all { variant ->
variant.outputs.each { output ->
def file = output.outputFile
def date = new Date();
def formattedDate = date.format('yyyy-MM-dd')
output.outputFile = new File(
file.parent,
"App-nightly-" + formattedDate + ".apk"
)
}
}
}
}
答案 0 :(得分:2)
通过https://stackoverflow.com/a/19406109/1139908,如果您没有在Gradle中定义版本号,可以使用Manifest Parser访问它们:
import com.android.builder.core.DefaultManifestParser // At the top of build.gradle
def manifestParser = new com.android.builder.core.DefaultManifestParser()
String versionName = manifestParser.getVersionName(android.sourceSets.main.manifest.srcFile)
另外值得注意的是,使用applicationVariants.all
(https://stackoverflow.com/a/22126638/1139908)可能会对您的默认调试版本产生意外行为。在我的最终解决方案中,我的buildTypes
部分如下所示:
buildTypes {
applicationVariants.all { variant ->
variant.outputs.each { output ->
def String fileName;
if(variant.name == android.buildTypes.release.name) {
def manifestParser = new DefaultManifestParser()
def String versionName = manifestParser.getVersionName((File) android.sourceSets.main.manifest.srcFile)
fileName = "App-release-v${versionName}.apk"
} else { //etc }
def File file = output.outputFile
output.outputFile = new File(
file.parent,
fileName
)
}
}
release {
//etc
}
}