How to Hide & Protect API Keys in Your Android App.
- Get a Maps API key.
- Create a file in the root directory of your project called secure.properties (this file should NOT be under version control to protect your API key)
- Add a single line to secure.properties that looks like: API_KEY=YOUR_API_KEY, where YOUR_API_KEY is the API key you obtained in the first step.
- Put following code into your module build.gradle file:
android { ... defaultConfig { ... def secureProps = new Properties() def securePropsFile = rootProject.file("secure.properties") if (securePropsFile.exists()) secureProps.load(new FileInputStream(securePropsFile)) resValue "string", "api_key", (secureProps.getProperty("API_KEY") ?: "") ...
- Use api_key in your Manifest:
<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/api_key" />
- Your API KEY can be accessed at runtime using the statement: getString(R.string.api_key)
- Build and run
No comments:
Post a Comment