I have dozens of api keys to facebook and twitter and many other services, what is the standard way to have different values for the keys depending on if I am making a development build vs. a staging build vs. a production build?
Build variants are the result of Gradle using a specific set of rules to combine settings, code, and resources configured in your build types and product flavors. Although you do not configure build variants directly, you do configure the build types and product flavors that form them.
To change the build variant Android Studio uses, select Build > Select Build Variant in the menu bar. For projects without native/C++ code, the Build Variants panel has two columns: Module and Active Build Variant.
Now you have three different flavors of the same application to change the build variant, Android Studio uses select Build > select Build Variant in the menu bar (or click Build Variants within the windows bar), then select a build variant from the menu.
You can use a static flag to use it in a switch block to define your keys. That works for a simple project with two or three alternative keys.
If you really have that many, to use in several projects, I suggest you to add them to a helper class, so you minimise the code changing in your classes. Something like:
public class BuildHelper {
public static final int DEBUG=0;
public static final int STAGING=1;
public static final int PRODUCTION=2;
public static int BUILD;
public static String getFbKey() {
switch(BUILD) {
case DEBUG: return "xxx";
case STAGING: return "yyy";
case PRODUCTION: return "zzz";
}
return null;
}
public static String getTwitterKey() {
switch(BUILD) {
case DEBUG: return "xxx";
case STAGING: return "yyy";
case PRODUCTION: return "zzz";
}
return null;
}
}
and use it as:
public class YourClass extends Activity {
public static String FB_KEY;
public static String TWITTER_KEY;
//etc.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BuildHelper.BUILD=BuildHelper.DEBUG; // or STAGING or PRODUCTION
FB_KEY = BuildHelper.getFbKey();
TWITTER_KEY = BuildHelper.getTwitterKey();
//etc.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With