如何在Kotlin中获取当前的构建变体

3

我在我的Android项目中有几个构建变体。

如何在Kotlin代码中检查正在编译的变体?我想要像这样进行条件判断:如果是本地变体,则执行此操作;否则,如果是远程变体,则执行其他操作...

例如,可以使用以下方式:

// kotlin code:
if (build.variant=="local") {
...
}
else
{
...
}
1个回答

4
在构建时,Gradle 会生成 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 = "";
}

您也可以根据自己的需求定义自定义变量:
android {
  ...
  buildTypes {
    release {
      // These values are defined only for the release build, which
      // is typically used for full builds and continuous builds.
      buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"")
      resValue("string", "build_time", "${minutesSinceEpoch}")
      ...
    }
    debug {
      // Use static values for incremental builds to ensure that
      // resource files and BuildConfig aren't rebuilt with each run.
      // If they were dynamic, they would prevent certain benefits of
      // Instant Run as well as Gradle UP-TO-DATE checks.
      buildConfigField("String", "BUILD_TIME", "\"0\"")
      resValue("string", "build_time", "0")
    }
  }
}

并且要使用它:

Log.i(TAG, BuildConfig.BUILD_TIME)
Log.i(TAG, getString(R.string.build_time))

更多信息请参考。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接