0

my ApiResources.java look like this

package com.example.utils;

import com.example.R;

public class ApiResources {

    public static String adStatus="0",adMobBannerId="null", adMobInterstitialId="null", adMobPublisherId="null";


    String URL = "http://example/api/";

    String API_SECRECT_KEY = "api_secret_key=1kkzczxc8fny1fagc";
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • _[What's the difference between JavaScript and Java?](https://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java)_ – Luca Kiebel Aug 05 '19 at 09:38

1 Answers1

3

Step 1: Defining your key outside source code

Place the below line in your user-level gradle.properties file.

MyAwesomeApp_ApiKey="your-api-key-goes-here"

I prefer to use this format <Project Name>_<Key Property Name> so that I don’t mix up keys for different projects by mistake.

Step 2: Importing the key in your project

  • Open your module-level build.gradle file (usually the one where you define dependencies for your app).
  • Add your property in each of your build types.
  • If you want to access the key from Java, then add it as a buildConfigField.
  • If you want to access the key in your XML files (layouts and other resources), then add it as a resValue.

After doing that your build.gradle might look like this

buildTypes {
  debug {
    buildConfigField 'String', "ApiKey", MyAwesomeApp_ApiKey
    resValue 'string', "api_key", MyAwesomeApp_ApiKey
  }
  release {
    minifyEnabled false
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    buildConfigField 'String', "ApiKey", MyAwesomeApp_ApiKey
    resValue 'string', "api_key", MyAwesomeApp_ApiKey
  }
}

Step 3: Using the key in your app's code

  • In Java now you can simply replace all your uses of API_SECRET_KEY with BuildConfig.ApiKey.
  • In XML, you can refer to the key using @string/api_key.
VarunBarad
  • 376
  • 3
  • 8