7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Android開発でAPIキーを隠蔽してGitHubに上げる

Posted at

この記事の目的

Android開発でWebAPIを利用する場合に、APIキーをGitのコミットログに含めずに扱う方法を紹介する。

手順

gradle.propertiesにAPIキーを記述

APIキーを記述

myApiKey=3a6...534

記述したAPIキーがgitの管理化に載らないよう、gradle.propertiesを.gitignoreに含めておく。

一度gitにgradle.propertiesを上げたことがある場合は、キャッシュを削除してからコミットする

BuildConfigの作成

app/build.gradleにbuildConfigFieldを定義、

android {
    defaultConfig {
        buildConfigField "String", "API_KEY", "\"${project.property("myApiKey")}\""
    }
}

ビルドするとBuildConfig.javaに追加されている

public final class BuildConfig {
  ...
  public static final String API_KEY = "3a6...534";
}

APIキーの取得

BuildConfig.MY_API_KEYでキーの文字列を取得

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        Log.i("MYTAG", BuildConfig.MY_API_KEY)
    }
}
7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?