Saving the API Key in gradle.properties

前端 未结 2 925
栀梦
栀梦 2020-12-13 04:50

I am new to android and working on a project where I see that the API key that I got is saved in gradle.properties as :

MyOpenWeatherMapApiKey=\"1

相关标签:
2条回答
  • 2020-12-13 05:02

    Refer - Complete implementation for storing API_KEY in gradle properties to avoid uploading to Github.

    https://richardroseblog.wordpress.com/2016/05/29/hiding-secret-api-keys-from-git/


    1. Add /gradle.properties into gitignore file.
    2. Add line in Gradle.properties file API_KEY = "CopyYourAPI_KEYhere"
    3. Add below line in app:build.gradle within the defaultConfig

      buildConfigField("String", "API_KEY", API_KEY)

    4. Use Key using the following statement

      String API_KEY = BuildConfig.API_KEY;

    Copy this wherever you need API_KEY

    It will save your efforts to add and remove API_KEY while committing code in Github.

    0 讨论(0)
  • 2020-12-13 05:20
    1. The idea of this indirection is to allow you to store API key in files that are not uploaded to the version control: gradle.properties is a local file and should not be stored under the version control, and BuildConfig is a generated class, so it will only be created at build time. It's definitely easier to store the API key somewhere as a plain String, but then you'll have to commit it to the repo.
    2. During build time, Gradle will generate the BuildConfig file to store some build-related constants. You can use buildConfigField command to instruct Gradle to add custom fields into BuildConfig. After the project is built, you can reference these constants inside your source code.
    0 讨论(0)
提交回复
热议问题