How to get the build variant at runtime in Android

2019-01-23 10:41发布

I'd like to get the build variant during runtime, is this possible without any extra config or code?

3条回答
你好瞎i
2楼-- · 2019-01-23 10:47

Look at the generated BuildConfig class.

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLCATION_ID = "com.example.app";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "";
}
查看更多
放我归山
3楼-- · 2019-01-23 10:53

You can try with

getPackageName(); 

it will return what you've defined in build.gradle

productFlavours{
  flavour1{
     applicationId 'com.example.package.flavour1'
  }
  flavour2{
     applicationId 'com.example.package.flavour2'
  }
}
查看更多
SAY GOODBYE
4楼-- · 2019-01-23 10:58

Another option would be to create a separate build config variable for each build variant and use it in your code like this:

In your build.gradle file:

productFlavors {

    production {
        buildConfigField "String", "BUILD_VARIANT", "\"prod\""
    }

    dev {
        buildConfigField "String", "BUILD_VARIANT", "\"dev\""
    }       
}

To use it in your code:

if (BuildConfig.BUILD_VARIANT.equals("prod")){ // do something cool }
查看更多
登录 后发表回答