Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have different build environments for android?

Tags:

android

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?

like image 664
hunterp Avatar asked Jun 01 '11 04:06

hunterp


People also ask

What are build variants in Android?

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.

Where is build variants in Android Studio?

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.

How do I add Flavours to my Android?

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.


1 Answers

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.
  }
}
like image 70
Aleadam Avatar answered Nov 15 '22 21:11

Aleadam