Try   HackMD

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

buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } debug{ resValue ("string", "API_KEY", GoogleMapKey) } }

然後再google_maps_api.xml引用

<resources> <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">@string/API_KEY</string> </resources>
  1. 寫在local.properties裡面

    首先在local.properties裡面定義要傳遞的key或任何包含私人key的資訊

//local.properties GoogleMapKey=xxxxxxxxxx(你的key)

然後再build.properties新增

記得把local.properties加入.gitignore

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導入方法
local.properties導入方法

tags: Gradle kotlin Android