Issue
I have some passwords and API keys for my app that I need to use.
For other development environments I've used, we would make a .env file, put all of our sensitive data in there, save that .env file to a password manager, and then let developers know to pull it down to start a project, and have the project read the .env file into the application for use. The .env file is never committed to the repository and is set to have git ignore it.
What's the best way to do this in Android development using Java?
Solution
You can create a properties file, put in under your app's folder and add it to .gitignore:
Example of content of a properties file called passwords.properties:
password1=123456
password2=qwerty
Under the plugin declaration in your build.gradle file, import the properties file and load it into a Properties object.
def passwordsPropertiesFile = rootProject.file("app/passwords.properties")
def passwordsProperties = new Properties()
passwordsProperties.load(new FileInputStream(passwordsPropertiesFile))
And in order to get a value use it inside your gradle file use:
passwordsProperties['password1']
If you need the values inside your application code, you can add the values to the BuildConfig either under the defaultConfig:
defaultConfig {
applicationId "some.app.id"
minSdkVersion 21
targetSdkVersion 30
...
buildConfigField "String", "PASSWORD1", passwordsProperties['password1']
}
Or add it for a specific build type by setting the BuildConfig variable under buildTypes section:
buildTypes {
debug {
buildConfigField "String", "PASSWORD1", passwordsProperties['debug_password1']
}
prod {
buildConfigField "String", "PASSWORD1", passwordsProperties['prod_password1']
}
}
To use the value in your application code use:
BuildConfig.PASSWORD1
Answered By - gioravered
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.