What is the right way to define versionName as ext variable in Android build.gradle?

流过昼夜 提交于 2019-12-07 17:53:57

问题


I tried to define versionName as an ext variable to be used in my gradle configuration file app/build.gradle.

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

It seemed work fine. However my android code failed to retrieve the versionName as following

PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pi.versionName;  // return null

I think I had not use the gradle in the right way. Any help would be appriciated.


回答1:


This is how to set a global variable in Gradle. Use this instead of ext {}

project.ext.set("versionCode", 19)
project.ext.set("versionName", "1.2.3")

Then in your defaultConfig

versionCode project.versionCode
versionName project.versionName


来源:https://stackoverflow.com/questions/29597368/what-is-the-right-way-to-define-versionname-as-ext-variable-in-android-build-gra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!