Android:Gradle:通过自定义任务更改versionCode

时间:2017-11-02 10:40:17

标签: android gradle

这是我的app / build.gradle

constructor(props){
   super(props);
   this.state = { myObject: {} };
}

componentDidMount(){
  //your API request here
  .then(response => response.json().then(result => {
     this.setState({ myObject: result });
  }))
  .catch((err) => { throw err; });
}

render(){
  return (
    <Container>
      <Header />
      <Content>
        <Card>  
          <CardItem>             
            <Left>
              <Thumbnail source={{uri: 'https://openclipart.org/image/2400px/svg_to_png/177482/ProfilePlaceholderSuit.png'}} />
              <Body>
                <Text>Email:</Text>
                <Text>{this.state.myObject.Email}</Text>
                <Text>Name:</Text>
                <Text>{this.state.myObject.Name}</Text>
                <Text>Surname:</Text>
                <Text>{this.state.myObject.Surname}</Text>
                <Text>ID Number:</Text>
                <Text>{this.state.myObject.IdNumber}</Text>
              </Body>
            </Left>
          </CardItem>
        </Card>            
      </Content>
    </Container>
  );
}

我需要在运行任务android { compileSdkVersion 26 buildToolsVersion "26.0.2" defaultConfig { applicationId "com.myproject.android" minSdkVersion 15 targetSdkVersion 26 versionCode 3 versionName "1.2.3" } } 之前增加 versionCode 。 所以,如果我理解正确,我需要编写增量 versionCode 的自定义Gradle任务。我是对的吗?

是否可以执行此任务?

1 个答案:

答案 0 :(得分:1)

是的,有可能。将版本代码存储在某处。例如,在您的应用模块文件夹下创建一个version.properties文件,将以下内容添加到其中:

VERSION_CODE=28

在您的应用模块文件夹下创建Gradle文件,例如devops.gradle并添加以下内容:

ext.getIncrementedVersionCode = {
    List<String> runTasks = gradle.startParameter.getTaskNames();
    def code = 1
    def versionPropsFile = file("$projectDir/version.properties")

    // get the old version code
    if (versionPropsFile.canRead()) {
        Properties versionProps = new Properties()
        versionProps.load(new FileInputStream(versionPropsFile))
        code = versionProps['VERSION_CODE'].toInteger()
        println "available version code = " + code

        for (String item : runTasks) {
            //TODO your gradle task comes here which will be executed
            if (item.contains("assembeDebug")) {
                println "Doing intermediate release.. incrementing the version code"
                code = code + 1
                versionProps['VERSION_CODE'] = code.toString()
                versionProps.store(versionPropsFile.newWriter(), null)
                println "new version code= " + code
            }
        }
    } else {
        throw new GradleException("Could not read version.properties!")
    }
    return code
}

然后按以下方式更改您的build.gradle(应用程序):

...
apply from: 'devops.gradle'

android {
        ...
        defaultConfig {
            ...
            def yourVersionCode = getIncrementedVersionCode()
            versionCode yourVersionCode
           ...
        }

现在,无论何时运行gradlew assembleDebug,您的版本代码都会自动递增。