Posted at

Android build時にapkにcommitHashを埋め込んでアプリ上で確認する

自分用メモ

/app/build.gradle

//commit hash 取得

def getCommitHasH() {
def process = "git rev-parse --short HEAD".execute()
process.waitFor()
(process.exitValue() == 0) ? process.text.trim() : ""
}

android {
defaultConfig {
// BuildConfig へ埋め込み
buildConfigField("String", "COMMIT_HASH", "\"" + getCommitHasH() + "\"")
}
}

kotlinで表示制御する場合

HogeActivity.kt

//debugビルドなら表示する

if(BuildConfig.DEBUG){
commitHashText.text = BuildConfig.COMMIT_HASH
commitHashText.visibility = View.VISIBLE
}else{
commitHashText.visibility = View.GONE
}

layoutxmlで表示制御する場合

<!-- import BuildConfig -->

<data>
<import type="com.hoge.BuildConfig"/>
</data>

<!-- Data binding -->
<TextView
tools:text="@{BuildConfig.COMMIT_HASH}"
android:visibility="@{BuildConfig.DEBUG ? View.VISIBLE : View.GONE}"
/>

ref

- https://gist.github.com/kappa-lab/fd8650dfcc2f780055255fa982e82473

- https://qiita.com/kawachi/items/d97c448b013c37f2f198