Skip to content

Instantly share code, notes, and snippets.

@vmlinz
Last active March 18, 2016 11:14
Show Gist options
  • Save vmlinz/d4d6d6c67302048def32 to your computer and use it in GitHub Desktop.
Save vmlinz/d4d6d6c67302048def32 to your computer and use it in GitHub Desktop.
Using local.properties file to store sensitive information in Android projects

问题

我们常常需要在Android工程里面放一些比较敏感的信息,比如某些三方服务的API Key之类的信息。但是设置到工程中每次手工修改代码又很麻烦,于是我查看了一些资料,实现了在local.properties这个文件中保存敏感信息。同时因为local.properties这个文件默认被gitignore了,相对来说还是比较安全。

操作方法

在工程根目录的local.properties里面填入你想保存的敏感信息

比如MyTMDBApiKey=xxxx

在项目的工程目录(比如app)里面找到build.gradle

找到android.buildTypes,在这个后面加上

    buildTypes.each {
        Properties properties = new Properties()
        properties.load(project.rootProject.file('local.properties').newDataInputStream())
        def myTMDBApiKey = properties.getProperty('MyTMDBApiKey')
        it.buildConfigField 'String', 'TMDB_API_KEY', myTMDBApiKey
    }

然后就可以在工程中通过BuildConfig.TMDB_API_KEY访问到该敏感数据了。

这个让人纠结的问题就可以这样被解决了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment