如何在Android Studio中运行时获取构build变体?

我想在运行时获得构build变体,这可能没有任何额外的configuration或代码?

Solutions Collecting From Web of "如何在Android Studio中运行时获取构build变体?"

看看生成的BuildConfig类。

 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 = ""; } 

你可以试试

 getPackageName(); 

它会返回你在build.gradle中定义的内容

 productFlavours{ flavour1{ applicationId 'com.example.package.flavour1' } flavour2{ applicationId 'com.example.package.flavour2' } } 

另一个select是为每个构build变体创build一个单独的构buildconfigurationvariables,并在代码中使用它,如下所示:

在你的build.gradle文件中:

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

要在你的代码中使用它:

 if (BuildConfig.BUILD_VARIANT.equals("prod")){ // do something cool }