I encountered a similar problem, but did not want to modify the versionName to include the git hash. We wanted to keep that as something like 1.2.2, but still have the possibility of displaying the git hash in the UI.
I modified the code from the other answer here to use the buildConfigField task to generate a BuildConfig.GitHash value that can be referenced in the Java code.
Add this above the android
section of your module's build.gradle file:
def getGitHash = { ->
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-parse', '--short', 'HEAD'
standardOutput = stdout
}
return stdout.toString().trim()
}
Then add the following line to the defaultConfig
section of the android
section of the build.gradle, i.e. below versionName
:
buildConfigField "String", "GitHash", ""${getGitHash()}""
This generates the following line in the auto-generated BuildConfig.java file:
// Fields from default config.
public static final String GitHash = "e61af97";
Now you can get the git hash in your Java code with BuildConfig.GitHash
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…