How to use API KEY in the Adnroid app

How to Hide & Protect API Keys in Your Android App.

  1. Get a Maps API key.
  2. 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)
  3. 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.
  4. 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") ?: "")
        ...
  5. Use api_key in your Manifest:
    <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="@string/api_key" />
  6. Your API KEY can be accessed at runtime using the statement: getString(R.string.api_key)
  7. Build and run

No comments:

Post a Comment

Why BQ28Z610 function Current() returns 0 mA

Fixing 0 mA Current Readings on the BQ28Z610 Device Custom driver for the BQ28Z610 device was connected directly via I2C. It is p...