LoginSignup
14
9

More than 5 years have passed since last update.

ビルド時の git commit id をAndroid プログラムに埋め込む

Last updated at Posted at 2016-12-14

Android アプリを作っていて、ビルドしたソースコードを特定したいときに git の commit が参照できたらいいですよね。

// git describe を実行して結果を取得
def getRevision() {
    def proc = "git describe --dirty --always --tags".execute()
    proc.waitFor()
    (proc.exitValue() == 0) ? proc.text.trim() : ""
}

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

Android の gradle plugin には BuildConfig クラスに static フィールドを追加する buildConfigField が用意されており、 build.gradle は groovy なので単に外部コマンドを実行することで実現できます。便利。

コード中からは次のように参照できます。

String revision = BuildConfig.REVISION; // ← あなたのパッケージの BuildConfig
14
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
9