我在build.gradle的android标签中有以下内容,以便增加versionCode:
apply plugin: 'com.android.library'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
List<String> runTasks = gradle.startParameter.getTaskNames();
def value = 0
for (String item : runTasks)
if (item.contains("packageReleaseJar")) {
value = 1;
}
def code = versionProps['VERSION_CODE'].toInteger() + value
versionProps['VERSION_CODE'] = code.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
minSdkVersion 8
targetSdkVersion 22
versionCode code
versionName version
testApplicationId 'se.android.instrumenttest'
testInstrumentationRunner 'se.android.Runner'
printf("\n--------" + "VERSION DATA--------"
+ "\n" + "- CODE: " + versionCode + "\n" +
"- NAME: " + versionName + "\n----------------------------\n")
}
} else {
throw new GradleException("Could not read version.properties!")
}
从commonsguy sample获取的想法。
我希望当我使用Gradle包装器执行packageReleaseJar
任务时,versionCode增加1。但它没有按预期工作。
我想这可能与generateReleaseBuildConfig
任务有关。
可能是什么原因以及解决方案是什么?
附加物
def getVersionCode() {
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def code = versionProps['VERSION_CODE'].toInteger()
} else {
throw new GradleException("Could not read version.properties!")
}
return code
}
此方法未按预期工作,但在android标记中使用方法逻辑时,问题将得到解决:
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def code = versionProps['VERSION_CODE'].toInteger()
defaultConfig {
minSdkVersion 8
targetSdkVersion 22
versionCode code
versionName version
testApplicationId 'se.android.instrumenttest'
testInstrumentationRunner 'se.android.Runner'
printf("\n--------" + "VERSION DATA--------\n" +
"- CODE: " + versionCode + "\n" +
"- NAME: " + versionName +
"\n----------------------------\n")
}
} else {
throw new GradleException("Could not read version.properties!")
}