在Android build.gradle中将versionName定义为ext变量的正确方法是什么?

fir*_*ear 3 android task gradle build.gradle

我尝试将versionName定义为要在我的gradle配置文件app/build.gradle中使用的ext变量.

ext {
    versionCode = 19
    versionName = "1.2.3"
    ...
}
...
android {
    ...
    defaultConfig {
        ...
        versionCode versionCode
        versionName versionName
    }
    ...
}
...
task updateReleaseMetadata(type:Exec) {
    commandLine 'sh'
    args "MyShellScript.sh", versionName
}
...
Run Code Online (Sandbox Code Playgroud)

看起来工作得很好.但是我的android代码无法检索versionName,如下所示

PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pi.versionName;  // return null
Run Code Online (Sandbox Code Playgroud)

我想我没有以正确的方式使用gradle.任何帮助都会得到满足.

Chr*_*lla 11

这是在Gradle中设置全局变量的方法.使用此代替ext {}

project.ext.set("versionCode", 19)
project.ext.set("versionName", "1.2.3")
Run Code Online (Sandbox Code Playgroud)

然后在你的defaultConfig中

versionCode project.versionCode
versionName project.versionName
Run Code Online (Sandbox Code Playgroud)