# read Gradle properties from local properties --- ## *在使用API的時候,通常會需要註冊一組api_key,或是一些密碼...之類的資訊,但如果專案有需要上傳到開源平台,如gitHub,就有暴露風險,* ## 那該怎麼做呢? 有兩種做法 1. ### **寫在gradle.properties裡面** ### 下面例子在開發階段[debug模式]導入googleMap API的key ### 並在gradle.properties裡面新增GoogleMapKey=xxxxxxxxxx(你的key) ### 最後記得把gradle.properties加入.gitignore ```kotlin= buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } debug{ resValue ("string", "API_KEY", GoogleMapKey) } } ``` ### 然後再google_maps_api.xml引用 ```kotlin= <resources> <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">@string/API_KEY</string> </resources> ``` 2. ### **寫在local.properties裡面** ### 首先在local.properties裡面定義要傳遞的key或任何包含私人key的資訊 ```kotlin= //local.properties GoogleMapKey=xxxxxxxxxx(你的key) ``` ### 然後再build.properties新增 ### 記得把local.properties加入.gitignore ```kotlin= buildTypes { Properties properties = new Properties() properties.load(project.rootProject.file('local.properties').newDataInputStream()) def googleMapKey = properties.getProperty('GoogleMapKey') debug { buildConfigField ("String", "API_KEY", googleMapKey) //在kt file讀取,透過BuildConfig.(變數名,這個例子就是API_KEY) resValue ("string", "API_KEY", googleMapKey) //在xml引用的寫法 ``` [參考資料] [gradle導入方法](https://www.tanelikorri.com/tutorial/android/set-variables-in-build-gradle/) [local.properties導入方法](https://medium.com/@waynechen323/%E5%A6%82%E4%BD%95%E5%BE%9E-local-properties-build-gradle-%E8%AE%80%E5%8F%96%E5%AE%9A%E7%BE%A9%E7%9A%84%E5%B1%AC%E6%80%A7-e19aa8a8c12b) ###### tags: `Gradle` `kotlin` `Android`