access Properties file located in app folder in src file in android

人盡茶涼 提交于 2019-12-13 19:42:19

问题


I want to access a property file from a module root, but failed to find any suitable example to access the property file as many only tells how to access from asset in android. My app structure is as follows,

├── app
│   ├── key.properties  <--It is my property file, which contains app keys,to be used in app 
│   └── src             <-- Here i want to access the key.properties to access some keys 
├── build.gradle
├── gradle
├── gradlew
├── gradlew.bat
├── settings.gradle
└── local.properties

回答1:


Mike M is correct in that you should use gitignore to hide your file from git so it won't be pushed on your repository.

To expand a bit on this, here's a solution to have gradle load your properties during the build, and make them available to your app via BuildConfig.

1/ app/build.gradle

Before the android { ... } plugin, add:

Properties props = new Properties()
try {
    props.load(file('keys.properties').newDataInputStream())
} catch (Exception ex) {
    throw new GradleException("Missing keys.properties file.");
}

2/ app/build.gradle

In your buildTypes config, add

buildTypes {
    debug {
        buildConfigField "String", "KEY_MY_PROP", "\"${props.getProperty("myPropKey")}\""
    }
    release {
        buildConfigField "String", "KEY_MY_PROP", "\"${props.getProperty("myPropKey")}\""
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

3/ Any class in your app

Your key is accessible as BuildConfig.KEY_MY_PROP



来源:https://stackoverflow.com/questions/35081348/access-properties-file-located-in-app-folder-in-src-file-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!